repository_name
stringclasses 316
values | func_path_in_repository
stringlengths 6
223
| func_name
stringlengths 1
134
| language
stringclasses 1
value | func_code_string
stringlengths 57
65.5k
| func_documentation_string
stringlengths 1
46.3k
| split_name
stringclasses 1
value | func_code_url
stringlengths 91
315
| called_functions
listlengths 1
156
⌀ | enclosing_scope
stringlengths 2
1.48M
|
|---|---|---|---|---|---|---|---|---|---|
saltstack/salt
|
salt/modules/purefb.py
|
_get_snapshot
|
python
|
def _get_snapshot(name, suffix, blade):
'''
Return name of Snapshot
or None
'''
try:
filt = 'source=\'{}\' and suffix=\'{}\''.format(name, suffix)
res = blade.file_system_snapshots.list_file_system_snapshots(filter=filt)
return res.items[0]
except rest.ApiException:
return None
|
Return name of Snapshot
or None
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/purefb.py#L140-L150
| null |
# -*- coding: utf-8 -*-
##
# Copyright 2018 Pure Storage Inc
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an 'AS IS' BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
'''
Management of Pure Storage FlashBlade
Installation Prerequisites
--------------------------
- You will need the ``purity_fb`` python package in your python installation
path that is running salt.
.. code-block:: bash
pip install purity_fb
- Configure Pure Storage FlashBlade authentication. Use one of the following
three methods.
1) From the minion config
.. code-block:: yaml
pure_tags:
fb:
san_ip: management vip or hostname for the FlashBlade
api_token: A valid api token for the FlashBlade being managed
2) From environment (PUREFB_IP and PUREFB_API)
3) From the pillar (PUREFB_IP and PUREFB_API)
:maintainer: Simon Dodsley (simon@purestorage.com)
:maturity: new
:requires: purity_fb
:platform: all
.. versionadded:: 2019.2.0
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
from datetime import datetime
# Import Salt libs
from salt.ext import six
from salt.exceptions import CommandExecutionError
# Import 3rd party modules
try:
from purity_fb import PurityFb, FileSystem, FileSystemSnapshot, SnapshotSuffix
from purity_fb import rest, NfsRule, ProtocolRule
HAS_PURITY_FB = True
except ImportError:
HAS_PURITY_FB = False
__docformat__ = 'restructuredtext en'
__virtualname__ = 'purefb'
def __virtual__():
'''
Determine whether or not to load this module
'''
if HAS_PURITY_FB:
return __virtualname__
return (False, 'purefb execution module not loaded: purity_fb python library not available.')
def _get_blade():
'''
Get Pure Storage FlasBlade configuration
1) From the minion config
pure_tags:
fb:
san_ip: management vip or hostname for the FlashBlade
api_token: A valid api token for the FlashBlade being managed
2) From environment (PUREFB_IP and PUREFB_API)
3) From the pillar (PUREFB_IP and PUREFB_API)
'''
try:
blade_name = __opts__['pure_tags']['fb'].get('san_ip')
api_token = __opts__['pure_tags']['fb'].get('api_token')
if blade_name and api:
blade = PurityFb(blade_name)
blade.disable_verify_ssl()
except (KeyError, NameError, TypeError):
try:
blade_name = os.environ.get('PUREFB_IP')
api_token = os.environ.get('PUREFB_API')
if blade_name:
blade = PurityFb(blade_name)
blade.disable_verify_ssl()
except (ValueError, KeyError, NameError):
try:
api_token = __pillar__['PUREFB_API']
blade = PurityFb(__pillar__['PUREFB_IP'])
blade.disable_verify_ssl()
except (KeyError, NameError):
raise CommandExecutionError('No Pure Storage FlashBlade credentials found.')
try:
blade.login(api_token)
except Exception:
raise CommandExecutionError('Pure Storage FlashBlade authentication failed.')
return blade
def _get_fs(name, blade):
'''
Private function to
check for existance of a filesystem
'''
_fs = []
_fs.append(name)
try:
res = blade.file_systems.list_file_systems(names=_fs)
return res.items[0]
except rest.ApiException:
return None
def _get_deleted_fs(name, blade):
'''
Private function to check
if a file systeem has already been deleted
'''
try:
_fs = _get_fs(name, blade)
if _fs and _fs.destroyed:
return _fs
except rest.ApiException:
return None
def snap_create(name, suffix=None):
'''
Create a filesystem snapshot on a Pure Storage FlashBlade.
Will return False if filesystem selected to snap does not exist.
.. versionadded:: 2019.2.0
name : string
name of filesystem to snapshot
suffix : string
if specificed forces snapshot name suffix. If not specified defaults to timestamp.
CLI Example:
.. code-block:: bash
salt '*' purefb.snap_create foo
salt '*' purefb.snap_create foo suffix=bar
'''
blade = _get_blade()
if suffix is None:
suffix = ('snap-' +
six.text_type((datetime.utcnow() -
datetime(1970, 1, 1, 0, 0, 0, 0)).total_seconds()))
suffix = suffix.replace('.', '')
if _get_fs(name, blade) is not None:
try:
source = []
source.append(name)
blade.file_system_snapshots.create_file_system_snapshots(sources=source,
suffix=SnapshotSuffix(suffix))
return True
except rest.ApiException:
return False
else:
return False
def snap_delete(name, suffix=None, eradicate=False):
'''
Delete a filesystem snapshot on a Pure Storage FlashBlade.
Will return False if selected snapshot does not exist.
.. versionadded:: 2019.2.0
name : string
name of filesystem
suffix : string
name of snapshot
eradicate : boolean
Eradicate snapshot after deletion if True. Default is False
CLI Example:
.. code-block:: bash
salt '*' purefb.snap_delete foo suffix=snap eradicate=True
'''
blade = _get_blade()
if _get_snapshot(name, suffix, blade) is not None:
try:
snapname = name + '.' + suffix
new_attr = FileSystemSnapshot(destroyed=True)
blade.file_system_snapshots.update_file_system_snapshots(name=snapname,
attributes=new_attr)
except rest.ApiException:
return False
if eradicate is True:
try:
blade.file_system_snapshots.delete_file_system_snapshots(name=snapname)
return True
except rest.ApiException:
return False
else:
return True
else:
return False
def snap_eradicate(name, suffix=None):
'''
Eradicate a deleted filesystem snapshot on a Pure Storage FlashBlade.
Will return False if snapshot is not in a deleted state.
.. versionadded:: 2019.2.0
name : string
name of filesystem
suffix : string
name of snapshot
CLI Example:
.. code-block:: bash
salt '*' purefb.snap_eradicate foo suffix=snap
'''
blade = _get_blade()
if _get_snapshot(name, suffix, blade) is not None:
snapname = name + '.' + suffix
try:
blade.file_system_snapshots.delete_file_system_snapshots(name=snapname)
return True
except rest.ApiException:
return False
else:
return False
def fs_create(name, size=None, proto='NFS', nfs_rules='*(rw,no_root_squash)', snapshot=False):
'''
Create a filesystem on a Pure Storage FlashBlade.
Will return False if filesystem already exists.
.. versionadded:: 2019.2.0
name : string
name of filesystem (truncated to 63 characters)
proto : string
(Optional) Sharing protocol (NFS, CIFS or HTTP). If not specified default is NFS
snapshot: boolean
(Optional) Are snapshots enabled on the filesystem. Default is False
nfs_rules : string
(Optional) export rules for NFS. If not specified default is
``*(rw,no_root_squash)``. Refer to Pure Storage documentation for
formatting rules.
size : string
if specified capacity of filesystem. If not specified default to 32G.
Refer to Pure Storage documentation for formatting rules.
CLI Example:
.. code-block:: bash
salt '*' purefb.fs_create foo proto=CIFS
salt '*' purefb.fs_create foo size=10T
'''
if len(name) > 63:
name = name[0:63]
blade = _get_blade()
print(proto)
if _get_fs(name, blade) is None:
if size is None:
size = __utils__['stringutils.human_to_bytes']('32G')
else:
size = __utils__['stringutils.human_to_bytes'](size)
if proto.lower() == 'nfs':
fs_obj = FileSystem(name=name,
provisioned=size,
fast_remove_directory_enabled=True,
snapshot_directory_enabled=snapshot,
nfs=NfsRule(enabled=True, rules=nfs_rules),
)
elif proto.lower() == 'cifs':
fs_obj = FileSystem(name=name,
provisioned=size,
fast_remove_directory_enabled=True,
snapshot_directory_enabled=snapshot,
smb=ProtocolRule(enabled=True),
)
elif proto.lower() == 'http':
fs_obj = FileSystem(name=name,
provisioned=size,
fast_remove_directory_enabled=True,
snapshot_directory_enabled=snapshot,
http=ProtocolRule(enabled=True),
)
else:
return False
try:
blade.file_systems.create_file_systems(fs_obj)
return True
except rest.ApiException:
return False
else:
return False
def fs_delete(name, eradicate=False):
'''
Delete a share on a Pure Storage FlashBlade.
Will return False if filesystem doesn't exist or is already in a deleted state.
.. versionadded:: 2019.2.0
name : string
name of filesystem
eradicate : boolean
(Optional) Eradicate filesystem after deletion if True. Default is False
CLI Example:
.. code-block:: bash
salt '*' purefb.fs_delete foo eradicate=True
'''
blade = _get_blade()
if _get_fs(name, blade) is not None:
try:
blade.file_systems.update_file_systems(name=name,
attributes=FileSystem(nfs=NfsRule(enabled=False),
smb=ProtocolRule(enabled=False),
http=ProtocolRule(enabled=False),
destroyed=True)
)
except rest.ApiException:
return False
if eradicate is True:
try:
blade.file_systems.delete_file_systems(name)
return True
except rest.ApiException:
return False
else:
return True
else:
return False
def fs_eradicate(name):
'''
Eradicate a deleted filesystem on a Pure Storage FlashBlade.
Will return False is filesystem is not in a deleted state.
.. versionadded:: 2019.2.0
name : string
name of filesystem
CLI Example:
.. code-block:: bash
salt '*' purefb.fs_eradicate foo
'''
blade = _get_blade()
if _get_deleted_fs(name, blade) is not None:
try:
blade.file_systems.delete_file_systems(name)
return True
except rest.ApiException:
return False
else:
return False
def fs_extend(name, size):
'''
Resize an existing filesystem on a Pure Storage FlashBlade.
Will return False if new size is less than or equal to existing size.
.. versionadded:: 2019.2.0
name : string
name of filesystem
size : string
New capacity of filesystem.
Refer to Pure Storage documentation for formatting rules.
CLI Example:
.. code-block:: bash
salt '*' purefb.fs_extend foo 10T
'''
attr = {}
blade = _get_blade()
_fs = _get_fs(name, blade)
if _fs is not None:
if __utils__['stringutils.human_to_bytes'](size) > _fs.provisioned:
try:
attr['provisioned'] = __utils__['stringutils.human_to_bytes'](size)
n_attr = FileSystem(**attr)
blade.file_systems.update_file_systems(name=name, attributes=n_attr)
return True
except rest.ApiException:
return False
else:
return False
else:
return False
def fs_update(name, rules, snapshot=False):
'''
Update filesystem on a Pure Storage FlashBlade.
Allows for change of NFS export rules and enabling/disabled
of snapshotting capability.
.. versionadded:: 2019.2.0
name : string
name of filesystem
rules : string
NFS export rules for filesystem
Refer to Pure Storage documentation for formatting rules.
snapshot: boolean
(Optional) Enable/Disable snapshots on the filesystem. Default is False
CLI Example:
.. code-block:: bash
salt '*' purefb.fs_nfs_update foo rules='10.234.112.23(ro), 10.234.112.24(rw)' snapshot=True
'''
blade = _get_blade()
attr = {}
_fs = _get_fs(name, blade)
if _fs is not None:
try:
if _fs.nfs.enabled:
attr['nfs'] = NfsRule(rules=rules)
attr['snapshot_directory_enabled'] = snapshot
n_attr = FileSystem(**attr)
blade.file_systems.update_file_systems(name=name, attributes=n_attr)
return True
except rest.ApiException:
return False
else:
return False
|
saltstack/salt
|
salt/modules/purefb.py
|
_get_deleted_fs
|
python
|
def _get_deleted_fs(name, blade):
'''
Private function to check
if a file systeem has already been deleted
'''
try:
_fs = _get_fs(name, blade)
if _fs and _fs.destroyed:
return _fs
except rest.ApiException:
return None
|
Private function to check
if a file systeem has already been deleted
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/purefb.py#L153-L163
|
[
"def _get_fs(name, blade):\n '''\n Private function to\n check for existance of a filesystem\n '''\n _fs = []\n _fs.append(name)\n try:\n res = blade.file_systems.list_file_systems(names=_fs)\n return res.items[0]\n except rest.ApiException:\n return None\n"
] |
# -*- coding: utf-8 -*-
##
# Copyright 2018 Pure Storage Inc
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an 'AS IS' BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
'''
Management of Pure Storage FlashBlade
Installation Prerequisites
--------------------------
- You will need the ``purity_fb`` python package in your python installation
path that is running salt.
.. code-block:: bash
pip install purity_fb
- Configure Pure Storage FlashBlade authentication. Use one of the following
three methods.
1) From the minion config
.. code-block:: yaml
pure_tags:
fb:
san_ip: management vip or hostname for the FlashBlade
api_token: A valid api token for the FlashBlade being managed
2) From environment (PUREFB_IP and PUREFB_API)
3) From the pillar (PUREFB_IP and PUREFB_API)
:maintainer: Simon Dodsley (simon@purestorage.com)
:maturity: new
:requires: purity_fb
:platform: all
.. versionadded:: 2019.2.0
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
from datetime import datetime
# Import Salt libs
from salt.ext import six
from salt.exceptions import CommandExecutionError
# Import 3rd party modules
try:
from purity_fb import PurityFb, FileSystem, FileSystemSnapshot, SnapshotSuffix
from purity_fb import rest, NfsRule, ProtocolRule
HAS_PURITY_FB = True
except ImportError:
HAS_PURITY_FB = False
__docformat__ = 'restructuredtext en'
__virtualname__ = 'purefb'
def __virtual__():
'''
Determine whether or not to load this module
'''
if HAS_PURITY_FB:
return __virtualname__
return (False, 'purefb execution module not loaded: purity_fb python library not available.')
def _get_blade():
'''
Get Pure Storage FlasBlade configuration
1) From the minion config
pure_tags:
fb:
san_ip: management vip or hostname for the FlashBlade
api_token: A valid api token for the FlashBlade being managed
2) From environment (PUREFB_IP and PUREFB_API)
3) From the pillar (PUREFB_IP and PUREFB_API)
'''
try:
blade_name = __opts__['pure_tags']['fb'].get('san_ip')
api_token = __opts__['pure_tags']['fb'].get('api_token')
if blade_name and api:
blade = PurityFb(blade_name)
blade.disable_verify_ssl()
except (KeyError, NameError, TypeError):
try:
blade_name = os.environ.get('PUREFB_IP')
api_token = os.environ.get('PUREFB_API')
if blade_name:
blade = PurityFb(blade_name)
blade.disable_verify_ssl()
except (ValueError, KeyError, NameError):
try:
api_token = __pillar__['PUREFB_API']
blade = PurityFb(__pillar__['PUREFB_IP'])
blade.disable_verify_ssl()
except (KeyError, NameError):
raise CommandExecutionError('No Pure Storage FlashBlade credentials found.')
try:
blade.login(api_token)
except Exception:
raise CommandExecutionError('Pure Storage FlashBlade authentication failed.')
return blade
def _get_fs(name, blade):
'''
Private function to
check for existance of a filesystem
'''
_fs = []
_fs.append(name)
try:
res = blade.file_systems.list_file_systems(names=_fs)
return res.items[0]
except rest.ApiException:
return None
def _get_snapshot(name, suffix, blade):
'''
Return name of Snapshot
or None
'''
try:
filt = 'source=\'{}\' and suffix=\'{}\''.format(name, suffix)
res = blade.file_system_snapshots.list_file_system_snapshots(filter=filt)
return res.items[0]
except rest.ApiException:
return None
def snap_create(name, suffix=None):
'''
Create a filesystem snapshot on a Pure Storage FlashBlade.
Will return False if filesystem selected to snap does not exist.
.. versionadded:: 2019.2.0
name : string
name of filesystem to snapshot
suffix : string
if specificed forces snapshot name suffix. If not specified defaults to timestamp.
CLI Example:
.. code-block:: bash
salt '*' purefb.snap_create foo
salt '*' purefb.snap_create foo suffix=bar
'''
blade = _get_blade()
if suffix is None:
suffix = ('snap-' +
six.text_type((datetime.utcnow() -
datetime(1970, 1, 1, 0, 0, 0, 0)).total_seconds()))
suffix = suffix.replace('.', '')
if _get_fs(name, blade) is not None:
try:
source = []
source.append(name)
blade.file_system_snapshots.create_file_system_snapshots(sources=source,
suffix=SnapshotSuffix(suffix))
return True
except rest.ApiException:
return False
else:
return False
def snap_delete(name, suffix=None, eradicate=False):
'''
Delete a filesystem snapshot on a Pure Storage FlashBlade.
Will return False if selected snapshot does not exist.
.. versionadded:: 2019.2.0
name : string
name of filesystem
suffix : string
name of snapshot
eradicate : boolean
Eradicate snapshot after deletion if True. Default is False
CLI Example:
.. code-block:: bash
salt '*' purefb.snap_delete foo suffix=snap eradicate=True
'''
blade = _get_blade()
if _get_snapshot(name, suffix, blade) is not None:
try:
snapname = name + '.' + suffix
new_attr = FileSystemSnapshot(destroyed=True)
blade.file_system_snapshots.update_file_system_snapshots(name=snapname,
attributes=new_attr)
except rest.ApiException:
return False
if eradicate is True:
try:
blade.file_system_snapshots.delete_file_system_snapshots(name=snapname)
return True
except rest.ApiException:
return False
else:
return True
else:
return False
def snap_eradicate(name, suffix=None):
'''
Eradicate a deleted filesystem snapshot on a Pure Storage FlashBlade.
Will return False if snapshot is not in a deleted state.
.. versionadded:: 2019.2.0
name : string
name of filesystem
suffix : string
name of snapshot
CLI Example:
.. code-block:: bash
salt '*' purefb.snap_eradicate foo suffix=snap
'''
blade = _get_blade()
if _get_snapshot(name, suffix, blade) is not None:
snapname = name + '.' + suffix
try:
blade.file_system_snapshots.delete_file_system_snapshots(name=snapname)
return True
except rest.ApiException:
return False
else:
return False
def fs_create(name, size=None, proto='NFS', nfs_rules='*(rw,no_root_squash)', snapshot=False):
'''
Create a filesystem on a Pure Storage FlashBlade.
Will return False if filesystem already exists.
.. versionadded:: 2019.2.0
name : string
name of filesystem (truncated to 63 characters)
proto : string
(Optional) Sharing protocol (NFS, CIFS or HTTP). If not specified default is NFS
snapshot: boolean
(Optional) Are snapshots enabled on the filesystem. Default is False
nfs_rules : string
(Optional) export rules for NFS. If not specified default is
``*(rw,no_root_squash)``. Refer to Pure Storage documentation for
formatting rules.
size : string
if specified capacity of filesystem. If not specified default to 32G.
Refer to Pure Storage documentation for formatting rules.
CLI Example:
.. code-block:: bash
salt '*' purefb.fs_create foo proto=CIFS
salt '*' purefb.fs_create foo size=10T
'''
if len(name) > 63:
name = name[0:63]
blade = _get_blade()
print(proto)
if _get_fs(name, blade) is None:
if size is None:
size = __utils__['stringutils.human_to_bytes']('32G')
else:
size = __utils__['stringutils.human_to_bytes'](size)
if proto.lower() == 'nfs':
fs_obj = FileSystem(name=name,
provisioned=size,
fast_remove_directory_enabled=True,
snapshot_directory_enabled=snapshot,
nfs=NfsRule(enabled=True, rules=nfs_rules),
)
elif proto.lower() == 'cifs':
fs_obj = FileSystem(name=name,
provisioned=size,
fast_remove_directory_enabled=True,
snapshot_directory_enabled=snapshot,
smb=ProtocolRule(enabled=True),
)
elif proto.lower() == 'http':
fs_obj = FileSystem(name=name,
provisioned=size,
fast_remove_directory_enabled=True,
snapshot_directory_enabled=snapshot,
http=ProtocolRule(enabled=True),
)
else:
return False
try:
blade.file_systems.create_file_systems(fs_obj)
return True
except rest.ApiException:
return False
else:
return False
def fs_delete(name, eradicate=False):
'''
Delete a share on a Pure Storage FlashBlade.
Will return False if filesystem doesn't exist or is already in a deleted state.
.. versionadded:: 2019.2.0
name : string
name of filesystem
eradicate : boolean
(Optional) Eradicate filesystem after deletion if True. Default is False
CLI Example:
.. code-block:: bash
salt '*' purefb.fs_delete foo eradicate=True
'''
blade = _get_blade()
if _get_fs(name, blade) is not None:
try:
blade.file_systems.update_file_systems(name=name,
attributes=FileSystem(nfs=NfsRule(enabled=False),
smb=ProtocolRule(enabled=False),
http=ProtocolRule(enabled=False),
destroyed=True)
)
except rest.ApiException:
return False
if eradicate is True:
try:
blade.file_systems.delete_file_systems(name)
return True
except rest.ApiException:
return False
else:
return True
else:
return False
def fs_eradicate(name):
'''
Eradicate a deleted filesystem on a Pure Storage FlashBlade.
Will return False is filesystem is not in a deleted state.
.. versionadded:: 2019.2.0
name : string
name of filesystem
CLI Example:
.. code-block:: bash
salt '*' purefb.fs_eradicate foo
'''
blade = _get_blade()
if _get_deleted_fs(name, blade) is not None:
try:
blade.file_systems.delete_file_systems(name)
return True
except rest.ApiException:
return False
else:
return False
def fs_extend(name, size):
'''
Resize an existing filesystem on a Pure Storage FlashBlade.
Will return False if new size is less than or equal to existing size.
.. versionadded:: 2019.2.0
name : string
name of filesystem
size : string
New capacity of filesystem.
Refer to Pure Storage documentation for formatting rules.
CLI Example:
.. code-block:: bash
salt '*' purefb.fs_extend foo 10T
'''
attr = {}
blade = _get_blade()
_fs = _get_fs(name, blade)
if _fs is not None:
if __utils__['stringutils.human_to_bytes'](size) > _fs.provisioned:
try:
attr['provisioned'] = __utils__['stringutils.human_to_bytes'](size)
n_attr = FileSystem(**attr)
blade.file_systems.update_file_systems(name=name, attributes=n_attr)
return True
except rest.ApiException:
return False
else:
return False
else:
return False
def fs_update(name, rules, snapshot=False):
'''
Update filesystem on a Pure Storage FlashBlade.
Allows for change of NFS export rules and enabling/disabled
of snapshotting capability.
.. versionadded:: 2019.2.0
name : string
name of filesystem
rules : string
NFS export rules for filesystem
Refer to Pure Storage documentation for formatting rules.
snapshot: boolean
(Optional) Enable/Disable snapshots on the filesystem. Default is False
CLI Example:
.. code-block:: bash
salt '*' purefb.fs_nfs_update foo rules='10.234.112.23(ro), 10.234.112.24(rw)' snapshot=True
'''
blade = _get_blade()
attr = {}
_fs = _get_fs(name, blade)
if _fs is not None:
try:
if _fs.nfs.enabled:
attr['nfs'] = NfsRule(rules=rules)
attr['snapshot_directory_enabled'] = snapshot
n_attr = FileSystem(**attr)
blade.file_systems.update_file_systems(name=name, attributes=n_attr)
return True
except rest.ApiException:
return False
else:
return False
|
saltstack/salt
|
salt/states/syslog_ng.py
|
started
|
python
|
def started(name=None,
user=None,
group=None,
chroot=None,
caps=None,
no_caps=False,
pidfile=None,
enable_core=False,
fd_limit=None,
verbose=False,
debug=False,
trace=False,
yydebug=False,
persist_file=None,
control=None,
worker_threads=None,
*args,
**kwargs):
'''
Ensures, that syslog-ng is started via the given parameters.
Users shouldn't use this function, if the service module is available on
their system.
'''
return __salt__['syslog_ng.start'](name=name,
user=user,
group=group,
chroot=chroot,
caps=caps,
no_caps=no_caps,
pidfile=pidfile,
enable_core=enable_core,
fd_limit=fd_limit,
verbose=verbose,
debug=debug,
trace=trace,
yydebug=yydebug,
persist_file=persist_file,
control=control,
worker_threads=worker_threads)
|
Ensures, that syslog-ng is started via the given parameters.
Users shouldn't use this function, if the service module is available on
their system.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/syslog_ng.py#L76-L115
| null |
# -*- coding: utf-8 -*-
'''
State module for syslog_ng
==========================
:maintainer: Tibor Benke <btibi@sch.bme.hu>
:maturity: new
:depends: cmd, ps, syslog_ng
:platform: all
Users can generate syslog-ng configuration files from YAML format or use
plain ones and reload, start, or stop their syslog-ng by using this module.
Details
-------
The service module is not available on all system, so this module includes
:mod:`syslog_ng.reloaded <salt.states.syslog_ng.reloaded>`,
:mod:`syslog_ng.stopped <salt.states.syslog_ng.stopped>`,
and :mod:`syslog_ng.started <salt.states.syslog_ng.started>` functions.
If the service module is available on the computers, users should use that.
Users can generate syslog-ng configuration with
:mod:`syslog_ng.config <salt.states.syslog_ng.config>` function.
For more information see :ref:`syslog-ng state usage <syslog-ng-sate-usage>`.
Syslog-ng configuration file format
-----------------------------------
The syntax of a configuration snippet in syslog-ng.conf:
..
object_type object_id {<options>};
These constructions are also called statements. There are options inside of them:
..
option(parameter1, parameter2); option2(parameter1, parameter2);
You can find more information about syslog-ng's configuration syntax in the
Syslog-ng Admin guide:
http://www.balabit.com/sites/default/files/documents/syslog-ng-ose-3.5-guides/en/syslog-ng-ose-v3.5-guide-admin/html-single/index.html#syslog-ng.conf.5
'''
from __future__ import absolute_import, unicode_literals, print_function, \
generators, with_statement
import logging
log = logging.getLogger(__name__)
def config(name,
config,
write=True):
'''
Builds syslog-ng configuration.
name : the id of the Salt document
config : the parsed YAML code
write : if True, it writes the config into the configuration file,
otherwise just returns it
'''
return __salt__['syslog_ng.config'](name, config, write)
def stopped(name=None):
'''
Kills syslog-ng.
'''
return __salt__['syslog_ng.stop'](name)
def reloaded(name):
'''
Reloads syslog-ng.
'''
return __salt__['syslog_ng.reload'](name)
|
saltstack/salt
|
salt/client/ssh/client.py
|
SSHClient._prep_ssh
|
python
|
def _prep_ssh(
self,
tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
kwarg=None,
**kwargs):
'''
Prepare the arguments
'''
opts = copy.deepcopy(self.opts)
opts.update(kwargs)
if timeout:
opts['timeout'] = timeout
arg = salt.utils.args.condition_input(arg, kwarg)
opts['argv'] = [fun] + arg
opts['selected_target_option'] = tgt_type
opts['tgt'] = tgt
opts['arg'] = arg
return salt.client.ssh.SSH(opts)
|
Prepare the arguments
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/client.py#L43-L64
|
[
"def condition_input(args, kwargs):\n '''\n Return a single arg structure for the publisher to safely use\n '''\n ret = []\n for arg in args:\n if (six.PY3 and isinstance(arg, six.integer_types) and salt.utils.jid.is_jid(six.text_type(arg))) or \\\n (six.PY2 and isinstance(arg, long)): # pylint: disable=incompatible-py3-code,undefined-variable\n ret.append(six.text_type(arg))\n else:\n ret.append(arg)\n if isinstance(kwargs, dict) and kwargs:\n kw_ = {'__kwarg__': True}\n for key, val in six.iteritems(kwargs):\n kw_[key] = val\n return ret + [kw_]\n return ret\n"
] |
class SSHClient(object):
'''
Create a client object for executing routines via the salt-ssh backend
.. versionadded:: 2015.5.0
'''
def __init__(self,
c_path=os.path.join(syspaths.CONFIG_DIR, 'master'),
mopts=None,
disable_custom_roster=False):
if mopts:
self.opts = mopts
else:
if os.path.isdir(c_path):
log.warning(
'%s expects a file path not a directory path(%s) to '
'its \'c_path\' keyword argument',
self.__class__.__name__, c_path
)
self.opts = salt.config.client_config(c_path)
# Salt API should never offer a custom roster!
self.opts['__disable_custom_roster'] = disable_custom_roster
def cmd_iter(
self,
tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
**kwargs):
'''
Execute a single command via the salt-ssh subsystem and return a
generator
.. versionadded:: 2015.5.0
'''
ssh = self._prep_ssh(
tgt,
fun,
arg,
timeout,
tgt_type,
kwarg,
**kwargs)
for ret in ssh.run_iter(jid=kwargs.get('jid', None)):
yield ret
def cmd(self,
tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
kwarg=None,
**kwargs):
'''
Execute a single command via the salt-ssh subsystem and return all
routines at once
.. versionadded:: 2015.5.0
'''
ssh = self._prep_ssh(
tgt,
fun,
arg,
timeout,
tgt_type,
kwarg,
**kwargs)
final = {}
for ret in ssh.run_iter(jid=kwargs.get('jid', None)):
final.update(ret)
return final
def cmd_sync(self, low):
'''
Execute a salt-ssh call synchronously.
.. versionadded:: 2015.5.0
WARNING: Eauth is **NOT** respected
.. code-block:: python
client.cmd_sync({
'tgt': 'silver',
'fun': 'test.ping',
'arg': (),
'tgt_type'='glob',
'kwarg'={}
})
{'silver': {'fun_args': [], 'jid': '20141202152721523072', 'return': True, 'retcode': 0, 'success': True, 'fun': 'test.ping', 'id': 'silver'}}
'''
kwargs = copy.deepcopy(low)
for ignore in ['tgt', 'fun', 'arg', 'timeout', 'tgt_type', 'kwarg']:
if ignore in kwargs:
del kwargs[ignore]
return self.cmd(low['tgt'],
low['fun'],
low.get('arg', []),
low.get('timeout'),
low.get('tgt_type'),
low.get('kwarg'),
**kwargs)
def cmd_async(self, low, timeout=None):
'''
Execute aa salt-ssh asynchronously
WARNING: Eauth is **NOT** respected
.. code-block:: python
client.cmd_sync({
'tgt': 'silver',
'fun': 'test.ping',
'arg': (),
'tgt_type'='glob',
'kwarg'={}
})
{'silver': {'fun_args': [], 'jid': '20141202152721523072', 'return': True, 'retcode': 0, 'success': True, 'fun': 'test.ping', 'id': 'silver'}}
'''
# TODO Not implemented
raise SaltClientError
def cmd_subset(
self,
tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
sub=3,
**kwargs):
'''
Execute a command on a random subset of the targeted systems
The function signature is the same as :py:meth:`cmd` with the
following exceptions.
:param sub: The number of systems to execute on
.. code-block:: python
>>> import salt.client.ssh.client
>>> sshclient= salt.client.ssh.client.SSHClient()
>>> sshclient.cmd_subset('*', 'test.ping', sub=1)
{'jerry': True}
.. versionadded:: 2017.7.0
'''
minion_ret = self.cmd(tgt,
'sys.list_functions',
tgt_type=tgt_type,
**kwargs)
minions = list(minion_ret)
random.shuffle(minions)
f_tgt = []
for minion in minions:
if fun in minion_ret[minion]['return']:
f_tgt.append(minion)
if len(f_tgt) >= sub:
break
return self.cmd_iter(f_tgt, fun, arg, timeout, tgt_type='list', ret=ret, kwarg=kwarg, **kwargs)
|
saltstack/salt
|
salt/client/ssh/client.py
|
SSHClient.cmd_iter
|
python
|
def cmd_iter(
self,
tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
**kwargs):
'''
Execute a single command via the salt-ssh subsystem and return a
generator
.. versionadded:: 2015.5.0
'''
ssh = self._prep_ssh(
tgt,
fun,
arg,
timeout,
tgt_type,
kwarg,
**kwargs)
for ret in ssh.run_iter(jid=kwargs.get('jid', None)):
yield ret
|
Execute a single command via the salt-ssh subsystem and return a
generator
.. versionadded:: 2015.5.0
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/client.py#L66-L91
|
[
"def run_iter(self, mine=False, jid=None):\n '''\n Execute and yield returns as they come in, do not print to the display\n\n mine\n The Single objects will use mine_functions defined in the roster,\n pillar, or master config (they will be checked in that order) and\n will modify the argv with the arguments from mine_functions\n '''\n fstr = '{0}.prep_jid'.format(self.opts['master_job_cache'])\n jid = self.returners[fstr](passed_jid=jid or self.opts.get('jid', None))\n\n # Save the invocation information\n argv = self.opts['argv']\n\n if self.opts.get('raw_shell', False):\n fun = 'ssh._raw'\n args = argv\n else:\n fun = argv[0] if argv else ''\n args = argv[1:]\n\n job_load = {\n 'jid': jid,\n 'tgt_type': self.tgt_type,\n 'tgt': self.opts['tgt'],\n 'user': self.opts['user'],\n 'fun': fun,\n 'arg': args,\n }\n\n # save load to the master job cache\n if self.opts['master_job_cache'] == 'local_cache':\n self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load, minions=self.targets.keys())\n else:\n self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load)\n\n for ret in self.handle_ssh(mine=mine):\n host = next(six.iterkeys(ret))\n self.cache_job(jid, host, ret[host], fun)\n if self.event:\n id_, data = next(six.iteritems(ret))\n if isinstance(data, six.text_type):\n data = {'return': data}\n if 'id' not in data:\n data['id'] = id_\n data['jid'] = jid # make the jid in the payload the same as the jid in the tag\n self.event.fire_event(\n data,\n salt.utils.event.tagify(\n [jid, 'ret', host],\n 'job'))\n yield ret\n",
"def _prep_ssh(\n self,\n tgt,\n fun,\n arg=(),\n timeout=None,\n tgt_type='glob',\n kwarg=None,\n **kwargs):\n '''\n Prepare the arguments\n '''\n opts = copy.deepcopy(self.opts)\n opts.update(kwargs)\n if timeout:\n opts['timeout'] = timeout\n arg = salt.utils.args.condition_input(arg, kwarg)\n opts['argv'] = [fun] + arg\n opts['selected_target_option'] = tgt_type\n opts['tgt'] = tgt\n opts['arg'] = arg\n return salt.client.ssh.SSH(opts)\n"
] |
class SSHClient(object):
'''
Create a client object for executing routines via the salt-ssh backend
.. versionadded:: 2015.5.0
'''
def __init__(self,
c_path=os.path.join(syspaths.CONFIG_DIR, 'master'),
mopts=None,
disable_custom_roster=False):
if mopts:
self.opts = mopts
else:
if os.path.isdir(c_path):
log.warning(
'%s expects a file path not a directory path(%s) to '
'its \'c_path\' keyword argument',
self.__class__.__name__, c_path
)
self.opts = salt.config.client_config(c_path)
# Salt API should never offer a custom roster!
self.opts['__disable_custom_roster'] = disable_custom_roster
def _prep_ssh(
self,
tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
kwarg=None,
**kwargs):
'''
Prepare the arguments
'''
opts = copy.deepcopy(self.opts)
opts.update(kwargs)
if timeout:
opts['timeout'] = timeout
arg = salt.utils.args.condition_input(arg, kwarg)
opts['argv'] = [fun] + arg
opts['selected_target_option'] = tgt_type
opts['tgt'] = tgt
opts['arg'] = arg
return salt.client.ssh.SSH(opts)
def cmd(self,
tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
kwarg=None,
**kwargs):
'''
Execute a single command via the salt-ssh subsystem and return all
routines at once
.. versionadded:: 2015.5.0
'''
ssh = self._prep_ssh(
tgt,
fun,
arg,
timeout,
tgt_type,
kwarg,
**kwargs)
final = {}
for ret in ssh.run_iter(jid=kwargs.get('jid', None)):
final.update(ret)
return final
def cmd_sync(self, low):
'''
Execute a salt-ssh call synchronously.
.. versionadded:: 2015.5.0
WARNING: Eauth is **NOT** respected
.. code-block:: python
client.cmd_sync({
'tgt': 'silver',
'fun': 'test.ping',
'arg': (),
'tgt_type'='glob',
'kwarg'={}
})
{'silver': {'fun_args': [], 'jid': '20141202152721523072', 'return': True, 'retcode': 0, 'success': True, 'fun': 'test.ping', 'id': 'silver'}}
'''
kwargs = copy.deepcopy(low)
for ignore in ['tgt', 'fun', 'arg', 'timeout', 'tgt_type', 'kwarg']:
if ignore in kwargs:
del kwargs[ignore]
return self.cmd(low['tgt'],
low['fun'],
low.get('arg', []),
low.get('timeout'),
low.get('tgt_type'),
low.get('kwarg'),
**kwargs)
def cmd_async(self, low, timeout=None):
'''
Execute aa salt-ssh asynchronously
WARNING: Eauth is **NOT** respected
.. code-block:: python
client.cmd_sync({
'tgt': 'silver',
'fun': 'test.ping',
'arg': (),
'tgt_type'='glob',
'kwarg'={}
})
{'silver': {'fun_args': [], 'jid': '20141202152721523072', 'return': True, 'retcode': 0, 'success': True, 'fun': 'test.ping', 'id': 'silver'}}
'''
# TODO Not implemented
raise SaltClientError
def cmd_subset(
self,
tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
sub=3,
**kwargs):
'''
Execute a command on a random subset of the targeted systems
The function signature is the same as :py:meth:`cmd` with the
following exceptions.
:param sub: The number of systems to execute on
.. code-block:: python
>>> import salt.client.ssh.client
>>> sshclient= salt.client.ssh.client.SSHClient()
>>> sshclient.cmd_subset('*', 'test.ping', sub=1)
{'jerry': True}
.. versionadded:: 2017.7.0
'''
minion_ret = self.cmd(tgt,
'sys.list_functions',
tgt_type=tgt_type,
**kwargs)
minions = list(minion_ret)
random.shuffle(minions)
f_tgt = []
for minion in minions:
if fun in minion_ret[minion]['return']:
f_tgt.append(minion)
if len(f_tgt) >= sub:
break
return self.cmd_iter(f_tgt, fun, arg, timeout, tgt_type='list', ret=ret, kwarg=kwarg, **kwargs)
|
saltstack/salt
|
salt/client/ssh/client.py
|
SSHClient.cmd
|
python
|
def cmd(self,
tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
kwarg=None,
**kwargs):
'''
Execute a single command via the salt-ssh subsystem and return all
routines at once
.. versionadded:: 2015.5.0
'''
ssh = self._prep_ssh(
tgt,
fun,
arg,
timeout,
tgt_type,
kwarg,
**kwargs)
final = {}
for ret in ssh.run_iter(jid=kwargs.get('jid', None)):
final.update(ret)
return final
|
Execute a single command via the salt-ssh subsystem and return all
routines at once
.. versionadded:: 2015.5.0
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/client.py#L93-L118
|
[
"def run_iter(self, mine=False, jid=None):\n '''\n Execute and yield returns as they come in, do not print to the display\n\n mine\n The Single objects will use mine_functions defined in the roster,\n pillar, or master config (they will be checked in that order) and\n will modify the argv with the arguments from mine_functions\n '''\n fstr = '{0}.prep_jid'.format(self.opts['master_job_cache'])\n jid = self.returners[fstr](passed_jid=jid or self.opts.get('jid', None))\n\n # Save the invocation information\n argv = self.opts['argv']\n\n if self.opts.get('raw_shell', False):\n fun = 'ssh._raw'\n args = argv\n else:\n fun = argv[0] if argv else ''\n args = argv[1:]\n\n job_load = {\n 'jid': jid,\n 'tgt_type': self.tgt_type,\n 'tgt': self.opts['tgt'],\n 'user': self.opts['user'],\n 'fun': fun,\n 'arg': args,\n }\n\n # save load to the master job cache\n if self.opts['master_job_cache'] == 'local_cache':\n self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load, minions=self.targets.keys())\n else:\n self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load)\n\n for ret in self.handle_ssh(mine=mine):\n host = next(six.iterkeys(ret))\n self.cache_job(jid, host, ret[host], fun)\n if self.event:\n id_, data = next(six.iteritems(ret))\n if isinstance(data, six.text_type):\n data = {'return': data}\n if 'id' not in data:\n data['id'] = id_\n data['jid'] = jid # make the jid in the payload the same as the jid in the tag\n self.event.fire_event(\n data,\n salt.utils.event.tagify(\n [jid, 'ret', host],\n 'job'))\n yield ret\n",
"def _prep_ssh(\n self,\n tgt,\n fun,\n arg=(),\n timeout=None,\n tgt_type='glob',\n kwarg=None,\n **kwargs):\n '''\n Prepare the arguments\n '''\n opts = copy.deepcopy(self.opts)\n opts.update(kwargs)\n if timeout:\n opts['timeout'] = timeout\n arg = salt.utils.args.condition_input(arg, kwarg)\n opts['argv'] = [fun] + arg\n opts['selected_target_option'] = tgt_type\n opts['tgt'] = tgt\n opts['arg'] = arg\n return salt.client.ssh.SSH(opts)\n"
] |
class SSHClient(object):
'''
Create a client object for executing routines via the salt-ssh backend
.. versionadded:: 2015.5.0
'''
def __init__(self,
c_path=os.path.join(syspaths.CONFIG_DIR, 'master'),
mopts=None,
disable_custom_roster=False):
if mopts:
self.opts = mopts
else:
if os.path.isdir(c_path):
log.warning(
'%s expects a file path not a directory path(%s) to '
'its \'c_path\' keyword argument',
self.__class__.__name__, c_path
)
self.opts = salt.config.client_config(c_path)
# Salt API should never offer a custom roster!
self.opts['__disable_custom_roster'] = disable_custom_roster
def _prep_ssh(
self,
tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
kwarg=None,
**kwargs):
'''
Prepare the arguments
'''
opts = copy.deepcopy(self.opts)
opts.update(kwargs)
if timeout:
opts['timeout'] = timeout
arg = salt.utils.args.condition_input(arg, kwarg)
opts['argv'] = [fun] + arg
opts['selected_target_option'] = tgt_type
opts['tgt'] = tgt
opts['arg'] = arg
return salt.client.ssh.SSH(opts)
def cmd_iter(
self,
tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
**kwargs):
'''
Execute a single command via the salt-ssh subsystem and return a
generator
.. versionadded:: 2015.5.0
'''
ssh = self._prep_ssh(
tgt,
fun,
arg,
timeout,
tgt_type,
kwarg,
**kwargs)
for ret in ssh.run_iter(jid=kwargs.get('jid', None)):
yield ret
def cmd_sync(self, low):
'''
Execute a salt-ssh call synchronously.
.. versionadded:: 2015.5.0
WARNING: Eauth is **NOT** respected
.. code-block:: python
client.cmd_sync({
'tgt': 'silver',
'fun': 'test.ping',
'arg': (),
'tgt_type'='glob',
'kwarg'={}
})
{'silver': {'fun_args': [], 'jid': '20141202152721523072', 'return': True, 'retcode': 0, 'success': True, 'fun': 'test.ping', 'id': 'silver'}}
'''
kwargs = copy.deepcopy(low)
for ignore in ['tgt', 'fun', 'arg', 'timeout', 'tgt_type', 'kwarg']:
if ignore in kwargs:
del kwargs[ignore]
return self.cmd(low['tgt'],
low['fun'],
low.get('arg', []),
low.get('timeout'),
low.get('tgt_type'),
low.get('kwarg'),
**kwargs)
def cmd_async(self, low, timeout=None):
'''
Execute aa salt-ssh asynchronously
WARNING: Eauth is **NOT** respected
.. code-block:: python
client.cmd_sync({
'tgt': 'silver',
'fun': 'test.ping',
'arg': (),
'tgt_type'='glob',
'kwarg'={}
})
{'silver': {'fun_args': [], 'jid': '20141202152721523072', 'return': True, 'retcode': 0, 'success': True, 'fun': 'test.ping', 'id': 'silver'}}
'''
# TODO Not implemented
raise SaltClientError
def cmd_subset(
self,
tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
sub=3,
**kwargs):
'''
Execute a command on a random subset of the targeted systems
The function signature is the same as :py:meth:`cmd` with the
following exceptions.
:param sub: The number of systems to execute on
.. code-block:: python
>>> import salt.client.ssh.client
>>> sshclient= salt.client.ssh.client.SSHClient()
>>> sshclient.cmd_subset('*', 'test.ping', sub=1)
{'jerry': True}
.. versionadded:: 2017.7.0
'''
minion_ret = self.cmd(tgt,
'sys.list_functions',
tgt_type=tgt_type,
**kwargs)
minions = list(minion_ret)
random.shuffle(minions)
f_tgt = []
for minion in minions:
if fun in minion_ret[minion]['return']:
f_tgt.append(minion)
if len(f_tgt) >= sub:
break
return self.cmd_iter(f_tgt, fun, arg, timeout, tgt_type='list', ret=ret, kwarg=kwarg, **kwargs)
|
saltstack/salt
|
salt/client/ssh/client.py
|
SSHClient.cmd_sync
|
python
|
def cmd_sync(self, low):
'''
Execute a salt-ssh call synchronously.
.. versionadded:: 2015.5.0
WARNING: Eauth is **NOT** respected
.. code-block:: python
client.cmd_sync({
'tgt': 'silver',
'fun': 'test.ping',
'arg': (),
'tgt_type'='glob',
'kwarg'={}
})
{'silver': {'fun_args': [], 'jid': '20141202152721523072', 'return': True, 'retcode': 0, 'success': True, 'fun': 'test.ping', 'id': 'silver'}}
'''
kwargs = copy.deepcopy(low)
for ignore in ['tgt', 'fun', 'arg', 'timeout', 'tgt_type', 'kwarg']:
if ignore in kwargs:
del kwargs[ignore]
return self.cmd(low['tgt'],
low['fun'],
low.get('arg', []),
low.get('timeout'),
low.get('tgt_type'),
low.get('kwarg'),
**kwargs)
|
Execute a salt-ssh call synchronously.
.. versionadded:: 2015.5.0
WARNING: Eauth is **NOT** respected
.. code-block:: python
client.cmd_sync({
'tgt': 'silver',
'fun': 'test.ping',
'arg': (),
'tgt_type'='glob',
'kwarg'={}
})
{'silver': {'fun_args': [], 'jid': '20141202152721523072', 'return': True, 'retcode': 0, 'success': True, 'fun': 'test.ping', 'id': 'silver'}}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/client.py#L120-L152
|
[
"def cmd(self,\n tgt,\n fun,\n arg=(),\n timeout=None,\n tgt_type='glob',\n kwarg=None,\n **kwargs):\n '''\n Execute a single command via the salt-ssh subsystem and return all\n routines at once\n\n .. versionadded:: 2015.5.0\n '''\n ssh = self._prep_ssh(\n tgt,\n fun,\n arg,\n timeout,\n tgt_type,\n kwarg,\n **kwargs)\n final = {}\n for ret in ssh.run_iter(jid=kwargs.get('jid', None)):\n final.update(ret)\n return final\n"
] |
class SSHClient(object):
'''
Create a client object for executing routines via the salt-ssh backend
.. versionadded:: 2015.5.0
'''
def __init__(self,
c_path=os.path.join(syspaths.CONFIG_DIR, 'master'),
mopts=None,
disable_custom_roster=False):
if mopts:
self.opts = mopts
else:
if os.path.isdir(c_path):
log.warning(
'%s expects a file path not a directory path(%s) to '
'its \'c_path\' keyword argument',
self.__class__.__name__, c_path
)
self.opts = salt.config.client_config(c_path)
# Salt API should never offer a custom roster!
self.opts['__disable_custom_roster'] = disable_custom_roster
def _prep_ssh(
self,
tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
kwarg=None,
**kwargs):
'''
Prepare the arguments
'''
opts = copy.deepcopy(self.opts)
opts.update(kwargs)
if timeout:
opts['timeout'] = timeout
arg = salt.utils.args.condition_input(arg, kwarg)
opts['argv'] = [fun] + arg
opts['selected_target_option'] = tgt_type
opts['tgt'] = tgt
opts['arg'] = arg
return salt.client.ssh.SSH(opts)
def cmd_iter(
self,
tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
**kwargs):
'''
Execute a single command via the salt-ssh subsystem and return a
generator
.. versionadded:: 2015.5.0
'''
ssh = self._prep_ssh(
tgt,
fun,
arg,
timeout,
tgt_type,
kwarg,
**kwargs)
for ret in ssh.run_iter(jid=kwargs.get('jid', None)):
yield ret
def cmd(self,
tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
kwarg=None,
**kwargs):
'''
Execute a single command via the salt-ssh subsystem and return all
routines at once
.. versionadded:: 2015.5.0
'''
ssh = self._prep_ssh(
tgt,
fun,
arg,
timeout,
tgt_type,
kwarg,
**kwargs)
final = {}
for ret in ssh.run_iter(jid=kwargs.get('jid', None)):
final.update(ret)
return final
def cmd_async(self, low, timeout=None):
'''
Execute aa salt-ssh asynchronously
WARNING: Eauth is **NOT** respected
.. code-block:: python
client.cmd_sync({
'tgt': 'silver',
'fun': 'test.ping',
'arg': (),
'tgt_type'='glob',
'kwarg'={}
})
{'silver': {'fun_args': [], 'jid': '20141202152721523072', 'return': True, 'retcode': 0, 'success': True, 'fun': 'test.ping', 'id': 'silver'}}
'''
# TODO Not implemented
raise SaltClientError
def cmd_subset(
self,
tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
sub=3,
**kwargs):
'''
Execute a command on a random subset of the targeted systems
The function signature is the same as :py:meth:`cmd` with the
following exceptions.
:param sub: The number of systems to execute on
.. code-block:: python
>>> import salt.client.ssh.client
>>> sshclient= salt.client.ssh.client.SSHClient()
>>> sshclient.cmd_subset('*', 'test.ping', sub=1)
{'jerry': True}
.. versionadded:: 2017.7.0
'''
minion_ret = self.cmd(tgt,
'sys.list_functions',
tgt_type=tgt_type,
**kwargs)
minions = list(minion_ret)
random.shuffle(minions)
f_tgt = []
for minion in minions:
if fun in minion_ret[minion]['return']:
f_tgt.append(minion)
if len(f_tgt) >= sub:
break
return self.cmd_iter(f_tgt, fun, arg, timeout, tgt_type='list', ret=ret, kwarg=kwarg, **kwargs)
|
saltstack/salt
|
salt/client/ssh/client.py
|
SSHClient.cmd_subset
|
python
|
def cmd_subset(
self,
tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
sub=3,
**kwargs):
'''
Execute a command on a random subset of the targeted systems
The function signature is the same as :py:meth:`cmd` with the
following exceptions.
:param sub: The number of systems to execute on
.. code-block:: python
>>> import salt.client.ssh.client
>>> sshclient= salt.client.ssh.client.SSHClient()
>>> sshclient.cmd_subset('*', 'test.ping', sub=1)
{'jerry': True}
.. versionadded:: 2017.7.0
'''
minion_ret = self.cmd(tgt,
'sys.list_functions',
tgt_type=tgt_type,
**kwargs)
minions = list(minion_ret)
random.shuffle(minions)
f_tgt = []
for minion in minions:
if fun in minion_ret[minion]['return']:
f_tgt.append(minion)
if len(f_tgt) >= sub:
break
return self.cmd_iter(f_tgt, fun, arg, timeout, tgt_type='list', ret=ret, kwarg=kwarg, **kwargs)
|
Execute a command on a random subset of the targeted systems
The function signature is the same as :py:meth:`cmd` with the
following exceptions.
:param sub: The number of systems to execute on
.. code-block:: python
>>> import salt.client.ssh.client
>>> sshclient= salt.client.ssh.client.SSHClient()
>>> sshclient.cmd_subset('*', 'test.ping', sub=1)
{'jerry': True}
.. versionadded:: 2017.7.0
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/client.py#L174-L214
|
[
"def cmd_iter(\n self,\n tgt,\n fun,\n arg=(),\n timeout=None,\n tgt_type='glob',\n ret='',\n kwarg=None,\n **kwargs):\n '''\n Execute a single command via the salt-ssh subsystem and return a\n generator\n\n .. versionadded:: 2015.5.0\n '''\n ssh = self._prep_ssh(\n tgt,\n fun,\n arg,\n timeout,\n tgt_type,\n kwarg,\n **kwargs)\n for ret in ssh.run_iter(jid=kwargs.get('jid', None)):\n yield ret\n",
"def cmd(self,\n tgt,\n fun,\n arg=(),\n timeout=None,\n tgt_type='glob',\n kwarg=None,\n **kwargs):\n '''\n Execute a single command via the salt-ssh subsystem and return all\n routines at once\n\n .. versionadded:: 2015.5.0\n '''\n ssh = self._prep_ssh(\n tgt,\n fun,\n arg,\n timeout,\n tgt_type,\n kwarg,\n **kwargs)\n final = {}\n for ret in ssh.run_iter(jid=kwargs.get('jid', None)):\n final.update(ret)\n return final\n"
] |
class SSHClient(object):
'''
Create a client object for executing routines via the salt-ssh backend
.. versionadded:: 2015.5.0
'''
def __init__(self,
c_path=os.path.join(syspaths.CONFIG_DIR, 'master'),
mopts=None,
disable_custom_roster=False):
if mopts:
self.opts = mopts
else:
if os.path.isdir(c_path):
log.warning(
'%s expects a file path not a directory path(%s) to '
'its \'c_path\' keyword argument',
self.__class__.__name__, c_path
)
self.opts = salt.config.client_config(c_path)
# Salt API should never offer a custom roster!
self.opts['__disable_custom_roster'] = disable_custom_roster
def _prep_ssh(
self,
tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
kwarg=None,
**kwargs):
'''
Prepare the arguments
'''
opts = copy.deepcopy(self.opts)
opts.update(kwargs)
if timeout:
opts['timeout'] = timeout
arg = salt.utils.args.condition_input(arg, kwarg)
opts['argv'] = [fun] + arg
opts['selected_target_option'] = tgt_type
opts['tgt'] = tgt
opts['arg'] = arg
return salt.client.ssh.SSH(opts)
def cmd_iter(
self,
tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
**kwargs):
'''
Execute a single command via the salt-ssh subsystem and return a
generator
.. versionadded:: 2015.5.0
'''
ssh = self._prep_ssh(
tgt,
fun,
arg,
timeout,
tgt_type,
kwarg,
**kwargs)
for ret in ssh.run_iter(jid=kwargs.get('jid', None)):
yield ret
def cmd(self,
tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
kwarg=None,
**kwargs):
'''
Execute a single command via the salt-ssh subsystem and return all
routines at once
.. versionadded:: 2015.5.0
'''
ssh = self._prep_ssh(
tgt,
fun,
arg,
timeout,
tgt_type,
kwarg,
**kwargs)
final = {}
for ret in ssh.run_iter(jid=kwargs.get('jid', None)):
final.update(ret)
return final
def cmd_sync(self, low):
'''
Execute a salt-ssh call synchronously.
.. versionadded:: 2015.5.0
WARNING: Eauth is **NOT** respected
.. code-block:: python
client.cmd_sync({
'tgt': 'silver',
'fun': 'test.ping',
'arg': (),
'tgt_type'='glob',
'kwarg'={}
})
{'silver': {'fun_args': [], 'jid': '20141202152721523072', 'return': True, 'retcode': 0, 'success': True, 'fun': 'test.ping', 'id': 'silver'}}
'''
kwargs = copy.deepcopy(low)
for ignore in ['tgt', 'fun', 'arg', 'timeout', 'tgt_type', 'kwarg']:
if ignore in kwargs:
del kwargs[ignore]
return self.cmd(low['tgt'],
low['fun'],
low.get('arg', []),
low.get('timeout'),
low.get('tgt_type'),
low.get('kwarg'),
**kwargs)
def cmd_async(self, low, timeout=None):
'''
Execute aa salt-ssh asynchronously
WARNING: Eauth is **NOT** respected
.. code-block:: python
client.cmd_sync({
'tgt': 'silver',
'fun': 'test.ping',
'arg': (),
'tgt_type'='glob',
'kwarg'={}
})
{'silver': {'fun_args': [], 'jid': '20141202152721523072', 'return': True, 'retcode': 0, 'success': True, 'fun': 'test.ping', 'id': 'silver'}}
'''
# TODO Not implemented
raise SaltClientError
|
saltstack/salt
|
salt/states/eselect.py
|
set_
|
python
|
def set_(name, target, module_parameter=None, action_parameter=None):
'''
Verify that the given module is set to the given target
name
The name of the module
target
The target to be set for this module
module_parameter
additional params passed to the defined module
action_parameter
additional params passed to the defined action
.. code-block:: yaml
profile:
eselect.set:
- target: hardened/linux/amd64
'''
ret = {'changes': {},
'comment': '',
'name': name,
'result': True}
old_target = __salt__['eselect.get_current_target'](name, module_parameter=module_parameter, action_parameter=action_parameter)
if target == old_target:
ret['comment'] = 'Target \'{0}\' is already set on \'{1}\' module.'.format(
target, name
)
elif target not in __salt__['eselect.get_target_list'](name, action_parameter=action_parameter):
ret['comment'] = (
'Target \'{0}\' is not available for \'{1}\' module.'.format(
target, name
)
)
ret['result'] = False
elif __opts__['test']:
ret['comment'] = 'Target \'{0}\' will be set on \'{1}\' module.'.format(
target, name
)
ret['result'] = None
else:
result = __salt__['eselect.set_target'](name, target, module_parameter=module_parameter, action_parameter=action_parameter)
if result:
ret['changes'][name] = {'old': old_target, 'new': target}
ret['comment'] = 'Target \'{0}\' set on \'{1}\' module.'.format(
target, name
)
else:
ret['comment'] = (
'Target \'{0}\' failed to be set on \'{1}\' module.'.format(
target, name
)
)
ret['result'] = False
return ret
|
Verify that the given module is set to the given target
name
The name of the module
target
The target to be set for this module
module_parameter
additional params passed to the defined module
action_parameter
additional params passed to the defined action
.. code-block:: yaml
profile:
eselect.set:
- target: hardened/linux/amd64
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/eselect.py#L26-L85
| null |
# -*- coding: utf-8 -*-
'''
Management of Gentoo configuration using eselect
================================================
A state module to manage Gentoo configuration via eselect
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
# Define a function alias in order not to shadow built-in's
__func_alias__ = {
'set_': 'set'
}
def __virtual__():
'''
Only load if the eselect module is available in __salt__
'''
return 'eselect' if 'eselect.exec_action' in __salt__ else False
|
saltstack/salt
|
salt/modules/napalm_network.py
|
_filter_list
|
python
|
def _filter_list(input_list, search_key, search_value):
'''
Filters a list of dictionary by a set of key-value pair.
:param input_list: is a list of dictionaries
:param search_key: is the key we are looking for
:param search_value: is the value we are looking for the key specified in search_key
:return: filered list of dictionaries
'''
output_list = list()
for dictionary in input_list:
if dictionary.get(search_key) == search_value:
output_list.append(dictionary)
return output_list
|
Filters a list of dictionary by a set of key-value pair.
:param input_list: is a list of dictionaries
:param search_key: is the key we are looking for
:param search_value: is the value we are looking for the key specified in search_key
:return: filered list of dictionaries
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_network.py#L70-L87
| null |
# -*- coding: utf-8 -*-
'''
NAPALM Network
==============
Basic methods for interaction with the network device through the virtual proxy 'napalm'.
:codeauthor: Mircea Ulinic <mircea@cloudflare.com> & Jerome Fleury <jf@cloudflare.com>
:maturity: new
:depends: napalm
:platform: unix
Dependencies
------------
- :mod:`napalm proxy minion <salt.proxy.napalm>`
.. versionadded:: 2016.11.0
.. versionchanged:: 2017.7.0
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import time
import logging
import datetime
log = logging.getLogger(__name__)
# Import Salt libs
from salt.ext import six
import salt.utils.files
import salt.utils.napalm
import salt.utils.versions
import salt.utils.templates
# Import 3rd-party libs
try:
import jxmlease # pylint: disable=unused-import
HAS_JXMLEASE = True
except ImportError:
HAS_JXMLEASE = False
# ----------------------------------------------------------------------------------------------------------------------
# module properties
# ----------------------------------------------------------------------------------------------------------------------
__virtualname__ = 'net'
__proxyenabled__ = ['*']
__virtual_aliases__ = ('napalm_net',)
# uses NAPALM-based proxy to interact with network devices
# ----------------------------------------------------------------------------------------------------------------------
# property functions
# ----------------------------------------------------------------------------------------------------------------------
def __virtual__():
'''
NAPALM library must be installed for this module to work and run in a (proxy) minion.
'''
return salt.utils.napalm.virtual(__opts__, __virtualname__, __file__)
# ----------------------------------------------------------------------------------------------------------------------
# helper functions -- will not be exported
# ----------------------------------------------------------------------------------------------------------------------
def _filter_dict(input_dict, search_key, search_value):
'''
Filters a dictionary of dictionaries by a key-value pair.
:param input_dict: is a dictionary whose values are lists of dictionaries
:param search_key: is the key in the leaf dictionaries
:param search_values: is the value in the leaf dictionaries
:return: filtered dictionary
'''
output_dict = dict()
for key, key_list in six.iteritems(input_dict):
key_list_filtered = _filter_list(key_list, search_key, search_value)
if key_list_filtered:
output_dict[key] = key_list_filtered
return output_dict
def _safe_commit_config(loaded_result, napalm_device):
_commit = commit(inherit_napalm_device=napalm_device) # calls the function commit, defined below
if not _commit.get('result', False):
# if unable to commit
loaded_result['comment'] += _commit['comment'] if _commit.get('comment') else 'Unable to commit.'
loaded_result['result'] = False
# unable to commit, something went wrong
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
return _commit
def _safe_dicard_config(loaded_result, napalm_device):
'''
'''
log.debug('Discarding the config')
log.debug(loaded_result)
_discarded = discard_config(inherit_napalm_device=napalm_device)
if not _discarded.get('result', False):
loaded_result['comment'] += _discarded['comment'] if _discarded.get('comment') \
else 'Unable to discard config.'
loaded_result['result'] = False
# make sure it notifies
# that something went wrong
_explicit_close(napalm_device)
__context__['retcode'] = 1
return loaded_result
return _discarded
def _explicit_close(napalm_device):
'''
Will explicily close the config session with the network device,
when running in a now-always-alive proxy minion or regular minion.
This helper must be used in configuration-related functions,
as the session is preserved and not closed before making any changes.
'''
if salt.utils.napalm.not_always_alive(__opts__):
# force closing the configuration session
# when running in a non-always-alive proxy
# or regular minion
try:
napalm_device['DRIVER'].close()
except Exception as err:
log.error('Unable to close the temp connection with the device:')
log.error(err)
log.error('Please report.')
def _config_logic(napalm_device,
loaded_result,
test=False,
debug=False,
replace=False,
commit_config=True,
loaded_config=None,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
commit_jid=None,
**kwargs):
'''
Builds the config logic for `load_config` and `load_template` functions.
'''
# As the Salt logic is built around independent events
# when it comes to configuration changes in the
# candidate DB on the network devices, we need to
# make sure we're using the same session.
# Hence, we need to pass the same object around.
# the napalm_device object is inherited from
# the load_config or load_template functions
# and forwarded to compare, discard, commit etc.
# then the decorator will make sure that
# if not proxy (when the connection is always alive)
# and the `inherit_napalm_device` is set,
# `napalm_device` will be overridden.
# See `salt.utils.napalm.proxy_napalm_wrap` decorator.
current_jid = kwargs.get('__pub_jid')
if not current_jid:
current_jid = '{0:%Y%m%d%H%M%S%f}'.format(datetime.datetime.now())
loaded_result['already_configured'] = False
loaded_result['loaded_config'] = ''
if debug:
loaded_result['loaded_config'] = loaded_config
_compare = compare_config(inherit_napalm_device=napalm_device)
if _compare.get('result', False):
loaded_result['diff'] = _compare.get('out')
loaded_result.pop('out', '') # not needed
else:
loaded_result['diff'] = None
loaded_result['result'] = False
loaded_result['comment'] = _compare.get('comment')
__context__['retcode'] = 1
return loaded_result
_loaded_res = loaded_result.get('result', False)
if not _loaded_res or test:
# if unable to load the config (errors / warnings)
# or in testing mode,
# will discard the config
if loaded_result['comment']:
loaded_result['comment'] += '\n'
if not loaded_result.get('diff', ''):
loaded_result['already_configured'] = True
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
loaded_result['comment'] += 'Configuration discarded.'
# loaded_result['result'] = False not necessary
# as the result can be true when test=True
_explicit_close(napalm_device)
if not loaded_result['result']:
__context__['retcode'] = 1
return loaded_result
if not test and commit_config:
# if not in testing mode and trying to commit
if commit_jid:
log.info('Committing the JID: %s', str(commit_jid))
removed = cancel_commit(commit_jid)
log.debug('Cleaned up the commit from the schedule')
log.debug(removed['comment'])
if loaded_result.get('diff', ''):
# if not testing mode
# and also the user wants to commit (default)
# and there are changes to commit
if commit_in or commit_at:
commit_time = __utils__['timeutil.get_time_at'](time_in=commit_in,
time_at=commit_in)
# schedule job
scheduled_job_name = '__napalm_commit_{}'.format(current_jid)
temp_file = salt.utils.files.mkstemp()
with salt.utils.files.fopen(temp_file, 'w') as fp_:
fp_.write(loaded_config)
scheduled = __salt__['schedule.add'](scheduled_job_name,
function='net.load_config',
job_kwargs={
'filename': temp_file,
'commit_jid': current_jid,
'replace': replace
},
once=commit_time)
log.debug('Scheduling job')
log.debug(scheduled)
saved = __salt__['schedule.save']() # ensure the schedule is
# persistent cross Minion restart
discarded = _safe_dicard_config(loaded_result, napalm_device)
# discard the changes
if not discarded['result']:
discarded['comment'] += ('Scheduled the job to be executed at {schedule_ts}, '
'but was unable to discard the config: \n').format(schedule_ts=commit_time)
return discarded
loaded_result['comment'] = ('Changes discarded for now, and scheduled commit at: {schedule_ts}.\n'
'The commit ID is: {current_jid}.\n'
'To discard this commit, you can execute: \n\n'
'salt {min_id} net.cancel_commit {current_jid}').format(schedule_ts=commit_time,
min_id=__opts__['id'],
current_jid=current_jid)
loaded_result['commit_id'] = current_jid
return loaded_result
log.debug('About to commit:')
log.debug(loaded_result['diff'])
if revert_in or revert_at:
revert_time = __utils__['timeutil.get_time_at'](time_in=revert_in,
time_at=revert_at)
if __grains__['os'] == 'junos':
if not HAS_JXMLEASE:
loaded_result['comment'] = ('This feature requires the library jxmlease to be installed.\n'
'To install, please execute: ``pip install jxmlease``.')
loaded_result['result'] = False
return loaded_result
timestamp_at = __utils__['timeutil.get_timestamp_at'](time_in=revert_in,
time_at=revert_at)
minutes = int((timestamp_at - time.time())/60)
_comm = __salt__['napalm.junos_commit'](confirm=minutes)
if not _comm['out']:
# If unable to commit confirm, should try to bail out
loaded_result['comment'] = 'Unable to commit confirm: {}'.format(_comm['message'])
loaded_result['result'] = False
# But before exiting, we must gracefully discard the config
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
else:
temp_file = salt.utils.files.mkstemp()
running_config = __salt__['net.config'](source='running')['out']['running']
with salt.utils.files.fopen(temp_file, 'w') as fp_:
fp_.write(running_config)
committed = _safe_commit_config(loaded_result, napalm_device)
if not committed['result']:
# If unable to commit, dicard the config (which is
# already done by the _safe_commit_config function), and
# return with the command and other details.
return loaded_result
scheduled_job_name = '__napalm_commit_{}'.format(current_jid)
scheduled = __salt__['schedule.add'](scheduled_job_name,
function='net.load_config',
job_kwargs={
'filename': temp_file,
'commit_jid': current_jid,
'replace': True
},
once=revert_time)
log.debug('Scheduling commit confirmed')
log.debug(scheduled)
saved = __salt__['schedule.save']()
loaded_result['comment'] = ('The commit ID is: {current_jid}.\n'
'This commit will be reverted at: {schedule_ts}, unless confirmed.\n'
'To confirm the commit and avoid reverting, you can execute:\n\n'
'salt {min_id} net.confirm_commit {current_jid}').format(schedule_ts=revert_time,
min_id=__opts__['id'],
current_jid=current_jid)
loaded_result['commit_id'] = current_jid
return loaded_result
committed = _safe_commit_config(loaded_result, napalm_device)
if not committed['result']:
return loaded_result
else:
# would like to commit, but there's no change
# need to call discard_config() to release the config DB
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
loaded_result['already_configured'] = True
loaded_result['comment'] = 'Already configured.'
_explicit_close(napalm_device)
if not loaded_result['result']:
__context__['retcode'] = 1
return loaded_result
# ----------------------------------------------------------------------------------------------------------------------
# callable functions
# ----------------------------------------------------------------------------------------------------------------------
@salt.utils.napalm.proxy_napalm_wrap
def connected(**kwargs): # pylint: disable=unused-argument
'''
Specifies if the connection to the device succeeded.
CLI Example:
.. code-block:: bash
salt '*' net.connected
'''
return {
'out': napalm_device.get('UP', False) # pylint: disable=undefined-variable
}
@salt.utils.napalm.proxy_napalm_wrap
def facts(**kwargs): # pylint: disable=unused-argument
'''
Returns characteristics of the network device.
:return: a dictionary with the following keys:
* uptime - Uptime of the device in seconds.
* vendor - Manufacturer of the device.
* model - Device model.
* hostname - Hostname of the device
* fqdn - Fqdn of the device
* os_version - String with the OS version running on the device.
* serial_number - Serial number of the device
* interface_list - List of the interfaces of the device
CLI Example:
.. code-block:: bash
salt '*' net.facts
Example output:
.. code-block:: python
{
'os_version': '13.3R6.5',
'uptime': 10117140,
'interface_list': [
'lc-0/0/0',
'pfe-0/0/0',
'pfh-0/0/0',
'xe-0/0/0',
'xe-0/0/1',
'xe-0/0/2',
'xe-0/0/3',
'gr-0/0/10',
'ip-0/0/10'
],
'vendor': 'Juniper',
'serial_number': 'JN131356FBFA',
'model': 'MX480',
'hostname': 're0.edge05.syd01',
'fqdn': 're0.edge05.syd01'
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_facts',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def environment(**kwargs): # pylint: disable=unused-argument
'''
Returns the environment of the device.
CLI Example:
.. code-block:: bash
salt '*' net.environment
Example output:
.. code-block:: python
{
'fans': {
'Bottom Rear Fan': {
'status': True
},
'Bottom Middle Fan': {
'status': True
},
'Top Middle Fan': {
'status': True
},
'Bottom Front Fan': {
'status': True
},
'Top Front Fan': {
'status': True
},
'Top Rear Fan': {
'status': True
}
},
'memory': {
'available_ram': 16349,
'used_ram': 4934
},
'temperature': {
'FPC 0 Exhaust A': {
'is_alert': False,
'temperature': 35.0,
'is_critical': False
}
},
'cpu': {
'1': {
'%usage': 19.0
},
'0': {
'%usage': 35.0
}
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_environment',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def cli(*commands, **kwargs): # pylint: disable=unused-argument
'''
Returns a dictionary with the raw output of all commands passed as arguments.
commands
List of commands to be executed on the device.
textfsm_parse: ``False``
Try parsing the outputs using the TextFSM templates.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``napalm_cli_textfsm_parse``.
textfsm_path
The path where the TextFSM templates can be found. This option implies
the usage of the TextFSM index file.
``textfsm_path`` can be either absolute path on the server,
either specified using the following URL mschemes: ``file://``,
``salt://``, ``http://``, ``https://``, ``ftp://``,
``s3://``, ``swift://``.
.. versionadded:: 2018.3.0
.. note::
This needs to be a directory with a flat structure, having an
index file (whose name can be specified using the ``index_file`` option)
and a number of TextFSM templates.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_path``.
textfsm_template
The path to a certain the TextFSM template.
This can be specified using the absolute path
to the file, or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
.. versionadded:: 2018.3.0
textfsm_template_dict
A dictionary with the mapping between a command
and the corresponding TextFSM path to use to extract the data.
The TextFSM paths can be specified as in ``textfsm_template``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``napalm_cli_textfsm_template_dict``.
platform_grain_name: ``os``
The name of the grain used to identify the platform name
in the TextFSM index file. Default: ``os``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_grain``.
platform_column_name: ``Platform``
The column name used to identify the platform,
exactly as specified in the TextFSM index file.
Default: ``Platform``.
.. versionadded:: 2018.3.0
.. note::
This is field is case sensitive, make sure
to assign the correct value to this option,
exactly as defined in the index file.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_column_name``.
index_file: ``index``
The name of the TextFSM index file, under the ``textfsm_path``. Default: ``index``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_index_file``.
saltenv: ``base``
Salt fileserver envrionment from which to retrieve the file.
Ignored if ``textfsm_path`` is not a ``salt://`` URL.
.. versionadded:: 2018.3.0
include_empty: ``False``
Include empty files under the ``textfsm_path``.
.. versionadded:: 2018.3.0
include_pat
Glob or regex to narrow down the files cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. versionadded:: 2018.3.0
exclude_pat
Glob or regex to exclude certain files from being cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. versionadded:: 2018.3.0
.. note::
If used with ``include_pat``, files matching this pattern will be
excluded from the subset of files defined by ``include_pat``.
CLI Example:
.. code-block:: bash
salt '*' net.cli "show version" "show chassis fan"
CLI Example with TextFSM template:
.. code-block:: bash
salt '*' net.cli textfsm_parse=True textfsm_path=salt://textfsm/
Example output:
.. code-block:: python
{
'show version and haiku': 'Hostname: re0.edge01.arn01
Model: mx480
Junos: 13.3R6.5
Help me, Obi-Wan
I just saw Episode Two
You're my only hope
',
'show chassis fan' : 'Item Status RPM Measurement
Top Rear Fan OK 3840 Spinning at intermediate-speed
Bottom Rear Fan OK 3840 Spinning at intermediate-speed
Top Middle Fan OK 3900 Spinning at intermediate-speed
Bottom Middle Fan OK 3840 Spinning at intermediate-speed
Top Front Fan OK 3810 Spinning at intermediate-speed
Bottom Front Fan OK 3840 Spinning at intermediate-speed
'
}
Example output with TextFSM parsing:
.. code-block:: json
{
"comment": "",
"result": true,
"out": {
"sh ver": [
{
"kernel": "9.1S3.5",
"documentation": "9.1S3.5",
"boot": "9.1S3.5",
"crypto": "9.1S3.5",
"chassis": "",
"routing": "9.1S3.5",
"base": "9.1S3.5",
"model": "mx960"
}
]
}
}
'''
raw_cli_outputs = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'cli',
**{
'commands': list(commands)
}
)
# thus we can display the output as is
# in case of errors, they'll be catched in the proxy
if not raw_cli_outputs['result']:
# Error -> dispaly the output as-is.
return raw_cli_outputs
textfsm_parse = kwargs.get('textfsm_parse') or __opts__.get('napalm_cli_textfsm_parse') or\
__pillar__.get('napalm_cli_textfsm_parse', False)
if not textfsm_parse:
# No TextFSM parsing required, return raw commands.
log.debug('No TextFSM parsing requested.')
return raw_cli_outputs
if 'textfsm.extract' not in __salt__ or 'textfsm.index' not in __salt__:
raw_cli_outputs['comment'] += 'Unable to process: is TextFSM installed?'
log.error(raw_cli_outputs['comment'])
return raw_cli_outputs
textfsm_template = kwargs.get('textfsm_template')
log.debug('textfsm_template: %s', textfsm_template)
textfsm_path = kwargs.get('textfsm_path') or __opts__.get('textfsm_path') or\
__pillar__.get('textfsm_path')
log.debug('textfsm_path: %s', textfsm_path)
textfsm_template_dict = kwargs.get('textfsm_template_dict') or __opts__.get('napalm_cli_textfsm_template_dict') or\
__pillar__.get('napalm_cli_textfsm_template_dict', {})
log.debug('TextFSM command-template mapping: %s', textfsm_template_dict)
index_file = kwargs.get('index_file') or __opts__.get('textfsm_index_file') or\
__pillar__.get('textfsm_index_file')
log.debug('index_file: %s', index_file)
platform_grain_name = kwargs.get('platform_grain_name') or __opts__.get('textfsm_platform_grain') or\
__pillar__.get('textfsm_platform_grain', 'os')
log.debug('platform_grain_name: %s', platform_grain_name)
platform_column_name = kwargs.get('platform_column_name') or __opts__.get('textfsm_platform_column_name') or\
__pillar__.get('textfsm_platform_column_name', 'Platform')
log.debug('platform_column_name: %s', platform_column_name)
saltenv = kwargs.get('saltenv', 'base')
include_empty = kwargs.get('include_empty', False)
include_pat = kwargs.get('include_pat')
exclude_pat = kwargs.get('exclude_pat')
processed_cli_outputs = {
'comment': raw_cli_outputs.get('comment', ''),
'result': raw_cli_outputs['result'],
'out': {}
}
log.debug('Starting to analyse the raw outputs')
for command in list(commands):
command_output = raw_cli_outputs['out'][command]
log.debug('Output from command: %s', command)
log.debug(command_output)
processed_command_output = None
if textfsm_path:
log.debug('Using the templates under %s', textfsm_path)
processed_cli_output = __salt__['textfsm.index'](command,
platform_grain_name=platform_grain_name,
platform_column_name=platform_column_name,
output=command_output.strip(),
textfsm_path=textfsm_path,
saltenv=saltenv,
include_empty=include_empty,
include_pat=include_pat,
exclude_pat=exclude_pat)
log.debug('Processed CLI output:')
log.debug(processed_cli_output)
if not processed_cli_output['result']:
log.debug('Apparently this didnt work, returnin the raw output')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {0}: {1}.'.format(command,
processed_cli_output['comment'])
log.error(processed_cli_outputs['comment'])
elif processed_cli_output['out']:
log.debug('All good, %s has a nice output!', command)
processed_command_output = processed_cli_output['out']
else:
comment = '''\nProcessing "{}" didn't fail, but didn't return anything either. Dumping raw.'''.format(
command)
processed_cli_outputs['comment'] += comment
log.error(comment)
processed_command_output = command_output
elif textfsm_template or command in textfsm_template_dict:
if command in textfsm_template_dict:
textfsm_template = textfsm_template_dict[command]
log.debug('Using %s to process the command: %s', textfsm_template, command)
processed_cli_output = __salt__['textfsm.extract'](textfsm_template,
raw_text=command_output,
saltenv=saltenv)
log.debug('Processed CLI output:')
log.debug(processed_cli_output)
if not processed_cli_output['result']:
log.debug('Apparently this didnt work, returning '
'the raw output')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {0}: {1}'.format(command,
processed_cli_output['comment'])
log.error(processed_cli_outputs['comment'])
elif processed_cli_output['out']:
log.debug('All good, %s has a nice output!', command)
processed_command_output = processed_cli_output['out']
else:
log.debug('Processing %s didnt fail, but didnt return'
' anything either. Dumping raw.', command)
processed_command_output = command_output
else:
log.error('No TextFSM template specified, or no TextFSM path defined')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {}.'.format(command)
processed_cli_outputs['out'][command] = processed_command_output
processed_cli_outputs['comment'] = processed_cli_outputs['comment'].strip()
return processed_cli_outputs
@salt.utils.napalm.proxy_napalm_wrap
def traceroute(destination, source=None, ttl=None, timeout=None, vrf=None, **kwargs): # pylint: disable=unused-argument
'''
Calls the method traceroute from the NAPALM driver object and returns a dictionary with the result of the traceroute
command executed on the device.
destination
Hostname or address of remote host
source
Source address to use in outgoing traceroute packets
ttl
IP maximum time-to-live value (or IPv6 maximum hop-limit value)
timeout
Number of seconds to wait for response (seconds)
vrf
VRF (routing instance) for traceroute attempt
.. versionadded:: 2016.11.4
CLI Example:
.. code-block:: bash
salt '*' net.traceroute 8.8.8.8
salt '*' net.traceroute 8.8.8.8 source=127.0.0.1 ttl=5 timeout=1
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'traceroute',
**{
'destination': destination,
'source': source,
'ttl': ttl,
'timeout': timeout,
'vrf': vrf
}
)
@salt.utils.napalm.proxy_napalm_wrap
def ping(destination, source=None, ttl=None, timeout=None, size=None, count=None, vrf=None, **kwargs): # pylint: disable=unused-argument
'''
Executes a ping on the network device and returns a dictionary as a result.
destination
Hostname or IP address of remote host
source
Source address of echo request
ttl
IP time-to-live value (IPv6 hop-limit value) (1..255 hops)
timeout
Maximum wait time after sending final packet (seconds)
size
Size of request packets (0..65468 bytes)
count
Number of ping requests to send (1..2000000000 packets)
vrf
VRF (routing instance) for ping attempt
.. versionadded:: 2016.11.4
CLI Example:
.. code-block:: bash
salt '*' net.ping 8.8.8.8
salt '*' net.ping 8.8.8.8 ttl=3 size=65468
salt '*' net.ping 8.8.8.8 source=127.0.0.1 timeout=1 count=100
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'ping',
**{
'destination': destination,
'source': source,
'ttl': ttl,
'timeout': timeout,
'size': size,
'count': count,
'vrf': vrf
}
)
@salt.utils.napalm.proxy_napalm_wrap
def arp(interface='', ipaddr='', macaddr='', **kwargs): # pylint: disable=unused-argument
'''
NAPALM returns a list of dictionaries with details of the ARP entries.
:param interface: interface name to filter on
:param ipaddr: IP address to filter on
:param macaddr: MAC address to filter on
:return: List of the entries in the ARP table
CLI Example:
.. code-block:: bash
salt '*' net.arp
salt '*' net.arp macaddr='5c:5e:ab:da:3c:f0'
Example output:
.. code-block:: python
[
{
'interface' : 'MgmtEth0/RSP0/CPU0/0',
'mac' : '5c:5e:ab:da:3c:f0',
'ip' : '172.17.17.1',
'age' : 1454496274.84
},
{
'interface': 'MgmtEth0/RSP0/CPU0/0',
'mac' : '66:0e:94:96:e0:ff',
'ip' : '172.17.17.2',
'age' : 1435641582.49
}
]
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_arp_table',
**{
}
)
if not proxy_output.get('result'):
return proxy_output
arp_table = proxy_output.get('out')
if interface:
arp_table = _filter_list(arp_table, 'interface', interface)
if ipaddr:
arp_table = _filter_list(arp_table, 'ip', ipaddr)
if macaddr:
arp_table = _filter_list(arp_table, 'mac', macaddr)
proxy_output.update({
'out': arp_table
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def ipaddrs(**kwargs): # pylint: disable=unused-argument
'''
Returns IP addresses configured on the device.
:return: A dictionary with the IPv4 and IPv6 addresses of the interfaces.
Returns all configured IP addresses on all interfaces as a dictionary
of dictionaries. Keys of the main dictionary represent the name of the
interface. Values of the main dictionary represent are dictionaries
that may consist of two keys 'ipv4' and 'ipv6' (one, both or none)
which are themselvs dictionaries with the IP addresses as keys.
CLI Example:
.. code-block:: bash
salt '*' net.ipaddrs
Example output:
.. code-block:: python
{
'FastEthernet8': {
'ipv4': {
'10.66.43.169': {
'prefix_length': 22
}
}
},
'Loopback555': {
'ipv4': {
'192.168.1.1': {
'prefix_length': 24
}
},
'ipv6': {
'1::1': {
'prefix_length': 64
},
'2001:DB8:1::1': {
'prefix_length': 64
},
'FE80::3': {
'prefix_length': 'N/A'
}
}
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_interfaces_ip',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def interfaces(**kwargs): # pylint: disable=unused-argument
'''
Returns details of the interfaces on the device.
:return: Returns a dictionary of dictionaries. The keys for the first
dictionary will be the interfaces in the devices.
CLI Example:
.. code-block:: bash
salt '*' net.interfaces
Example output:
.. code-block:: python
{
'Management1': {
'is_up': False,
'is_enabled': False,
'description': '',
'last_flapped': -1,
'speed': 1000,
'mac_address': 'dead:beef:dead',
},
'Ethernet1':{
'is_up': True,
'is_enabled': True,
'description': 'foo',
'last_flapped': 1429978575.1554043,
'speed': 1000,
'mac_address': 'beef:dead:beef',
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_interfaces',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def lldp(interface='', **kwargs): # pylint: disable=unused-argument
'''
Returns a detailed view of the LLDP neighbors.
:param interface: interface name to filter on
:return: A dictionary with the LLDL neighbors. The keys are the
interfaces with LLDP activated on.
CLI Example:
.. code-block:: bash
salt '*' net.lldp
salt '*' net.lldp interface='TenGigE0/0/0/8'
Example output:
.. code-block:: python
{
'TenGigE0/0/0/8': [
{
'parent_interface': 'Bundle-Ether8',
'interface_description': 'TenGigE0/0/0/8',
'remote_chassis_id': '8c60.4f69.e96c',
'remote_system_name': 'switch',
'remote_port': 'Eth2/2/1',
'remote_port_description': 'Ethernet2/2/1',
'remote_system_description': 'Cisco Nexus Operating System (NX-OS) Software 7.1(0)N1(1a)
TAC support: http://www.cisco.com/tac
Copyright (c) 2002-2015, Cisco Systems, Inc. All rights reserved.',
'remote_system_capab': 'B, R',
'remote_system_enable_capab': 'B'
}
]
}
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_lldp_neighbors_detail',
**{
}
)
if not proxy_output.get('result'):
return proxy_output
lldp_neighbors = proxy_output.get('out')
if interface:
lldp_neighbors = {interface: lldp_neighbors.get(interface)}
proxy_output.update({
'out': lldp_neighbors
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def mac(address='', interface='', vlan=0, **kwargs): # pylint: disable=unused-argument
'''
Returns the MAC Address Table on the device.
:param address: MAC address to filter on
:param interface: Interface name to filter on
:param vlan: VLAN identifier
:return: A list of dictionaries representing the entries in the MAC Address Table
CLI Example:
.. code-block:: bash
salt '*' net.mac
salt '*' net.mac vlan=10
Example output:
.. code-block:: python
[
{
'mac' : '00:1c:58:29:4a:71',
'interface' : 'xe-3/0/2',
'static' : False,
'active' : True,
'moves' : 1,
'vlan' : 10,
'last_move' : 1454417742.58
},
{
'mac' : '8c:60:4f:58:e1:c1',
'interface' : 'xe-1/0/1',
'static' : False,
'active' : True,
'moves' : 2,
'vlan' : 42,
'last_move' : 1453191948.11
}
]
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_mac_address_table',
**{
}
)
if not proxy_output.get('result'):
# if negative, leave the output unchanged
return proxy_output
mac_address_table = proxy_output.get('out')
if vlan and isinstance(vlan, int):
mac_address_table = _filter_list(mac_address_table, 'vlan', vlan)
if address:
mac_address_table = _filter_list(mac_address_table, 'mac', address)
if interface:
mac_address_table = _filter_list(mac_address_table, 'interface', interface)
proxy_output.update({
'out': mac_address_table
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def config(source=None, **kwargs): # pylint: disable=unused-argument
'''
.. versionadded:: 2017.7.0
Return the whole configuration of the network device. By default, it will
return all possible configuration sources supported by the network device.
At most, there will be:
- running config
- startup config
- candidate config
To return only one of the configurations, you can use the ``source``
argument.
source
Which configuration type you want to display, default is all of them.
Options:
- running
- candidate
- startup
:return:
The object returned is a dictionary with the following keys:
- running (string): Representation of the native running configuration.
- candidate (string): Representation of the native candidate configuration.
If the device doesn't differentiate between running and startup
configuration this will an empty string.
- startup (string): Representation of the native startup configuration.
If the device doesn't differentiate between running and startup
configuration this will an empty string.
CLI Example:
.. code-block:: bash
salt '*' net.config
salt '*' net.config source=candidate
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_config',
**{
'retrieve': source
}
)
@salt.utils.napalm.proxy_napalm_wrap
def optics(**kwargs): # pylint: disable=unused-argument
'''
.. versionadded:: 2017.7.0
Fetches the power usage on the various transceivers installed
on the network device (in dBm), and returns a view that conforms with the
OpenConfig model openconfig-platform-transceiver.yang.
:return:
Returns a dictionary where the keys are as listed below:
* intf_name (unicode)
* physical_channels
* channels (list of dicts)
* index (int)
* state
* input_power
* instant (float)
* avg (float)
* min (float)
* max (float)
* output_power
* instant (float)
* avg (float)
* min (float)
* max (float)
* laser_bias_current
* instant (float)
* avg (float)
* min (float)
* max (float)
CLI Example:
.. code-block:: bash
salt '*' net.optics
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_optics',
**{
}
)
# <---- Call NAPALM getters --------------------------------------------------------------------------------------------
# ----- Configuration specific functions ------------------------------------------------------------------------------>
@salt.utils.napalm.proxy_napalm_wrap
def load_config(filename=None,
text=None,
test=False,
commit=True,
debug=False,
replace=False,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
commit_jid=None,
inherit_napalm_device=None,
saltenv='base',
**kwargs): # pylint: disable=unused-argument
'''
Applies configuration changes on the device. It can be loaded from a file or from inline string.
If you send both a filename and a string containing the configuration, the file has higher precedence.
By default this function will commit the changes. If there are no changes, it does not commit and
the flag ``already_configured`` will be set as ``True`` to point this out.
To avoid committing the configuration, set the argument ``test`` to ``True`` and will discard (dry run).
To keep the changes but not commit, set ``commit`` to ``False``.
To replace the config, set ``replace`` to ``True``.
filename
Path to the file containing the desired configuration.
This can be specified using the absolute path to the file,
or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
.. versionchanged:: 2018.3.0
text
String containing the desired configuration.
This argument is ignored when ``filename`` is specified.
test: False
Dry run? If set as ``True``, will apply the config, discard and return the changes. Default: ``False``
and will commit the changes on the device.
commit: True
Commit? Default: ``True``.
debug: False
Debug mode. Will insert a new key under the output dictionary, as ``loaded_config`` containing the raw
configuration loaded on the device.
.. versionadded:: 2016.11.2
replace: False
Load and replace the configuration. Default: ``False``.
.. versionadded:: 2016.11.2
commit_in: ``None``
Commit the changes in a specific number of minutes / hours. Example of
accepted formats: ``5`` (commit in 5 minutes), ``2m`` (commit in 2
minutes), ``1h`` (commit the changes in 1 hour)`, ``5h30m`` (commit
the changes in 5 hours and 30 minutes).
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
commit_at: ``None``
Commit the changes at a specific time. Example of accepted formats:
``1am`` (will commit the changes at the next 1AM), ``13:20`` (will
commit at 13:20), ``1:20am``, etc.
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
revert_in: ``None``
Commit and revert the changes in a specific number of minutes / hours.
Example of accepted formats: ``5`` (revert in 5 minutes), ``2m`` (revert
in 2 minutes), ``1h`` (revert the changes in 1 hour)`, ``5h30m`` (revert
the changes in 5 hours and 30 minutes).
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
revert_at: ``None``
Commit and revert the changes at a specific time. Example of accepted
formats: ``1am`` (will commit and revert the changes at the next 1AM),
``13:20`` (will commit and revert at 13:20), ``1:20am``, etc.
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
saltenv: ``base``
Specifies the Salt environment name.
.. versionadded:: 2018.3.0
:return: a dictionary having the following keys:
* result (bool): if the config was applied successfully. It is ``False`` only in case of failure. In case \
there are no changes to be applied and successfully performs all operations it is still ``True`` and so will be \
the ``already_configured`` flag (example below)
* comment (str): a message for the user
* already_configured (bool): flag to check if there were no changes applied
* loaded_config (str): the configuration loaded on the device. Requires ``debug`` to be set as ``True``
* diff (str): returns the config changes applied
CLI Example:
.. code-block:: bash
salt '*' net.load_config text='ntp peer 192.168.0.1'
salt '*' net.load_config filename='/absolute/path/to/your/file'
salt '*' net.load_config filename='/absolute/path/to/your/file' test=True
salt '*' net.load_config filename='/absolute/path/to/your/file' commit=False
Example output:
.. code-block:: python
{
'comment': 'Configuration discarded.',
'already_configured': False,
'result': True,
'diff': '[edit interfaces xe-0/0/5]+ description "Adding a description";'
}
'''
fun = 'load_merge_candidate'
if replace:
fun = 'load_replace_candidate'
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
if filename:
text = __salt__['cp.get_file_str'](filename, saltenv=saltenv)
if text is False:
# When using salt:// or https://, if the resource is not available,
# it will either raise an exception, or return False.
ret = {
'result': False,
'out': None
}
ret['comment'] = 'Unable to read from {}. Please specify a valid file or text.'.format(filename)
log.error(ret['comment'])
return ret
if commit_jid:
# When the commit_jid argument is passed, it probably is a scheduled
# commit to be executed, and filename is a temporary file which
# can be removed after reading it.
salt.utils.files.safe_rm(filename)
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
fun,
**{
'config': text
}
)
return _config_logic(napalm_device, # pylint: disable=undefined-variable
_loaded,
test=test,
debug=debug,
replace=replace,
commit_config=commit,
loaded_config=text,
commit_at=commit_at,
commit_in=commit_in,
revert_in=revert_in,
revert_at=revert_at,
commit_jid=commit_jid,
**kwargs)
@salt.utils.napalm.proxy_napalm_wrap
def load_template(template_name=None,
template_source=None,
context=None,
defaults=None,
template_engine='jinja',
saltenv='base',
template_hash=None,
template_hash_name=None,
skip_verify=False,
test=False,
commit=True,
debug=False,
replace=False,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
inherit_napalm_device=None, # pylint: disable=unused-argument
**template_vars):
'''
Renders a configuration template (default: Jinja) and loads the result on the device.
By default this function will commit the changes. If there are no changes,
it does not commit, discards he config and the flag ``already_configured``
will be set as ``True`` to point this out.
To avoid committing the configuration, set the argument ``test`` to ``True``
and will discard (dry run).
To preserve the changes, set ``commit`` to ``False``.
However, this is recommended to be used only in exceptional cases
when there are applied few consecutive states
and/or configuration changes.
Otherwise the user might forget that the config DB is locked
and the candidate config buffer is not cleared/merged in the running config.
To replace the config, set ``replace`` to ``True``.
template_name
Identifies path to the template source.
The template can be either stored on the local machine, either remotely.
The recommended location is under the ``file_roots``
as specified in the master config file.
For example, let's suppose the ``file_roots`` is configured as:
.. code-block:: yaml
file_roots:
base:
- /etc/salt/states
Placing the template under ``/etc/salt/states/templates/example.jinja``,
it can be used as ``salt://templates/example.jinja``.
Alternatively, for local files, the user can specify the absolute path.
If remotely, the source can be retrieved via ``http``, ``https`` or ``ftp``.
Examples:
- ``salt://my_template.jinja``
- ``/absolute/path/to/my_template.jinja``
- ``http://example.com/template.cheetah``
- ``https:/example.com/template.mako``
- ``ftp://example.com/template.py``
.. versionchanged:: 2019.2.0
This argument can now support a list of templates to be rendered.
The resulting configuration text is loaded at once, as a single
configuration chunk.
template_source: None
Inline config template to be rendered and loaded on the device.
template_hash: None
Hash of the template file. Format: ``{hash_type: 'md5', 'hsum': <md5sum>}``
.. versionadded:: 2016.11.2
context: None
Overrides default context variables passed to the template.
.. versionadded:: 2019.2.0
template_hash_name: None
When ``template_hash`` refers to a remote file,
this specifies the filename to look for in that file.
.. versionadded:: 2016.11.2
saltenv: ``base``
Specifies the template environment.
This will influence the relative imports inside the templates.
.. versionadded:: 2016.11.2
template_engine: jinja
The following templates engines are supported:
- :mod:`cheetah<salt.renderers.cheetah>`
- :mod:`genshi<salt.renderers.genshi>`
- :mod:`jinja<salt.renderers.jinja>`
- :mod:`mako<salt.renderers.mako>`
- :mod:`py<salt.renderers.py>`
- :mod:`wempy<salt.renderers.wempy>`
.. versionadded:: 2016.11.2
skip_verify: True
If ``True``, hash verification of remote file sources
(``http://``, ``https://``, ``ftp://``) will be skipped,
and the ``source_hash`` argument will be ignored.
.. versionadded:: 2016.11.2
test: False
Dry run? If set to ``True``, will apply the config,
discard and return the changes.
Default: ``False`` and will commit the changes on the device.
commit: True
Commit? (default: ``True``)
debug: False
Debug mode. Will insert a new key under the output dictionary,
as ``loaded_config`` containing the raw result after the template was rendered.
.. versionadded:: 2016.11.2
replace: False
Load and replace the configuration.
.. versionadded:: 2016.11.2
commit_in: ``None``
Commit the changes in a specific number of minutes / hours. Example of
accepted formats: ``5`` (commit in 5 minutes), ``2m`` (commit in 2
minutes), ``1h`` (commit the changes in 1 hour)`, ``5h30m`` (commit
the changes in 5 hours and 30 minutes).
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
commit_at: ``None``
Commit the changes at a specific time. Example of accepted formats:
``1am`` (will commit the changes at the next 1AM), ``13:20`` (will
commit at 13:20), ``1:20am``, etc.
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
revert_in: ``None``
Commit and revert the changes in a specific number of minutes / hours.
Example of accepted formats: ``5`` (revert in 5 minutes), ``2m`` (revert
in 2 minutes), ``1h`` (revert the changes in 1 hour)`, ``5h30m`` (revert
the changes in 5 hours and 30 minutes).
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
revert_at: ``None``
Commit and revert the changes at a specific time. Example of accepted
formats: ``1am`` (will commit and revert the changes at the next 1AM),
``13:20`` (will commit and revert at 13:20), ``1:20am``, etc.
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
defaults: None
Default variables/context passed to the template.
.. versionadded:: 2016.11.2
template_vars
Dictionary with the arguments/context to be used when the template is rendered.
.. note::
Do not explicitly specify this argument. This represents any other
variable that will be sent to the template rendering system.
Please see the examples below!
.. note::
It is more recommended to use the ``context`` argument to avoid
conflicts between CLI arguments and template variables.
:return: a dictionary having the following keys:
- result (bool): if the config was applied successfully. It is ``False``
only in case of failure. In case there are no changes to be applied and
successfully performs all operations it is still ``True`` and so will be
the ``already_configured`` flag (example below)
- comment (str): a message for the user
- already_configured (bool): flag to check if there were no changes applied
- loaded_config (str): the configuration loaded on the device, after
rendering the template. Requires ``debug`` to be set as ``True``
- diff (str): returns the config changes applied
The template can use variables from the ``grains``, ``pillar`` or ``opts``, for example:
.. code-block:: jinja
{% set router_model = grains.get('model') -%}
{% set router_vendor = grains.get('vendor') -%}
{% set os_version = grains.get('version') -%}
{% set hostname = pillar.get('proxy', {}).get('host') -%}
{% if router_vendor|lower == 'juniper' %}
system {
host-name {{hostname}};
}
{% elif router_vendor|lower == 'cisco' %}
hostname {{hostname}}
{% endif %}
CLI Examples:
.. code-block:: bash
salt '*' net.load_template set_ntp_peers peers=[192.168.0.1] # uses NAPALM default templates
# inline template:
salt -G 'os:junos' net.load_template template_source='system { host-name {{host_name}}; }' \
host_name='MX480.lab'
# inline template using grains info:
salt -G 'os:junos' net.load_template \
template_source='system { host-name {{grains.model}}.lab; }'
# if the device is a MX480, the command above will set the hostname as: MX480.lab
# inline template using pillar data:
salt -G 'os:junos' net.load_template template_source='system { host-name {{pillar.proxy.host}}; }'
salt '*' net.load_template https://bit.ly/2OhSgqP hostname=example # will commit
salt '*' net.load_template https://bit.ly/2OhSgqP hostname=example test=True # dry run
salt '*' net.load_template salt://templates/example.jinja debug=True # Using the salt:// URI
# render a mako template:
salt '*' net.load_template salt://templates/example.mako template_engine=mako debug=True
# render remote template
salt -G 'os:junos' net.load_template http://bit.ly/2fReJg7 test=True debug=True peers=['192.168.0.1']
salt -G 'os:ios' net.load_template http://bit.ly/2gKOj20 test=True debug=True peers=['192.168.0.1']
# render multiple templates at once
salt '*' net.load_template "['https://bit.ly/2OhSgqP', 'salt://templates/example.jinja']" context="{'hostname': 'example'}"
Example output:
.. code-block:: python
{
'comment': '',
'already_configured': False,
'result': True,
'diff': '[edit system]+ host-name edge01.bjm01',
'loaded_config': 'system { host-name edge01.bjm01; }''
}
'''
_rendered = ''
_loaded = {
'result': True,
'comment': '',
'out': None
}
loaded_config = None
# prechecks
deprecated_args = ('template_user', 'template_attrs', 'template_group', 'template_mode')
for deprecated_arg in deprecated_args:
if template_vars.get(deprecated_arg):
del template_vars[deprecated_arg]
salt.utils.versions.warn_until(
'Sodium',
('The \'{arg}\' argument to \'net.load_template\' is deprecated '
'and has been ignored').format(arg=deprecated_arg)
)
if template_engine not in salt.utils.templates.TEMPLATE_REGISTRY:
_loaded.update({
'result': False,
'comment': 'Invalid templating engine! Choose between: {tpl_eng_opts}'.format(
tpl_eng_opts=', '.join(list(salt.utils.templates.TEMPLATE_REGISTRY.keys()))
)
})
return _loaded # exit
# to check if will be rendered by salt or NAPALM
salt_render_prefixes = ('salt://', 'http://', 'https://', 'ftp://')
salt_render = False
file_exists = False
if not isinstance(template_name, (tuple, list)):
for salt_render_prefix in salt_render_prefixes:
if not salt_render:
salt_render = salt_render or template_name.startswith(salt_render_prefix)
file_exists = __salt__['file.file_exists'](template_name)
if template_source or file_exists or salt_render or isinstance(template_name, (tuple, list)):
# either inline template
# either template in a custom path
# either abs path send
# either starts with salt:// and
# then use Salt render system
if context is None:
context = {}
context.update(template_vars)
# if needed to render the template send as inline arg
if template_source:
# render the content
_rendered = __salt__['file.apply_template_on_contents'](
contents=template_source,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv
)
if not isinstance(_rendered, six.string_types):
if 'result' in _rendered:
_loaded['result'] = _rendered['result']
else:
_loaded['result'] = False
if 'comment' in _rendered:
_loaded['comment'] = _rendered['comment']
else:
_loaded['comment'] = 'Error while rendering the template.'
return _loaded
else:
# render the file - either local, either remote
if not isinstance(template_name, (list, tuple)):
template_name = [template_name]
if template_hash_name and not isinstance(template_hash_name, (list, tuple)):
template_hash_name = [template_hash_name]
elif not template_hash_name:
template_hash_name = [None] * len(template_name)
if template_hash and isinstance(template_hash, six.string_types) and not\
(template_hash.startswith('salt://') or template_hash.startswith('file://')):
# If the template hash is passed as string, and it's not a file
# (starts with the salt:// or file:// URI), then make it a list
# of 1 element (for the iteration below)
template_hash = [template_hash]
elif template_hash and isinstance(template_hash, six.string_types) and\
(template_hash.startswith('salt://') or template_hash.startswith('file://')):
# If the template hash is a file URI, then provide the same value
# for each of the templates in the list, as probably they all
# share the same hash file, otherwise the user should provide
# this as a list
template_hash = [template_hash] * len(template_name)
elif not template_hash:
template_hash = [None] * len(template_name)
for tpl_index, tpl_name in enumerate(template_name):
tpl_hash = template_hash[tpl_index]
tpl_hash_name = template_hash_name[tpl_index]
_rand_filename = __salt__['random.hash'](tpl_name, 'md5')
_temp_file = __salt__['file.join']('/tmp', _rand_filename)
_managed = __salt__['file.get_managed'](name=_temp_file,
source=tpl_name,
source_hash=tpl_hash,
source_hash_name=tpl_hash_name,
user=None,
group=None,
mode=None,
attrs=None,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv,
skip_verify=skip_verify)
if not isinstance(_managed, (list, tuple)) and isinstance(_managed, six.string_types):
_loaded['comment'] += _managed
_loaded['result'] = False
elif isinstance(_managed, (list, tuple)) and not _managed:
_loaded['result'] = False
_loaded['comment'] += 'Error while rendering the template.'
elif isinstance(_managed, (list, tuple)) and not _managed[0]:
_loaded['result'] = False
_loaded['comment'] += _managed[-1] # contains the error message
if _loaded['result']: # all good
_temp_tpl_file = _managed[0]
_temp_tpl_file_exists = __salt__['file.file_exists'](_temp_tpl_file)
if not _temp_tpl_file_exists:
_loaded['result'] = False
_loaded['comment'] += 'Error while rendering the template.'
return _loaded
_rendered += __salt__['file.read'](_temp_tpl_file)
__salt__['file.remove'](_temp_tpl_file)
else:
return _loaded # exit
loaded_config = _rendered
if _loaded['result']: # all good
fun = 'load_merge_candidate'
if replace: # replace requested
fun = 'load_replace_candidate'
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
fun,
**{
'config': _rendered
}
)
else:
salt.utils.versions.warn_until(
'Sodium',
'Native NAPALM templates support will be removed in the Sodium '
'release. Please consider using the Salt rendering pipeline instead.'
'If you are using the \'netntp\', \'netsnmp\', or \'netusers\' Salt '
'State modules, you can ignore this message'
)
# otherwise, use NAPALM render system, injecting pillar/grains/opts vars
load_templates_params = defaults if defaults else {}
load_templates_params.update(template_vars)
load_templates_params.update(
{
'template_name': template_name,
'template_source': template_source, # inline template
'pillar': __pillar__, # inject pillar content
'grains': __grains__, # inject grains content
'opts': __opts__ # inject opts content
}
)
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
# so we'll set the CLOSE global explicitly as False
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'load_template',
**load_templates_params
)
return _config_logic(napalm_device, # pylint: disable=undefined-variable
_loaded,
test=test,
debug=debug,
replace=replace,
commit_config=commit,
loaded_config=loaded_config,
commit_at=commit_at,
commit_in=commit_in,
revert_in=revert_in,
revert_at=revert_at,
**template_vars)
@salt.utils.napalm.proxy_napalm_wrap
def commit(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Commits the configuration changes made on the network device.
CLI Example:
.. code-block:: bash
salt '*' net.commit
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'commit_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def discard_config(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
"""
Discards the changes applied.
CLI Example:
.. code-block:: bash
salt '*' net.discard_config
"""
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'discard_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def compare_config(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Returns the difference between the running config and the candidate config.
CLI Example:
.. code-block:: bash
salt '*' net.compare_config
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'compare_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def rollback(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Rollbacks the configuration.
CLI Example:
.. code-block:: bash
salt '*' net.rollback
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'rollback',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def config_changed(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Will prompt if the configuration has been changed.
:return: A tuple with a boolean that specifies if the config was changed on the device.\
And a string that provides more details of the reason why the configuration was not changed.
CLI Example:
.. code-block:: bash
salt '*' net.config_changed
'''
is_config_changed = False
reason = ''
try_compare = compare_config(inherit_napalm_device=napalm_device) # pylint: disable=undefined-variable
if try_compare.get('result'):
if try_compare.get('out'):
is_config_changed = True
else:
reason = 'Configuration was not changed on the device.'
else:
reason = try_compare.get('comment')
return is_config_changed, reason
@salt.utils.napalm.proxy_napalm_wrap
def config_control(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Will check if the configuration was changed.
If differences found, will try to commit.
In case commit unsuccessful, will try to rollback.
:return: A tuple with a boolean that specifies if the config was changed/committed/rollbacked on the device.\
And a string that provides more details of the reason why the configuration was not committed properly.
CLI Example:
.. code-block:: bash
salt '*' net.config_control
'''
result = True
comment = ''
changed, not_changed_rsn = config_changed(inherit_napalm_device=napalm_device) # pylint: disable=undefined-variable
if not changed:
return (changed, not_changed_rsn)
# config changed, thus let's try to commit
try_commit = commit()
if not try_commit.get('result'):
result = False
comment = 'Unable to commit the changes: {reason}.\n\
Will try to rollback now!'.format(
reason=try_commit.get('comment')
)
try_rollback = rollback()
if not try_rollback.get('result'):
comment += '\nCannot rollback! {reason}'.format(
reason=try_rollback.get('comment')
)
return result, comment
def cancel_commit(jid):
'''
.. versionadded:: 2019.2.0
Cancel a commit scheduled to be executed via the ``commit_in`` and
``commit_at`` arguments from the
:py:func:`net.load_template <salt.modules.napalm_network.load_template>` or
:py:func:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit ID is displayed when the commit is scheduled
via the functions named above.
CLI Example:
.. code-block:: bash
salt '*' net.cancel_commit 20180726083540640360
'''
job_name = '__napalm_commit_{}'.format(jid)
removed = __salt__['schedule.delete'](job_name)
if removed['result']:
saved = __salt__['schedule.save']()
removed['comment'] = 'Commit #{jid} cancelled.'.format(jid=jid)
else:
removed['comment'] = 'Unable to find commit #{jid}.'.format(jid=jid)
return removed
def confirm_commit(jid):
'''
.. versionadded:: 2019.2.0
Confirm a commit scheduled to be reverted via the ``revert_in`` and
``revert_at`` arguments from the
:mod:`net.load_template <salt.modules.napalm_network.load_template>` or
:mod:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit ID is displayed when the commit confirmed
is scheduled via the functions named above.
CLI Example:
.. code-block:: bash
salt '*' net.confirm_commit 20180726083540640360
'''
if __grains__['os'] == 'junos':
# Confirm the commit, by committing (i.e., invoking the RPC call)
confirmed = __salt__['napalm.junos_commit']()
confirmed['result'] = confirmed.pop('out')
confirmed['comment'] = confirmed.pop('message')
else:
confirmed = cancel_commit(jid)
if confirmed['result']:
confirmed['comment'] = 'Commit #{jid} confirmed.'.format(jid=jid)
return confirmed
def save_config(source=None,
path=None):
'''
.. versionadded:: 2019.2.0
Save the configuration to a file on the local file system.
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``,
``startup``. Default: ``running``.
path
Absolute path to file where to save the configuration.
To push the files to the Master, use
:mod:`cp.push <salt.modules.cp.push>` Execution function.
CLI Example:
.. code-block:: bash
salt '*' net.save_config source=running
'''
if not source:
source = 'running'
if not path:
path = salt.utils.files.mkstemp()
running_config = __salt__['net.config'](source=source)
if not running_config or not running_config['result']:
log.error('Unable to retrieve the config')
return running_config
with salt.utils.files.fopen(path, 'w') as fh_:
fh_.write(running_config['out'][source])
return {
'result': True,
'out': path,
'comment': '{source} config saved to {path}'.format(source=source, path=path)
}
def replace_pattern(pattern,
repl,
count=0,
flags=8,
bufsize=1,
append_if_not_found=False,
prepend_if_not_found=False,
not_found_content=None,
search_only=False,
show_changes=True,
backslash_literal=False,
source=None,
path=None,
test=False,
replace=True,
debug=False,
commit=True):
'''
.. versionadded:: 2019.2.0
Replace occurrences of a pattern in the configuration source. If
``show_changes`` is ``True``, then a diff of what changed will be returned,
otherwise a ``True`` will be returned when changes are made, and ``False``
when no changes are made.
This is a pure Python implementation that wraps Python's :py:func:`~re.sub`.
pattern
A regular expression, to be matched using Python's
:py:func:`~re.search`.
repl
The replacement text.
count: ``0``
Maximum number of pattern occurrences to be replaced. If count is a
positive integer ``n``, only ``n`` occurrences will be replaced,
otherwise all occurrences will be replaced.
flags (list or int): ``8``
A list of flags defined in the ``re`` module documentation from the
Python standard library. Each list item should be a string that will
correlate to the human-friendly flag name. E.g., ``['IGNORECASE',
'MULTILINE']``. Optionally, ``flags`` may be an int, with a value
corresponding to the XOR (``|``) of all the desired flags. Defaults to
8 (which supports 'MULTILINE').
bufsize (int or str): ``1``
How much of the configuration to buffer into memory at once. The
default value ``1`` processes one line at a time. The special value
``file`` may be specified which will read the entire file into memory
before processing.
append_if_not_found: ``False``
If set to ``True``, and pattern is not found, then the content will be
appended to the file.
prepend_if_not_found: ``False``
If set to ``True`` and pattern is not found, then the content will be
prepended to the file.
not_found_content
Content to use for append/prepend if not found. If None (default), uses
``repl``. Useful when ``repl`` uses references to group in pattern.
search_only: ``False``
If set to true, this no changes will be performed on the file, and this
function will simply return ``True`` if the pattern was matched, and
``False`` if not.
show_changes: ``True``
If ``True``, return a diff of changes made. Otherwise, return ``True``
if changes were made, and ``False`` if not.
backslash_literal: ``False``
Interpret backslashes as literal backslashes for the repl and not
escape characters. This will help when using append/prepend so that
the backslashes are not interpreted for the repl on the second run of
the state.
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path
Save the temporary configuration to a specific path, then read from
there.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' net.replace_pattern "bind-address\\s*=" "bind-address:"
CLI Example:
.. code-block:: bash
salt '*' net.replace_pattern PREFIX-LIST_NAME new-prefix-list-name
salt '*' net.replace_pattern bgp-group-name new-bgp-group-name count=1
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
replace_pattern = __salt__['file.replace'](path,
pattern,
repl,
count=count,
flags=flags,
bufsize=bufsize,
append_if_not_found=append_if_not_found,
prepend_if_not_found=prepend_if_not_found,
not_found_content=not_found_content,
search_only=search_only,
show_changes=show_changes,
backslash_literal=backslash_literal)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
def blockreplace(marker_start,
marker_end,
content='',
append_if_not_found=False,
prepend_if_not_found=False,
show_changes=True,
append_newline=False,
source='running',
path=None,
test=False,
commit=True,
debug=False,
replace=True):
'''
.. versionadded:: 2019.2.0
Replace content of the configuration source, delimited by the line markers.
A block of content delimited by comments can help you manage several lines
without worrying about old entries removal.
marker_start
The line content identifying a line as the start of the content block.
Note that the whole line containing this marker will be considered,
so whitespace or extra content before or after the marker is included
in final output.
marker_end
The line content identifying a line as the end of the content block.
Note that the whole line containing this marker will be considered,
so whitespace or extra content before or after the marker is included
in final output.
content
The content to be used between the two lines identified by
``marker_start`` and ``marker_stop``.
append_if_not_found: ``False``
If markers are not found and set to True then, the markers and content
will be appended to the file.
prepend_if_not_found: ``False``
If markers are not found and set to True then, the markers and content
will be prepended to the file.
append_newline: ``False``
Controls whether or not a newline is appended to the content block.
If the value of this argument is ``True`` then a newline will be added
to the content block. If it is ``False``, then a newline will not be
added to the content block. If it is ``None`` then a newline will only
be added to the content block if it does not already end in a newline.
show_changes: ``True``
Controls how changes are presented. If ``True``, this function will
return the of the changes made.
If ``False``, then it will return a boolean (``True`` if any changes
were made, otherwise False).
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path: ``None``
Save the temporary configuration to a specific path, then read from
there. This argument is optional, can be used when you prefers a
particular location of the temporary file.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
CLI Example:
.. code-block:: bash
salt '*' net.blockreplace 'ntp' 'interface' ''
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
replace_pattern = __salt__['file.blockreplace'](path,
marker_start=marker_start,
marker_end=marker_end,
content=content,
append_if_not_found=append_if_not_found,
prepend_if_not_found=prepend_if_not_found,
show_changes=show_changes,
append_newline=append_newline)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
def patch(patchfile,
options='',
saltenv='base',
source_hash=None,
show_changes=True,
source='running',
path=None,
test=False,
commit=True,
debug=False,
replace=True):
'''
.. versionadded:: 2019.2.0
Apply a patch to the configuration source, and load the result into the
running config of the device.
patchfile
A patch file to apply to the configuration source.
options
Options to pass to patch.
source_hash
If the patch file (specified via the ``patchfile`` argument) is an
HTTP(S) or FTP URL and the file exists in the minion's file cache, this
option can be passed to keep the minion from re-downloading the file if
the cached copy matches the specified hash.
show_changes: ``True``
Controls how changes are presented. If ``True``, this function will
return the of the changes made.
If ``False``, then it will return a boolean (``True`` if any changes
were made, otherwise False).
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path: ``None``
Save the temporary configuration to a specific path, then read from
there. This argument is optional, can the user prefers a particular
location of the temporary file.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
CLI Example:
.. code-block:: bash
salt '*' net.patch https://example.com/running_config.patch
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
patchfile_cache = __salt__['cp.cache_file'](patchfile)
if patchfile_cache is False:
return {
'out': None,
'result': False,
'comment': 'The file "{}" does not exist.'.format(patchfile)
}
replace_pattern = __salt__['file.patch'](path,
patchfile_cache,
options=options)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
# <---- Configuration specific functions -------------------------------------------------------------------------------
|
saltstack/salt
|
salt/modules/napalm_network.py
|
_filter_dict
|
python
|
def _filter_dict(input_dict, search_key, search_value):
'''
Filters a dictionary of dictionaries by a key-value pair.
:param input_dict: is a dictionary whose values are lists of dictionaries
:param search_key: is the key in the leaf dictionaries
:param search_values: is the value in the leaf dictionaries
:return: filtered dictionary
'''
output_dict = dict()
for key, key_list in six.iteritems(input_dict):
key_list_filtered = _filter_list(key_list, search_key, search_value)
if key_list_filtered:
output_dict[key] = key_list_filtered
return output_dict
|
Filters a dictionary of dictionaries by a key-value pair.
:param input_dict: is a dictionary whose values are lists of dictionaries
:param search_key: is the key in the leaf dictionaries
:param search_values: is the value in the leaf dictionaries
:return: filtered dictionary
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_network.py#L90-L108
| null |
# -*- coding: utf-8 -*-
'''
NAPALM Network
==============
Basic methods for interaction with the network device through the virtual proxy 'napalm'.
:codeauthor: Mircea Ulinic <mircea@cloudflare.com> & Jerome Fleury <jf@cloudflare.com>
:maturity: new
:depends: napalm
:platform: unix
Dependencies
------------
- :mod:`napalm proxy minion <salt.proxy.napalm>`
.. versionadded:: 2016.11.0
.. versionchanged:: 2017.7.0
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import time
import logging
import datetime
log = logging.getLogger(__name__)
# Import Salt libs
from salt.ext import six
import salt.utils.files
import salt.utils.napalm
import salt.utils.versions
import salt.utils.templates
# Import 3rd-party libs
try:
import jxmlease # pylint: disable=unused-import
HAS_JXMLEASE = True
except ImportError:
HAS_JXMLEASE = False
# ----------------------------------------------------------------------------------------------------------------------
# module properties
# ----------------------------------------------------------------------------------------------------------------------
__virtualname__ = 'net'
__proxyenabled__ = ['*']
__virtual_aliases__ = ('napalm_net',)
# uses NAPALM-based proxy to interact with network devices
# ----------------------------------------------------------------------------------------------------------------------
# property functions
# ----------------------------------------------------------------------------------------------------------------------
def __virtual__():
'''
NAPALM library must be installed for this module to work and run in a (proxy) minion.
'''
return salt.utils.napalm.virtual(__opts__, __virtualname__, __file__)
# ----------------------------------------------------------------------------------------------------------------------
# helper functions -- will not be exported
# ----------------------------------------------------------------------------------------------------------------------
def _filter_list(input_list, search_key, search_value):
'''
Filters a list of dictionary by a set of key-value pair.
:param input_list: is a list of dictionaries
:param search_key: is the key we are looking for
:param search_value: is the value we are looking for the key specified in search_key
:return: filered list of dictionaries
'''
output_list = list()
for dictionary in input_list:
if dictionary.get(search_key) == search_value:
output_list.append(dictionary)
return output_list
def _safe_commit_config(loaded_result, napalm_device):
_commit = commit(inherit_napalm_device=napalm_device) # calls the function commit, defined below
if not _commit.get('result', False):
# if unable to commit
loaded_result['comment'] += _commit['comment'] if _commit.get('comment') else 'Unable to commit.'
loaded_result['result'] = False
# unable to commit, something went wrong
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
return _commit
def _safe_dicard_config(loaded_result, napalm_device):
'''
'''
log.debug('Discarding the config')
log.debug(loaded_result)
_discarded = discard_config(inherit_napalm_device=napalm_device)
if not _discarded.get('result', False):
loaded_result['comment'] += _discarded['comment'] if _discarded.get('comment') \
else 'Unable to discard config.'
loaded_result['result'] = False
# make sure it notifies
# that something went wrong
_explicit_close(napalm_device)
__context__['retcode'] = 1
return loaded_result
return _discarded
def _explicit_close(napalm_device):
'''
Will explicily close the config session with the network device,
when running in a now-always-alive proxy minion or regular minion.
This helper must be used in configuration-related functions,
as the session is preserved and not closed before making any changes.
'''
if salt.utils.napalm.not_always_alive(__opts__):
# force closing the configuration session
# when running in a non-always-alive proxy
# or regular minion
try:
napalm_device['DRIVER'].close()
except Exception as err:
log.error('Unable to close the temp connection with the device:')
log.error(err)
log.error('Please report.')
def _config_logic(napalm_device,
loaded_result,
test=False,
debug=False,
replace=False,
commit_config=True,
loaded_config=None,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
commit_jid=None,
**kwargs):
'''
Builds the config logic for `load_config` and `load_template` functions.
'''
# As the Salt logic is built around independent events
# when it comes to configuration changes in the
# candidate DB on the network devices, we need to
# make sure we're using the same session.
# Hence, we need to pass the same object around.
# the napalm_device object is inherited from
# the load_config or load_template functions
# and forwarded to compare, discard, commit etc.
# then the decorator will make sure that
# if not proxy (when the connection is always alive)
# and the `inherit_napalm_device` is set,
# `napalm_device` will be overridden.
# See `salt.utils.napalm.proxy_napalm_wrap` decorator.
current_jid = kwargs.get('__pub_jid')
if not current_jid:
current_jid = '{0:%Y%m%d%H%M%S%f}'.format(datetime.datetime.now())
loaded_result['already_configured'] = False
loaded_result['loaded_config'] = ''
if debug:
loaded_result['loaded_config'] = loaded_config
_compare = compare_config(inherit_napalm_device=napalm_device)
if _compare.get('result', False):
loaded_result['diff'] = _compare.get('out')
loaded_result.pop('out', '') # not needed
else:
loaded_result['diff'] = None
loaded_result['result'] = False
loaded_result['comment'] = _compare.get('comment')
__context__['retcode'] = 1
return loaded_result
_loaded_res = loaded_result.get('result', False)
if not _loaded_res or test:
# if unable to load the config (errors / warnings)
# or in testing mode,
# will discard the config
if loaded_result['comment']:
loaded_result['comment'] += '\n'
if not loaded_result.get('diff', ''):
loaded_result['already_configured'] = True
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
loaded_result['comment'] += 'Configuration discarded.'
# loaded_result['result'] = False not necessary
# as the result can be true when test=True
_explicit_close(napalm_device)
if not loaded_result['result']:
__context__['retcode'] = 1
return loaded_result
if not test and commit_config:
# if not in testing mode and trying to commit
if commit_jid:
log.info('Committing the JID: %s', str(commit_jid))
removed = cancel_commit(commit_jid)
log.debug('Cleaned up the commit from the schedule')
log.debug(removed['comment'])
if loaded_result.get('diff', ''):
# if not testing mode
# and also the user wants to commit (default)
# and there are changes to commit
if commit_in or commit_at:
commit_time = __utils__['timeutil.get_time_at'](time_in=commit_in,
time_at=commit_in)
# schedule job
scheduled_job_name = '__napalm_commit_{}'.format(current_jid)
temp_file = salt.utils.files.mkstemp()
with salt.utils.files.fopen(temp_file, 'w') as fp_:
fp_.write(loaded_config)
scheduled = __salt__['schedule.add'](scheduled_job_name,
function='net.load_config',
job_kwargs={
'filename': temp_file,
'commit_jid': current_jid,
'replace': replace
},
once=commit_time)
log.debug('Scheduling job')
log.debug(scheduled)
saved = __salt__['schedule.save']() # ensure the schedule is
# persistent cross Minion restart
discarded = _safe_dicard_config(loaded_result, napalm_device)
# discard the changes
if not discarded['result']:
discarded['comment'] += ('Scheduled the job to be executed at {schedule_ts}, '
'but was unable to discard the config: \n').format(schedule_ts=commit_time)
return discarded
loaded_result['comment'] = ('Changes discarded for now, and scheduled commit at: {schedule_ts}.\n'
'The commit ID is: {current_jid}.\n'
'To discard this commit, you can execute: \n\n'
'salt {min_id} net.cancel_commit {current_jid}').format(schedule_ts=commit_time,
min_id=__opts__['id'],
current_jid=current_jid)
loaded_result['commit_id'] = current_jid
return loaded_result
log.debug('About to commit:')
log.debug(loaded_result['diff'])
if revert_in or revert_at:
revert_time = __utils__['timeutil.get_time_at'](time_in=revert_in,
time_at=revert_at)
if __grains__['os'] == 'junos':
if not HAS_JXMLEASE:
loaded_result['comment'] = ('This feature requires the library jxmlease to be installed.\n'
'To install, please execute: ``pip install jxmlease``.')
loaded_result['result'] = False
return loaded_result
timestamp_at = __utils__['timeutil.get_timestamp_at'](time_in=revert_in,
time_at=revert_at)
minutes = int((timestamp_at - time.time())/60)
_comm = __salt__['napalm.junos_commit'](confirm=minutes)
if not _comm['out']:
# If unable to commit confirm, should try to bail out
loaded_result['comment'] = 'Unable to commit confirm: {}'.format(_comm['message'])
loaded_result['result'] = False
# But before exiting, we must gracefully discard the config
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
else:
temp_file = salt.utils.files.mkstemp()
running_config = __salt__['net.config'](source='running')['out']['running']
with salt.utils.files.fopen(temp_file, 'w') as fp_:
fp_.write(running_config)
committed = _safe_commit_config(loaded_result, napalm_device)
if not committed['result']:
# If unable to commit, dicard the config (which is
# already done by the _safe_commit_config function), and
# return with the command and other details.
return loaded_result
scheduled_job_name = '__napalm_commit_{}'.format(current_jid)
scheduled = __salt__['schedule.add'](scheduled_job_name,
function='net.load_config',
job_kwargs={
'filename': temp_file,
'commit_jid': current_jid,
'replace': True
},
once=revert_time)
log.debug('Scheduling commit confirmed')
log.debug(scheduled)
saved = __salt__['schedule.save']()
loaded_result['comment'] = ('The commit ID is: {current_jid}.\n'
'This commit will be reverted at: {schedule_ts}, unless confirmed.\n'
'To confirm the commit and avoid reverting, you can execute:\n\n'
'salt {min_id} net.confirm_commit {current_jid}').format(schedule_ts=revert_time,
min_id=__opts__['id'],
current_jid=current_jid)
loaded_result['commit_id'] = current_jid
return loaded_result
committed = _safe_commit_config(loaded_result, napalm_device)
if not committed['result']:
return loaded_result
else:
# would like to commit, but there's no change
# need to call discard_config() to release the config DB
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
loaded_result['already_configured'] = True
loaded_result['comment'] = 'Already configured.'
_explicit_close(napalm_device)
if not loaded_result['result']:
__context__['retcode'] = 1
return loaded_result
# ----------------------------------------------------------------------------------------------------------------------
# callable functions
# ----------------------------------------------------------------------------------------------------------------------
@salt.utils.napalm.proxy_napalm_wrap
def connected(**kwargs): # pylint: disable=unused-argument
'''
Specifies if the connection to the device succeeded.
CLI Example:
.. code-block:: bash
salt '*' net.connected
'''
return {
'out': napalm_device.get('UP', False) # pylint: disable=undefined-variable
}
@salt.utils.napalm.proxy_napalm_wrap
def facts(**kwargs): # pylint: disable=unused-argument
'''
Returns characteristics of the network device.
:return: a dictionary with the following keys:
* uptime - Uptime of the device in seconds.
* vendor - Manufacturer of the device.
* model - Device model.
* hostname - Hostname of the device
* fqdn - Fqdn of the device
* os_version - String with the OS version running on the device.
* serial_number - Serial number of the device
* interface_list - List of the interfaces of the device
CLI Example:
.. code-block:: bash
salt '*' net.facts
Example output:
.. code-block:: python
{
'os_version': '13.3R6.5',
'uptime': 10117140,
'interface_list': [
'lc-0/0/0',
'pfe-0/0/0',
'pfh-0/0/0',
'xe-0/0/0',
'xe-0/0/1',
'xe-0/0/2',
'xe-0/0/3',
'gr-0/0/10',
'ip-0/0/10'
],
'vendor': 'Juniper',
'serial_number': 'JN131356FBFA',
'model': 'MX480',
'hostname': 're0.edge05.syd01',
'fqdn': 're0.edge05.syd01'
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_facts',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def environment(**kwargs): # pylint: disable=unused-argument
'''
Returns the environment of the device.
CLI Example:
.. code-block:: bash
salt '*' net.environment
Example output:
.. code-block:: python
{
'fans': {
'Bottom Rear Fan': {
'status': True
},
'Bottom Middle Fan': {
'status': True
},
'Top Middle Fan': {
'status': True
},
'Bottom Front Fan': {
'status': True
},
'Top Front Fan': {
'status': True
},
'Top Rear Fan': {
'status': True
}
},
'memory': {
'available_ram': 16349,
'used_ram': 4934
},
'temperature': {
'FPC 0 Exhaust A': {
'is_alert': False,
'temperature': 35.0,
'is_critical': False
}
},
'cpu': {
'1': {
'%usage': 19.0
},
'0': {
'%usage': 35.0
}
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_environment',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def cli(*commands, **kwargs): # pylint: disable=unused-argument
'''
Returns a dictionary with the raw output of all commands passed as arguments.
commands
List of commands to be executed on the device.
textfsm_parse: ``False``
Try parsing the outputs using the TextFSM templates.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``napalm_cli_textfsm_parse``.
textfsm_path
The path where the TextFSM templates can be found. This option implies
the usage of the TextFSM index file.
``textfsm_path`` can be either absolute path on the server,
either specified using the following URL mschemes: ``file://``,
``salt://``, ``http://``, ``https://``, ``ftp://``,
``s3://``, ``swift://``.
.. versionadded:: 2018.3.0
.. note::
This needs to be a directory with a flat structure, having an
index file (whose name can be specified using the ``index_file`` option)
and a number of TextFSM templates.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_path``.
textfsm_template
The path to a certain the TextFSM template.
This can be specified using the absolute path
to the file, or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
.. versionadded:: 2018.3.0
textfsm_template_dict
A dictionary with the mapping between a command
and the corresponding TextFSM path to use to extract the data.
The TextFSM paths can be specified as in ``textfsm_template``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``napalm_cli_textfsm_template_dict``.
platform_grain_name: ``os``
The name of the grain used to identify the platform name
in the TextFSM index file. Default: ``os``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_grain``.
platform_column_name: ``Platform``
The column name used to identify the platform,
exactly as specified in the TextFSM index file.
Default: ``Platform``.
.. versionadded:: 2018.3.0
.. note::
This is field is case sensitive, make sure
to assign the correct value to this option,
exactly as defined in the index file.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_column_name``.
index_file: ``index``
The name of the TextFSM index file, under the ``textfsm_path``. Default: ``index``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_index_file``.
saltenv: ``base``
Salt fileserver envrionment from which to retrieve the file.
Ignored if ``textfsm_path`` is not a ``salt://`` URL.
.. versionadded:: 2018.3.0
include_empty: ``False``
Include empty files under the ``textfsm_path``.
.. versionadded:: 2018.3.0
include_pat
Glob or regex to narrow down the files cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. versionadded:: 2018.3.0
exclude_pat
Glob or regex to exclude certain files from being cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. versionadded:: 2018.3.0
.. note::
If used with ``include_pat``, files matching this pattern will be
excluded from the subset of files defined by ``include_pat``.
CLI Example:
.. code-block:: bash
salt '*' net.cli "show version" "show chassis fan"
CLI Example with TextFSM template:
.. code-block:: bash
salt '*' net.cli textfsm_parse=True textfsm_path=salt://textfsm/
Example output:
.. code-block:: python
{
'show version and haiku': 'Hostname: re0.edge01.arn01
Model: mx480
Junos: 13.3R6.5
Help me, Obi-Wan
I just saw Episode Two
You're my only hope
',
'show chassis fan' : 'Item Status RPM Measurement
Top Rear Fan OK 3840 Spinning at intermediate-speed
Bottom Rear Fan OK 3840 Spinning at intermediate-speed
Top Middle Fan OK 3900 Spinning at intermediate-speed
Bottom Middle Fan OK 3840 Spinning at intermediate-speed
Top Front Fan OK 3810 Spinning at intermediate-speed
Bottom Front Fan OK 3840 Spinning at intermediate-speed
'
}
Example output with TextFSM parsing:
.. code-block:: json
{
"comment": "",
"result": true,
"out": {
"sh ver": [
{
"kernel": "9.1S3.5",
"documentation": "9.1S3.5",
"boot": "9.1S3.5",
"crypto": "9.1S3.5",
"chassis": "",
"routing": "9.1S3.5",
"base": "9.1S3.5",
"model": "mx960"
}
]
}
}
'''
raw_cli_outputs = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'cli',
**{
'commands': list(commands)
}
)
# thus we can display the output as is
# in case of errors, they'll be catched in the proxy
if not raw_cli_outputs['result']:
# Error -> dispaly the output as-is.
return raw_cli_outputs
textfsm_parse = kwargs.get('textfsm_parse') or __opts__.get('napalm_cli_textfsm_parse') or\
__pillar__.get('napalm_cli_textfsm_parse', False)
if not textfsm_parse:
# No TextFSM parsing required, return raw commands.
log.debug('No TextFSM parsing requested.')
return raw_cli_outputs
if 'textfsm.extract' not in __salt__ or 'textfsm.index' not in __salt__:
raw_cli_outputs['comment'] += 'Unable to process: is TextFSM installed?'
log.error(raw_cli_outputs['comment'])
return raw_cli_outputs
textfsm_template = kwargs.get('textfsm_template')
log.debug('textfsm_template: %s', textfsm_template)
textfsm_path = kwargs.get('textfsm_path') or __opts__.get('textfsm_path') or\
__pillar__.get('textfsm_path')
log.debug('textfsm_path: %s', textfsm_path)
textfsm_template_dict = kwargs.get('textfsm_template_dict') or __opts__.get('napalm_cli_textfsm_template_dict') or\
__pillar__.get('napalm_cli_textfsm_template_dict', {})
log.debug('TextFSM command-template mapping: %s', textfsm_template_dict)
index_file = kwargs.get('index_file') or __opts__.get('textfsm_index_file') or\
__pillar__.get('textfsm_index_file')
log.debug('index_file: %s', index_file)
platform_grain_name = kwargs.get('platform_grain_name') or __opts__.get('textfsm_platform_grain') or\
__pillar__.get('textfsm_platform_grain', 'os')
log.debug('platform_grain_name: %s', platform_grain_name)
platform_column_name = kwargs.get('platform_column_name') or __opts__.get('textfsm_platform_column_name') or\
__pillar__.get('textfsm_platform_column_name', 'Platform')
log.debug('platform_column_name: %s', platform_column_name)
saltenv = kwargs.get('saltenv', 'base')
include_empty = kwargs.get('include_empty', False)
include_pat = kwargs.get('include_pat')
exclude_pat = kwargs.get('exclude_pat')
processed_cli_outputs = {
'comment': raw_cli_outputs.get('comment', ''),
'result': raw_cli_outputs['result'],
'out': {}
}
log.debug('Starting to analyse the raw outputs')
for command in list(commands):
command_output = raw_cli_outputs['out'][command]
log.debug('Output from command: %s', command)
log.debug(command_output)
processed_command_output = None
if textfsm_path:
log.debug('Using the templates under %s', textfsm_path)
processed_cli_output = __salt__['textfsm.index'](command,
platform_grain_name=platform_grain_name,
platform_column_name=platform_column_name,
output=command_output.strip(),
textfsm_path=textfsm_path,
saltenv=saltenv,
include_empty=include_empty,
include_pat=include_pat,
exclude_pat=exclude_pat)
log.debug('Processed CLI output:')
log.debug(processed_cli_output)
if not processed_cli_output['result']:
log.debug('Apparently this didnt work, returnin the raw output')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {0}: {1}.'.format(command,
processed_cli_output['comment'])
log.error(processed_cli_outputs['comment'])
elif processed_cli_output['out']:
log.debug('All good, %s has a nice output!', command)
processed_command_output = processed_cli_output['out']
else:
comment = '''\nProcessing "{}" didn't fail, but didn't return anything either. Dumping raw.'''.format(
command)
processed_cli_outputs['comment'] += comment
log.error(comment)
processed_command_output = command_output
elif textfsm_template or command in textfsm_template_dict:
if command in textfsm_template_dict:
textfsm_template = textfsm_template_dict[command]
log.debug('Using %s to process the command: %s', textfsm_template, command)
processed_cli_output = __salt__['textfsm.extract'](textfsm_template,
raw_text=command_output,
saltenv=saltenv)
log.debug('Processed CLI output:')
log.debug(processed_cli_output)
if not processed_cli_output['result']:
log.debug('Apparently this didnt work, returning '
'the raw output')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {0}: {1}'.format(command,
processed_cli_output['comment'])
log.error(processed_cli_outputs['comment'])
elif processed_cli_output['out']:
log.debug('All good, %s has a nice output!', command)
processed_command_output = processed_cli_output['out']
else:
log.debug('Processing %s didnt fail, but didnt return'
' anything either. Dumping raw.', command)
processed_command_output = command_output
else:
log.error('No TextFSM template specified, or no TextFSM path defined')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {}.'.format(command)
processed_cli_outputs['out'][command] = processed_command_output
processed_cli_outputs['comment'] = processed_cli_outputs['comment'].strip()
return processed_cli_outputs
@salt.utils.napalm.proxy_napalm_wrap
def traceroute(destination, source=None, ttl=None, timeout=None, vrf=None, **kwargs): # pylint: disable=unused-argument
'''
Calls the method traceroute from the NAPALM driver object and returns a dictionary with the result of the traceroute
command executed on the device.
destination
Hostname or address of remote host
source
Source address to use in outgoing traceroute packets
ttl
IP maximum time-to-live value (or IPv6 maximum hop-limit value)
timeout
Number of seconds to wait for response (seconds)
vrf
VRF (routing instance) for traceroute attempt
.. versionadded:: 2016.11.4
CLI Example:
.. code-block:: bash
salt '*' net.traceroute 8.8.8.8
salt '*' net.traceroute 8.8.8.8 source=127.0.0.1 ttl=5 timeout=1
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'traceroute',
**{
'destination': destination,
'source': source,
'ttl': ttl,
'timeout': timeout,
'vrf': vrf
}
)
@salt.utils.napalm.proxy_napalm_wrap
def ping(destination, source=None, ttl=None, timeout=None, size=None, count=None, vrf=None, **kwargs): # pylint: disable=unused-argument
'''
Executes a ping on the network device and returns a dictionary as a result.
destination
Hostname or IP address of remote host
source
Source address of echo request
ttl
IP time-to-live value (IPv6 hop-limit value) (1..255 hops)
timeout
Maximum wait time after sending final packet (seconds)
size
Size of request packets (0..65468 bytes)
count
Number of ping requests to send (1..2000000000 packets)
vrf
VRF (routing instance) for ping attempt
.. versionadded:: 2016.11.4
CLI Example:
.. code-block:: bash
salt '*' net.ping 8.8.8.8
salt '*' net.ping 8.8.8.8 ttl=3 size=65468
salt '*' net.ping 8.8.8.8 source=127.0.0.1 timeout=1 count=100
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'ping',
**{
'destination': destination,
'source': source,
'ttl': ttl,
'timeout': timeout,
'size': size,
'count': count,
'vrf': vrf
}
)
@salt.utils.napalm.proxy_napalm_wrap
def arp(interface='', ipaddr='', macaddr='', **kwargs): # pylint: disable=unused-argument
'''
NAPALM returns a list of dictionaries with details of the ARP entries.
:param interface: interface name to filter on
:param ipaddr: IP address to filter on
:param macaddr: MAC address to filter on
:return: List of the entries in the ARP table
CLI Example:
.. code-block:: bash
salt '*' net.arp
salt '*' net.arp macaddr='5c:5e:ab:da:3c:f0'
Example output:
.. code-block:: python
[
{
'interface' : 'MgmtEth0/RSP0/CPU0/0',
'mac' : '5c:5e:ab:da:3c:f0',
'ip' : '172.17.17.1',
'age' : 1454496274.84
},
{
'interface': 'MgmtEth0/RSP0/CPU0/0',
'mac' : '66:0e:94:96:e0:ff',
'ip' : '172.17.17.2',
'age' : 1435641582.49
}
]
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_arp_table',
**{
}
)
if not proxy_output.get('result'):
return proxy_output
arp_table = proxy_output.get('out')
if interface:
arp_table = _filter_list(arp_table, 'interface', interface)
if ipaddr:
arp_table = _filter_list(arp_table, 'ip', ipaddr)
if macaddr:
arp_table = _filter_list(arp_table, 'mac', macaddr)
proxy_output.update({
'out': arp_table
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def ipaddrs(**kwargs): # pylint: disable=unused-argument
'''
Returns IP addresses configured on the device.
:return: A dictionary with the IPv4 and IPv6 addresses of the interfaces.
Returns all configured IP addresses on all interfaces as a dictionary
of dictionaries. Keys of the main dictionary represent the name of the
interface. Values of the main dictionary represent are dictionaries
that may consist of two keys 'ipv4' and 'ipv6' (one, both or none)
which are themselvs dictionaries with the IP addresses as keys.
CLI Example:
.. code-block:: bash
salt '*' net.ipaddrs
Example output:
.. code-block:: python
{
'FastEthernet8': {
'ipv4': {
'10.66.43.169': {
'prefix_length': 22
}
}
},
'Loopback555': {
'ipv4': {
'192.168.1.1': {
'prefix_length': 24
}
},
'ipv6': {
'1::1': {
'prefix_length': 64
},
'2001:DB8:1::1': {
'prefix_length': 64
},
'FE80::3': {
'prefix_length': 'N/A'
}
}
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_interfaces_ip',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def interfaces(**kwargs): # pylint: disable=unused-argument
'''
Returns details of the interfaces on the device.
:return: Returns a dictionary of dictionaries. The keys for the first
dictionary will be the interfaces in the devices.
CLI Example:
.. code-block:: bash
salt '*' net.interfaces
Example output:
.. code-block:: python
{
'Management1': {
'is_up': False,
'is_enabled': False,
'description': '',
'last_flapped': -1,
'speed': 1000,
'mac_address': 'dead:beef:dead',
},
'Ethernet1':{
'is_up': True,
'is_enabled': True,
'description': 'foo',
'last_flapped': 1429978575.1554043,
'speed': 1000,
'mac_address': 'beef:dead:beef',
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_interfaces',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def lldp(interface='', **kwargs): # pylint: disable=unused-argument
'''
Returns a detailed view of the LLDP neighbors.
:param interface: interface name to filter on
:return: A dictionary with the LLDL neighbors. The keys are the
interfaces with LLDP activated on.
CLI Example:
.. code-block:: bash
salt '*' net.lldp
salt '*' net.lldp interface='TenGigE0/0/0/8'
Example output:
.. code-block:: python
{
'TenGigE0/0/0/8': [
{
'parent_interface': 'Bundle-Ether8',
'interface_description': 'TenGigE0/0/0/8',
'remote_chassis_id': '8c60.4f69.e96c',
'remote_system_name': 'switch',
'remote_port': 'Eth2/2/1',
'remote_port_description': 'Ethernet2/2/1',
'remote_system_description': 'Cisco Nexus Operating System (NX-OS) Software 7.1(0)N1(1a)
TAC support: http://www.cisco.com/tac
Copyright (c) 2002-2015, Cisco Systems, Inc. All rights reserved.',
'remote_system_capab': 'B, R',
'remote_system_enable_capab': 'B'
}
]
}
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_lldp_neighbors_detail',
**{
}
)
if not proxy_output.get('result'):
return proxy_output
lldp_neighbors = proxy_output.get('out')
if interface:
lldp_neighbors = {interface: lldp_neighbors.get(interface)}
proxy_output.update({
'out': lldp_neighbors
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def mac(address='', interface='', vlan=0, **kwargs): # pylint: disable=unused-argument
'''
Returns the MAC Address Table on the device.
:param address: MAC address to filter on
:param interface: Interface name to filter on
:param vlan: VLAN identifier
:return: A list of dictionaries representing the entries in the MAC Address Table
CLI Example:
.. code-block:: bash
salt '*' net.mac
salt '*' net.mac vlan=10
Example output:
.. code-block:: python
[
{
'mac' : '00:1c:58:29:4a:71',
'interface' : 'xe-3/0/2',
'static' : False,
'active' : True,
'moves' : 1,
'vlan' : 10,
'last_move' : 1454417742.58
},
{
'mac' : '8c:60:4f:58:e1:c1',
'interface' : 'xe-1/0/1',
'static' : False,
'active' : True,
'moves' : 2,
'vlan' : 42,
'last_move' : 1453191948.11
}
]
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_mac_address_table',
**{
}
)
if not proxy_output.get('result'):
# if negative, leave the output unchanged
return proxy_output
mac_address_table = proxy_output.get('out')
if vlan and isinstance(vlan, int):
mac_address_table = _filter_list(mac_address_table, 'vlan', vlan)
if address:
mac_address_table = _filter_list(mac_address_table, 'mac', address)
if interface:
mac_address_table = _filter_list(mac_address_table, 'interface', interface)
proxy_output.update({
'out': mac_address_table
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def config(source=None, **kwargs): # pylint: disable=unused-argument
'''
.. versionadded:: 2017.7.0
Return the whole configuration of the network device. By default, it will
return all possible configuration sources supported by the network device.
At most, there will be:
- running config
- startup config
- candidate config
To return only one of the configurations, you can use the ``source``
argument.
source
Which configuration type you want to display, default is all of them.
Options:
- running
- candidate
- startup
:return:
The object returned is a dictionary with the following keys:
- running (string): Representation of the native running configuration.
- candidate (string): Representation of the native candidate configuration.
If the device doesn't differentiate between running and startup
configuration this will an empty string.
- startup (string): Representation of the native startup configuration.
If the device doesn't differentiate between running and startup
configuration this will an empty string.
CLI Example:
.. code-block:: bash
salt '*' net.config
salt '*' net.config source=candidate
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_config',
**{
'retrieve': source
}
)
@salt.utils.napalm.proxy_napalm_wrap
def optics(**kwargs): # pylint: disable=unused-argument
'''
.. versionadded:: 2017.7.0
Fetches the power usage on the various transceivers installed
on the network device (in dBm), and returns a view that conforms with the
OpenConfig model openconfig-platform-transceiver.yang.
:return:
Returns a dictionary where the keys are as listed below:
* intf_name (unicode)
* physical_channels
* channels (list of dicts)
* index (int)
* state
* input_power
* instant (float)
* avg (float)
* min (float)
* max (float)
* output_power
* instant (float)
* avg (float)
* min (float)
* max (float)
* laser_bias_current
* instant (float)
* avg (float)
* min (float)
* max (float)
CLI Example:
.. code-block:: bash
salt '*' net.optics
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_optics',
**{
}
)
# <---- Call NAPALM getters --------------------------------------------------------------------------------------------
# ----- Configuration specific functions ------------------------------------------------------------------------------>
@salt.utils.napalm.proxy_napalm_wrap
def load_config(filename=None,
text=None,
test=False,
commit=True,
debug=False,
replace=False,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
commit_jid=None,
inherit_napalm_device=None,
saltenv='base',
**kwargs): # pylint: disable=unused-argument
'''
Applies configuration changes on the device. It can be loaded from a file or from inline string.
If you send both a filename and a string containing the configuration, the file has higher precedence.
By default this function will commit the changes. If there are no changes, it does not commit and
the flag ``already_configured`` will be set as ``True`` to point this out.
To avoid committing the configuration, set the argument ``test`` to ``True`` and will discard (dry run).
To keep the changes but not commit, set ``commit`` to ``False``.
To replace the config, set ``replace`` to ``True``.
filename
Path to the file containing the desired configuration.
This can be specified using the absolute path to the file,
or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
.. versionchanged:: 2018.3.0
text
String containing the desired configuration.
This argument is ignored when ``filename`` is specified.
test: False
Dry run? If set as ``True``, will apply the config, discard and return the changes. Default: ``False``
and will commit the changes on the device.
commit: True
Commit? Default: ``True``.
debug: False
Debug mode. Will insert a new key under the output dictionary, as ``loaded_config`` containing the raw
configuration loaded on the device.
.. versionadded:: 2016.11.2
replace: False
Load and replace the configuration. Default: ``False``.
.. versionadded:: 2016.11.2
commit_in: ``None``
Commit the changes in a specific number of minutes / hours. Example of
accepted formats: ``5`` (commit in 5 minutes), ``2m`` (commit in 2
minutes), ``1h`` (commit the changes in 1 hour)`, ``5h30m`` (commit
the changes in 5 hours and 30 minutes).
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
commit_at: ``None``
Commit the changes at a specific time. Example of accepted formats:
``1am`` (will commit the changes at the next 1AM), ``13:20`` (will
commit at 13:20), ``1:20am``, etc.
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
revert_in: ``None``
Commit and revert the changes in a specific number of minutes / hours.
Example of accepted formats: ``5`` (revert in 5 minutes), ``2m`` (revert
in 2 minutes), ``1h`` (revert the changes in 1 hour)`, ``5h30m`` (revert
the changes in 5 hours and 30 minutes).
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
revert_at: ``None``
Commit and revert the changes at a specific time. Example of accepted
formats: ``1am`` (will commit and revert the changes at the next 1AM),
``13:20`` (will commit and revert at 13:20), ``1:20am``, etc.
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
saltenv: ``base``
Specifies the Salt environment name.
.. versionadded:: 2018.3.0
:return: a dictionary having the following keys:
* result (bool): if the config was applied successfully. It is ``False`` only in case of failure. In case \
there are no changes to be applied and successfully performs all operations it is still ``True`` and so will be \
the ``already_configured`` flag (example below)
* comment (str): a message for the user
* already_configured (bool): flag to check if there were no changes applied
* loaded_config (str): the configuration loaded on the device. Requires ``debug`` to be set as ``True``
* diff (str): returns the config changes applied
CLI Example:
.. code-block:: bash
salt '*' net.load_config text='ntp peer 192.168.0.1'
salt '*' net.load_config filename='/absolute/path/to/your/file'
salt '*' net.load_config filename='/absolute/path/to/your/file' test=True
salt '*' net.load_config filename='/absolute/path/to/your/file' commit=False
Example output:
.. code-block:: python
{
'comment': 'Configuration discarded.',
'already_configured': False,
'result': True,
'diff': '[edit interfaces xe-0/0/5]+ description "Adding a description";'
}
'''
fun = 'load_merge_candidate'
if replace:
fun = 'load_replace_candidate'
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
if filename:
text = __salt__['cp.get_file_str'](filename, saltenv=saltenv)
if text is False:
# When using salt:// or https://, if the resource is not available,
# it will either raise an exception, or return False.
ret = {
'result': False,
'out': None
}
ret['comment'] = 'Unable to read from {}. Please specify a valid file or text.'.format(filename)
log.error(ret['comment'])
return ret
if commit_jid:
# When the commit_jid argument is passed, it probably is a scheduled
# commit to be executed, and filename is a temporary file which
# can be removed after reading it.
salt.utils.files.safe_rm(filename)
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
fun,
**{
'config': text
}
)
return _config_logic(napalm_device, # pylint: disable=undefined-variable
_loaded,
test=test,
debug=debug,
replace=replace,
commit_config=commit,
loaded_config=text,
commit_at=commit_at,
commit_in=commit_in,
revert_in=revert_in,
revert_at=revert_at,
commit_jid=commit_jid,
**kwargs)
@salt.utils.napalm.proxy_napalm_wrap
def load_template(template_name=None,
template_source=None,
context=None,
defaults=None,
template_engine='jinja',
saltenv='base',
template_hash=None,
template_hash_name=None,
skip_verify=False,
test=False,
commit=True,
debug=False,
replace=False,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
inherit_napalm_device=None, # pylint: disable=unused-argument
**template_vars):
'''
Renders a configuration template (default: Jinja) and loads the result on the device.
By default this function will commit the changes. If there are no changes,
it does not commit, discards he config and the flag ``already_configured``
will be set as ``True`` to point this out.
To avoid committing the configuration, set the argument ``test`` to ``True``
and will discard (dry run).
To preserve the changes, set ``commit`` to ``False``.
However, this is recommended to be used only in exceptional cases
when there are applied few consecutive states
and/or configuration changes.
Otherwise the user might forget that the config DB is locked
and the candidate config buffer is not cleared/merged in the running config.
To replace the config, set ``replace`` to ``True``.
template_name
Identifies path to the template source.
The template can be either stored on the local machine, either remotely.
The recommended location is under the ``file_roots``
as specified in the master config file.
For example, let's suppose the ``file_roots`` is configured as:
.. code-block:: yaml
file_roots:
base:
- /etc/salt/states
Placing the template under ``/etc/salt/states/templates/example.jinja``,
it can be used as ``salt://templates/example.jinja``.
Alternatively, for local files, the user can specify the absolute path.
If remotely, the source can be retrieved via ``http``, ``https`` or ``ftp``.
Examples:
- ``salt://my_template.jinja``
- ``/absolute/path/to/my_template.jinja``
- ``http://example.com/template.cheetah``
- ``https:/example.com/template.mako``
- ``ftp://example.com/template.py``
.. versionchanged:: 2019.2.0
This argument can now support a list of templates to be rendered.
The resulting configuration text is loaded at once, as a single
configuration chunk.
template_source: None
Inline config template to be rendered and loaded on the device.
template_hash: None
Hash of the template file. Format: ``{hash_type: 'md5', 'hsum': <md5sum>}``
.. versionadded:: 2016.11.2
context: None
Overrides default context variables passed to the template.
.. versionadded:: 2019.2.0
template_hash_name: None
When ``template_hash`` refers to a remote file,
this specifies the filename to look for in that file.
.. versionadded:: 2016.11.2
saltenv: ``base``
Specifies the template environment.
This will influence the relative imports inside the templates.
.. versionadded:: 2016.11.2
template_engine: jinja
The following templates engines are supported:
- :mod:`cheetah<salt.renderers.cheetah>`
- :mod:`genshi<salt.renderers.genshi>`
- :mod:`jinja<salt.renderers.jinja>`
- :mod:`mako<salt.renderers.mako>`
- :mod:`py<salt.renderers.py>`
- :mod:`wempy<salt.renderers.wempy>`
.. versionadded:: 2016.11.2
skip_verify: True
If ``True``, hash verification of remote file sources
(``http://``, ``https://``, ``ftp://``) will be skipped,
and the ``source_hash`` argument will be ignored.
.. versionadded:: 2016.11.2
test: False
Dry run? If set to ``True``, will apply the config,
discard and return the changes.
Default: ``False`` and will commit the changes on the device.
commit: True
Commit? (default: ``True``)
debug: False
Debug mode. Will insert a new key under the output dictionary,
as ``loaded_config`` containing the raw result after the template was rendered.
.. versionadded:: 2016.11.2
replace: False
Load and replace the configuration.
.. versionadded:: 2016.11.2
commit_in: ``None``
Commit the changes in a specific number of minutes / hours. Example of
accepted formats: ``5`` (commit in 5 minutes), ``2m`` (commit in 2
minutes), ``1h`` (commit the changes in 1 hour)`, ``5h30m`` (commit
the changes in 5 hours and 30 minutes).
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
commit_at: ``None``
Commit the changes at a specific time. Example of accepted formats:
``1am`` (will commit the changes at the next 1AM), ``13:20`` (will
commit at 13:20), ``1:20am``, etc.
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
revert_in: ``None``
Commit and revert the changes in a specific number of minutes / hours.
Example of accepted formats: ``5`` (revert in 5 minutes), ``2m`` (revert
in 2 minutes), ``1h`` (revert the changes in 1 hour)`, ``5h30m`` (revert
the changes in 5 hours and 30 minutes).
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
revert_at: ``None``
Commit and revert the changes at a specific time. Example of accepted
formats: ``1am`` (will commit and revert the changes at the next 1AM),
``13:20`` (will commit and revert at 13:20), ``1:20am``, etc.
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
defaults: None
Default variables/context passed to the template.
.. versionadded:: 2016.11.2
template_vars
Dictionary with the arguments/context to be used when the template is rendered.
.. note::
Do not explicitly specify this argument. This represents any other
variable that will be sent to the template rendering system.
Please see the examples below!
.. note::
It is more recommended to use the ``context`` argument to avoid
conflicts between CLI arguments and template variables.
:return: a dictionary having the following keys:
- result (bool): if the config was applied successfully. It is ``False``
only in case of failure. In case there are no changes to be applied and
successfully performs all operations it is still ``True`` and so will be
the ``already_configured`` flag (example below)
- comment (str): a message for the user
- already_configured (bool): flag to check if there were no changes applied
- loaded_config (str): the configuration loaded on the device, after
rendering the template. Requires ``debug`` to be set as ``True``
- diff (str): returns the config changes applied
The template can use variables from the ``grains``, ``pillar`` or ``opts``, for example:
.. code-block:: jinja
{% set router_model = grains.get('model') -%}
{% set router_vendor = grains.get('vendor') -%}
{% set os_version = grains.get('version') -%}
{% set hostname = pillar.get('proxy', {}).get('host') -%}
{% if router_vendor|lower == 'juniper' %}
system {
host-name {{hostname}};
}
{% elif router_vendor|lower == 'cisco' %}
hostname {{hostname}}
{% endif %}
CLI Examples:
.. code-block:: bash
salt '*' net.load_template set_ntp_peers peers=[192.168.0.1] # uses NAPALM default templates
# inline template:
salt -G 'os:junos' net.load_template template_source='system { host-name {{host_name}}; }' \
host_name='MX480.lab'
# inline template using grains info:
salt -G 'os:junos' net.load_template \
template_source='system { host-name {{grains.model}}.lab; }'
# if the device is a MX480, the command above will set the hostname as: MX480.lab
# inline template using pillar data:
salt -G 'os:junos' net.load_template template_source='system { host-name {{pillar.proxy.host}}; }'
salt '*' net.load_template https://bit.ly/2OhSgqP hostname=example # will commit
salt '*' net.load_template https://bit.ly/2OhSgqP hostname=example test=True # dry run
salt '*' net.load_template salt://templates/example.jinja debug=True # Using the salt:// URI
# render a mako template:
salt '*' net.load_template salt://templates/example.mako template_engine=mako debug=True
# render remote template
salt -G 'os:junos' net.load_template http://bit.ly/2fReJg7 test=True debug=True peers=['192.168.0.1']
salt -G 'os:ios' net.load_template http://bit.ly/2gKOj20 test=True debug=True peers=['192.168.0.1']
# render multiple templates at once
salt '*' net.load_template "['https://bit.ly/2OhSgqP', 'salt://templates/example.jinja']" context="{'hostname': 'example'}"
Example output:
.. code-block:: python
{
'comment': '',
'already_configured': False,
'result': True,
'diff': '[edit system]+ host-name edge01.bjm01',
'loaded_config': 'system { host-name edge01.bjm01; }''
}
'''
_rendered = ''
_loaded = {
'result': True,
'comment': '',
'out': None
}
loaded_config = None
# prechecks
deprecated_args = ('template_user', 'template_attrs', 'template_group', 'template_mode')
for deprecated_arg in deprecated_args:
if template_vars.get(deprecated_arg):
del template_vars[deprecated_arg]
salt.utils.versions.warn_until(
'Sodium',
('The \'{arg}\' argument to \'net.load_template\' is deprecated '
'and has been ignored').format(arg=deprecated_arg)
)
if template_engine not in salt.utils.templates.TEMPLATE_REGISTRY:
_loaded.update({
'result': False,
'comment': 'Invalid templating engine! Choose between: {tpl_eng_opts}'.format(
tpl_eng_opts=', '.join(list(salt.utils.templates.TEMPLATE_REGISTRY.keys()))
)
})
return _loaded # exit
# to check if will be rendered by salt or NAPALM
salt_render_prefixes = ('salt://', 'http://', 'https://', 'ftp://')
salt_render = False
file_exists = False
if not isinstance(template_name, (tuple, list)):
for salt_render_prefix in salt_render_prefixes:
if not salt_render:
salt_render = salt_render or template_name.startswith(salt_render_prefix)
file_exists = __salt__['file.file_exists'](template_name)
if template_source or file_exists or salt_render or isinstance(template_name, (tuple, list)):
# either inline template
# either template in a custom path
# either abs path send
# either starts with salt:// and
# then use Salt render system
if context is None:
context = {}
context.update(template_vars)
# if needed to render the template send as inline arg
if template_source:
# render the content
_rendered = __salt__['file.apply_template_on_contents'](
contents=template_source,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv
)
if not isinstance(_rendered, six.string_types):
if 'result' in _rendered:
_loaded['result'] = _rendered['result']
else:
_loaded['result'] = False
if 'comment' in _rendered:
_loaded['comment'] = _rendered['comment']
else:
_loaded['comment'] = 'Error while rendering the template.'
return _loaded
else:
# render the file - either local, either remote
if not isinstance(template_name, (list, tuple)):
template_name = [template_name]
if template_hash_name and not isinstance(template_hash_name, (list, tuple)):
template_hash_name = [template_hash_name]
elif not template_hash_name:
template_hash_name = [None] * len(template_name)
if template_hash and isinstance(template_hash, six.string_types) and not\
(template_hash.startswith('salt://') or template_hash.startswith('file://')):
# If the template hash is passed as string, and it's not a file
# (starts with the salt:// or file:// URI), then make it a list
# of 1 element (for the iteration below)
template_hash = [template_hash]
elif template_hash and isinstance(template_hash, six.string_types) and\
(template_hash.startswith('salt://') or template_hash.startswith('file://')):
# If the template hash is a file URI, then provide the same value
# for each of the templates in the list, as probably they all
# share the same hash file, otherwise the user should provide
# this as a list
template_hash = [template_hash] * len(template_name)
elif not template_hash:
template_hash = [None] * len(template_name)
for tpl_index, tpl_name in enumerate(template_name):
tpl_hash = template_hash[tpl_index]
tpl_hash_name = template_hash_name[tpl_index]
_rand_filename = __salt__['random.hash'](tpl_name, 'md5')
_temp_file = __salt__['file.join']('/tmp', _rand_filename)
_managed = __salt__['file.get_managed'](name=_temp_file,
source=tpl_name,
source_hash=tpl_hash,
source_hash_name=tpl_hash_name,
user=None,
group=None,
mode=None,
attrs=None,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv,
skip_verify=skip_verify)
if not isinstance(_managed, (list, tuple)) and isinstance(_managed, six.string_types):
_loaded['comment'] += _managed
_loaded['result'] = False
elif isinstance(_managed, (list, tuple)) and not _managed:
_loaded['result'] = False
_loaded['comment'] += 'Error while rendering the template.'
elif isinstance(_managed, (list, tuple)) and not _managed[0]:
_loaded['result'] = False
_loaded['comment'] += _managed[-1] # contains the error message
if _loaded['result']: # all good
_temp_tpl_file = _managed[0]
_temp_tpl_file_exists = __salt__['file.file_exists'](_temp_tpl_file)
if not _temp_tpl_file_exists:
_loaded['result'] = False
_loaded['comment'] += 'Error while rendering the template.'
return _loaded
_rendered += __salt__['file.read'](_temp_tpl_file)
__salt__['file.remove'](_temp_tpl_file)
else:
return _loaded # exit
loaded_config = _rendered
if _loaded['result']: # all good
fun = 'load_merge_candidate'
if replace: # replace requested
fun = 'load_replace_candidate'
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
fun,
**{
'config': _rendered
}
)
else:
salt.utils.versions.warn_until(
'Sodium',
'Native NAPALM templates support will be removed in the Sodium '
'release. Please consider using the Salt rendering pipeline instead.'
'If you are using the \'netntp\', \'netsnmp\', or \'netusers\' Salt '
'State modules, you can ignore this message'
)
# otherwise, use NAPALM render system, injecting pillar/grains/opts vars
load_templates_params = defaults if defaults else {}
load_templates_params.update(template_vars)
load_templates_params.update(
{
'template_name': template_name,
'template_source': template_source, # inline template
'pillar': __pillar__, # inject pillar content
'grains': __grains__, # inject grains content
'opts': __opts__ # inject opts content
}
)
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
# so we'll set the CLOSE global explicitly as False
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'load_template',
**load_templates_params
)
return _config_logic(napalm_device, # pylint: disable=undefined-variable
_loaded,
test=test,
debug=debug,
replace=replace,
commit_config=commit,
loaded_config=loaded_config,
commit_at=commit_at,
commit_in=commit_in,
revert_in=revert_in,
revert_at=revert_at,
**template_vars)
@salt.utils.napalm.proxy_napalm_wrap
def commit(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Commits the configuration changes made on the network device.
CLI Example:
.. code-block:: bash
salt '*' net.commit
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'commit_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def discard_config(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
"""
Discards the changes applied.
CLI Example:
.. code-block:: bash
salt '*' net.discard_config
"""
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'discard_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def compare_config(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Returns the difference between the running config and the candidate config.
CLI Example:
.. code-block:: bash
salt '*' net.compare_config
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'compare_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def rollback(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Rollbacks the configuration.
CLI Example:
.. code-block:: bash
salt '*' net.rollback
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'rollback',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def config_changed(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Will prompt if the configuration has been changed.
:return: A tuple with a boolean that specifies if the config was changed on the device.\
And a string that provides more details of the reason why the configuration was not changed.
CLI Example:
.. code-block:: bash
salt '*' net.config_changed
'''
is_config_changed = False
reason = ''
try_compare = compare_config(inherit_napalm_device=napalm_device) # pylint: disable=undefined-variable
if try_compare.get('result'):
if try_compare.get('out'):
is_config_changed = True
else:
reason = 'Configuration was not changed on the device.'
else:
reason = try_compare.get('comment')
return is_config_changed, reason
@salt.utils.napalm.proxy_napalm_wrap
def config_control(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Will check if the configuration was changed.
If differences found, will try to commit.
In case commit unsuccessful, will try to rollback.
:return: A tuple with a boolean that specifies if the config was changed/committed/rollbacked on the device.\
And a string that provides more details of the reason why the configuration was not committed properly.
CLI Example:
.. code-block:: bash
salt '*' net.config_control
'''
result = True
comment = ''
changed, not_changed_rsn = config_changed(inherit_napalm_device=napalm_device) # pylint: disable=undefined-variable
if not changed:
return (changed, not_changed_rsn)
# config changed, thus let's try to commit
try_commit = commit()
if not try_commit.get('result'):
result = False
comment = 'Unable to commit the changes: {reason}.\n\
Will try to rollback now!'.format(
reason=try_commit.get('comment')
)
try_rollback = rollback()
if not try_rollback.get('result'):
comment += '\nCannot rollback! {reason}'.format(
reason=try_rollback.get('comment')
)
return result, comment
def cancel_commit(jid):
'''
.. versionadded:: 2019.2.0
Cancel a commit scheduled to be executed via the ``commit_in`` and
``commit_at`` arguments from the
:py:func:`net.load_template <salt.modules.napalm_network.load_template>` or
:py:func:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit ID is displayed when the commit is scheduled
via the functions named above.
CLI Example:
.. code-block:: bash
salt '*' net.cancel_commit 20180726083540640360
'''
job_name = '__napalm_commit_{}'.format(jid)
removed = __salt__['schedule.delete'](job_name)
if removed['result']:
saved = __salt__['schedule.save']()
removed['comment'] = 'Commit #{jid} cancelled.'.format(jid=jid)
else:
removed['comment'] = 'Unable to find commit #{jid}.'.format(jid=jid)
return removed
def confirm_commit(jid):
'''
.. versionadded:: 2019.2.0
Confirm a commit scheduled to be reverted via the ``revert_in`` and
``revert_at`` arguments from the
:mod:`net.load_template <salt.modules.napalm_network.load_template>` or
:mod:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit ID is displayed when the commit confirmed
is scheduled via the functions named above.
CLI Example:
.. code-block:: bash
salt '*' net.confirm_commit 20180726083540640360
'''
if __grains__['os'] == 'junos':
# Confirm the commit, by committing (i.e., invoking the RPC call)
confirmed = __salt__['napalm.junos_commit']()
confirmed['result'] = confirmed.pop('out')
confirmed['comment'] = confirmed.pop('message')
else:
confirmed = cancel_commit(jid)
if confirmed['result']:
confirmed['comment'] = 'Commit #{jid} confirmed.'.format(jid=jid)
return confirmed
def save_config(source=None,
path=None):
'''
.. versionadded:: 2019.2.0
Save the configuration to a file on the local file system.
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``,
``startup``. Default: ``running``.
path
Absolute path to file where to save the configuration.
To push the files to the Master, use
:mod:`cp.push <salt.modules.cp.push>` Execution function.
CLI Example:
.. code-block:: bash
salt '*' net.save_config source=running
'''
if not source:
source = 'running'
if not path:
path = salt.utils.files.mkstemp()
running_config = __salt__['net.config'](source=source)
if not running_config or not running_config['result']:
log.error('Unable to retrieve the config')
return running_config
with salt.utils.files.fopen(path, 'w') as fh_:
fh_.write(running_config['out'][source])
return {
'result': True,
'out': path,
'comment': '{source} config saved to {path}'.format(source=source, path=path)
}
def replace_pattern(pattern,
repl,
count=0,
flags=8,
bufsize=1,
append_if_not_found=False,
prepend_if_not_found=False,
not_found_content=None,
search_only=False,
show_changes=True,
backslash_literal=False,
source=None,
path=None,
test=False,
replace=True,
debug=False,
commit=True):
'''
.. versionadded:: 2019.2.0
Replace occurrences of a pattern in the configuration source. If
``show_changes`` is ``True``, then a diff of what changed will be returned,
otherwise a ``True`` will be returned when changes are made, and ``False``
when no changes are made.
This is a pure Python implementation that wraps Python's :py:func:`~re.sub`.
pattern
A regular expression, to be matched using Python's
:py:func:`~re.search`.
repl
The replacement text.
count: ``0``
Maximum number of pattern occurrences to be replaced. If count is a
positive integer ``n``, only ``n`` occurrences will be replaced,
otherwise all occurrences will be replaced.
flags (list or int): ``8``
A list of flags defined in the ``re`` module documentation from the
Python standard library. Each list item should be a string that will
correlate to the human-friendly flag name. E.g., ``['IGNORECASE',
'MULTILINE']``. Optionally, ``flags`` may be an int, with a value
corresponding to the XOR (``|``) of all the desired flags. Defaults to
8 (which supports 'MULTILINE').
bufsize (int or str): ``1``
How much of the configuration to buffer into memory at once. The
default value ``1`` processes one line at a time. The special value
``file`` may be specified which will read the entire file into memory
before processing.
append_if_not_found: ``False``
If set to ``True``, and pattern is not found, then the content will be
appended to the file.
prepend_if_not_found: ``False``
If set to ``True`` and pattern is not found, then the content will be
prepended to the file.
not_found_content
Content to use for append/prepend if not found. If None (default), uses
``repl``. Useful when ``repl`` uses references to group in pattern.
search_only: ``False``
If set to true, this no changes will be performed on the file, and this
function will simply return ``True`` if the pattern was matched, and
``False`` if not.
show_changes: ``True``
If ``True``, return a diff of changes made. Otherwise, return ``True``
if changes were made, and ``False`` if not.
backslash_literal: ``False``
Interpret backslashes as literal backslashes for the repl and not
escape characters. This will help when using append/prepend so that
the backslashes are not interpreted for the repl on the second run of
the state.
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path
Save the temporary configuration to a specific path, then read from
there.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' net.replace_pattern "bind-address\\s*=" "bind-address:"
CLI Example:
.. code-block:: bash
salt '*' net.replace_pattern PREFIX-LIST_NAME new-prefix-list-name
salt '*' net.replace_pattern bgp-group-name new-bgp-group-name count=1
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
replace_pattern = __salt__['file.replace'](path,
pattern,
repl,
count=count,
flags=flags,
bufsize=bufsize,
append_if_not_found=append_if_not_found,
prepend_if_not_found=prepend_if_not_found,
not_found_content=not_found_content,
search_only=search_only,
show_changes=show_changes,
backslash_literal=backslash_literal)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
def blockreplace(marker_start,
marker_end,
content='',
append_if_not_found=False,
prepend_if_not_found=False,
show_changes=True,
append_newline=False,
source='running',
path=None,
test=False,
commit=True,
debug=False,
replace=True):
'''
.. versionadded:: 2019.2.0
Replace content of the configuration source, delimited by the line markers.
A block of content delimited by comments can help you manage several lines
without worrying about old entries removal.
marker_start
The line content identifying a line as the start of the content block.
Note that the whole line containing this marker will be considered,
so whitespace or extra content before or after the marker is included
in final output.
marker_end
The line content identifying a line as the end of the content block.
Note that the whole line containing this marker will be considered,
so whitespace or extra content before or after the marker is included
in final output.
content
The content to be used between the two lines identified by
``marker_start`` and ``marker_stop``.
append_if_not_found: ``False``
If markers are not found and set to True then, the markers and content
will be appended to the file.
prepend_if_not_found: ``False``
If markers are not found and set to True then, the markers and content
will be prepended to the file.
append_newline: ``False``
Controls whether or not a newline is appended to the content block.
If the value of this argument is ``True`` then a newline will be added
to the content block. If it is ``False``, then a newline will not be
added to the content block. If it is ``None`` then a newline will only
be added to the content block if it does not already end in a newline.
show_changes: ``True``
Controls how changes are presented. If ``True``, this function will
return the of the changes made.
If ``False``, then it will return a boolean (``True`` if any changes
were made, otherwise False).
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path: ``None``
Save the temporary configuration to a specific path, then read from
there. This argument is optional, can be used when you prefers a
particular location of the temporary file.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
CLI Example:
.. code-block:: bash
salt '*' net.blockreplace 'ntp' 'interface' ''
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
replace_pattern = __salt__['file.blockreplace'](path,
marker_start=marker_start,
marker_end=marker_end,
content=content,
append_if_not_found=append_if_not_found,
prepend_if_not_found=prepend_if_not_found,
show_changes=show_changes,
append_newline=append_newline)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
def patch(patchfile,
options='',
saltenv='base',
source_hash=None,
show_changes=True,
source='running',
path=None,
test=False,
commit=True,
debug=False,
replace=True):
'''
.. versionadded:: 2019.2.0
Apply a patch to the configuration source, and load the result into the
running config of the device.
patchfile
A patch file to apply to the configuration source.
options
Options to pass to patch.
source_hash
If the patch file (specified via the ``patchfile`` argument) is an
HTTP(S) or FTP URL and the file exists in the minion's file cache, this
option can be passed to keep the minion from re-downloading the file if
the cached copy matches the specified hash.
show_changes: ``True``
Controls how changes are presented. If ``True``, this function will
return the of the changes made.
If ``False``, then it will return a boolean (``True`` if any changes
were made, otherwise False).
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path: ``None``
Save the temporary configuration to a specific path, then read from
there. This argument is optional, can the user prefers a particular
location of the temporary file.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
CLI Example:
.. code-block:: bash
salt '*' net.patch https://example.com/running_config.patch
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
patchfile_cache = __salt__['cp.cache_file'](patchfile)
if patchfile_cache is False:
return {
'out': None,
'result': False,
'comment': 'The file "{}" does not exist.'.format(patchfile)
}
replace_pattern = __salt__['file.patch'](path,
patchfile_cache,
options=options)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
# <---- Configuration specific functions -------------------------------------------------------------------------------
|
saltstack/salt
|
salt/modules/napalm_network.py
|
_explicit_close
|
python
|
def _explicit_close(napalm_device):
'''
Will explicily close the config session with the network device,
when running in a now-always-alive proxy minion or regular minion.
This helper must be used in configuration-related functions,
as the session is preserved and not closed before making any changes.
'''
if salt.utils.napalm.not_always_alive(__opts__):
# force closing the configuration session
# when running in a non-always-alive proxy
# or regular minion
try:
napalm_device['DRIVER'].close()
except Exception as err:
log.error('Unable to close the temp connection with the device:')
log.error(err)
log.error('Please report.')
|
Will explicily close the config session with the network device,
when running in a now-always-alive proxy minion or regular minion.
This helper must be used in configuration-related functions,
as the session is preserved and not closed before making any changes.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_network.py#L142-L158
| null |
# -*- coding: utf-8 -*-
'''
NAPALM Network
==============
Basic methods for interaction with the network device through the virtual proxy 'napalm'.
:codeauthor: Mircea Ulinic <mircea@cloudflare.com> & Jerome Fleury <jf@cloudflare.com>
:maturity: new
:depends: napalm
:platform: unix
Dependencies
------------
- :mod:`napalm proxy minion <salt.proxy.napalm>`
.. versionadded:: 2016.11.0
.. versionchanged:: 2017.7.0
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import time
import logging
import datetime
log = logging.getLogger(__name__)
# Import Salt libs
from salt.ext import six
import salt.utils.files
import salt.utils.napalm
import salt.utils.versions
import salt.utils.templates
# Import 3rd-party libs
try:
import jxmlease # pylint: disable=unused-import
HAS_JXMLEASE = True
except ImportError:
HAS_JXMLEASE = False
# ----------------------------------------------------------------------------------------------------------------------
# module properties
# ----------------------------------------------------------------------------------------------------------------------
__virtualname__ = 'net'
__proxyenabled__ = ['*']
__virtual_aliases__ = ('napalm_net',)
# uses NAPALM-based proxy to interact with network devices
# ----------------------------------------------------------------------------------------------------------------------
# property functions
# ----------------------------------------------------------------------------------------------------------------------
def __virtual__():
'''
NAPALM library must be installed for this module to work and run in a (proxy) minion.
'''
return salt.utils.napalm.virtual(__opts__, __virtualname__, __file__)
# ----------------------------------------------------------------------------------------------------------------------
# helper functions -- will not be exported
# ----------------------------------------------------------------------------------------------------------------------
def _filter_list(input_list, search_key, search_value):
'''
Filters a list of dictionary by a set of key-value pair.
:param input_list: is a list of dictionaries
:param search_key: is the key we are looking for
:param search_value: is the value we are looking for the key specified in search_key
:return: filered list of dictionaries
'''
output_list = list()
for dictionary in input_list:
if dictionary.get(search_key) == search_value:
output_list.append(dictionary)
return output_list
def _filter_dict(input_dict, search_key, search_value):
'''
Filters a dictionary of dictionaries by a key-value pair.
:param input_dict: is a dictionary whose values are lists of dictionaries
:param search_key: is the key in the leaf dictionaries
:param search_values: is the value in the leaf dictionaries
:return: filtered dictionary
'''
output_dict = dict()
for key, key_list in six.iteritems(input_dict):
key_list_filtered = _filter_list(key_list, search_key, search_value)
if key_list_filtered:
output_dict[key] = key_list_filtered
return output_dict
def _safe_commit_config(loaded_result, napalm_device):
_commit = commit(inherit_napalm_device=napalm_device) # calls the function commit, defined below
if not _commit.get('result', False):
# if unable to commit
loaded_result['comment'] += _commit['comment'] if _commit.get('comment') else 'Unable to commit.'
loaded_result['result'] = False
# unable to commit, something went wrong
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
return _commit
def _safe_dicard_config(loaded_result, napalm_device):
'''
'''
log.debug('Discarding the config')
log.debug(loaded_result)
_discarded = discard_config(inherit_napalm_device=napalm_device)
if not _discarded.get('result', False):
loaded_result['comment'] += _discarded['comment'] if _discarded.get('comment') \
else 'Unable to discard config.'
loaded_result['result'] = False
# make sure it notifies
# that something went wrong
_explicit_close(napalm_device)
__context__['retcode'] = 1
return loaded_result
return _discarded
def _config_logic(napalm_device,
loaded_result,
test=False,
debug=False,
replace=False,
commit_config=True,
loaded_config=None,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
commit_jid=None,
**kwargs):
'''
Builds the config logic for `load_config` and `load_template` functions.
'''
# As the Salt logic is built around independent events
# when it comes to configuration changes in the
# candidate DB on the network devices, we need to
# make sure we're using the same session.
# Hence, we need to pass the same object around.
# the napalm_device object is inherited from
# the load_config or load_template functions
# and forwarded to compare, discard, commit etc.
# then the decorator will make sure that
# if not proxy (when the connection is always alive)
# and the `inherit_napalm_device` is set,
# `napalm_device` will be overridden.
# See `salt.utils.napalm.proxy_napalm_wrap` decorator.
current_jid = kwargs.get('__pub_jid')
if not current_jid:
current_jid = '{0:%Y%m%d%H%M%S%f}'.format(datetime.datetime.now())
loaded_result['already_configured'] = False
loaded_result['loaded_config'] = ''
if debug:
loaded_result['loaded_config'] = loaded_config
_compare = compare_config(inherit_napalm_device=napalm_device)
if _compare.get('result', False):
loaded_result['diff'] = _compare.get('out')
loaded_result.pop('out', '') # not needed
else:
loaded_result['diff'] = None
loaded_result['result'] = False
loaded_result['comment'] = _compare.get('comment')
__context__['retcode'] = 1
return loaded_result
_loaded_res = loaded_result.get('result', False)
if not _loaded_res or test:
# if unable to load the config (errors / warnings)
# or in testing mode,
# will discard the config
if loaded_result['comment']:
loaded_result['comment'] += '\n'
if not loaded_result.get('diff', ''):
loaded_result['already_configured'] = True
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
loaded_result['comment'] += 'Configuration discarded.'
# loaded_result['result'] = False not necessary
# as the result can be true when test=True
_explicit_close(napalm_device)
if not loaded_result['result']:
__context__['retcode'] = 1
return loaded_result
if not test and commit_config:
# if not in testing mode and trying to commit
if commit_jid:
log.info('Committing the JID: %s', str(commit_jid))
removed = cancel_commit(commit_jid)
log.debug('Cleaned up the commit from the schedule')
log.debug(removed['comment'])
if loaded_result.get('diff', ''):
# if not testing mode
# and also the user wants to commit (default)
# and there are changes to commit
if commit_in or commit_at:
commit_time = __utils__['timeutil.get_time_at'](time_in=commit_in,
time_at=commit_in)
# schedule job
scheduled_job_name = '__napalm_commit_{}'.format(current_jid)
temp_file = salt.utils.files.mkstemp()
with salt.utils.files.fopen(temp_file, 'w') as fp_:
fp_.write(loaded_config)
scheduled = __salt__['schedule.add'](scheduled_job_name,
function='net.load_config',
job_kwargs={
'filename': temp_file,
'commit_jid': current_jid,
'replace': replace
},
once=commit_time)
log.debug('Scheduling job')
log.debug(scheduled)
saved = __salt__['schedule.save']() # ensure the schedule is
# persistent cross Minion restart
discarded = _safe_dicard_config(loaded_result, napalm_device)
# discard the changes
if not discarded['result']:
discarded['comment'] += ('Scheduled the job to be executed at {schedule_ts}, '
'but was unable to discard the config: \n').format(schedule_ts=commit_time)
return discarded
loaded_result['comment'] = ('Changes discarded for now, and scheduled commit at: {schedule_ts}.\n'
'The commit ID is: {current_jid}.\n'
'To discard this commit, you can execute: \n\n'
'salt {min_id} net.cancel_commit {current_jid}').format(schedule_ts=commit_time,
min_id=__opts__['id'],
current_jid=current_jid)
loaded_result['commit_id'] = current_jid
return loaded_result
log.debug('About to commit:')
log.debug(loaded_result['diff'])
if revert_in or revert_at:
revert_time = __utils__['timeutil.get_time_at'](time_in=revert_in,
time_at=revert_at)
if __grains__['os'] == 'junos':
if not HAS_JXMLEASE:
loaded_result['comment'] = ('This feature requires the library jxmlease to be installed.\n'
'To install, please execute: ``pip install jxmlease``.')
loaded_result['result'] = False
return loaded_result
timestamp_at = __utils__['timeutil.get_timestamp_at'](time_in=revert_in,
time_at=revert_at)
minutes = int((timestamp_at - time.time())/60)
_comm = __salt__['napalm.junos_commit'](confirm=minutes)
if not _comm['out']:
# If unable to commit confirm, should try to bail out
loaded_result['comment'] = 'Unable to commit confirm: {}'.format(_comm['message'])
loaded_result['result'] = False
# But before exiting, we must gracefully discard the config
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
else:
temp_file = salt.utils.files.mkstemp()
running_config = __salt__['net.config'](source='running')['out']['running']
with salt.utils.files.fopen(temp_file, 'w') as fp_:
fp_.write(running_config)
committed = _safe_commit_config(loaded_result, napalm_device)
if not committed['result']:
# If unable to commit, dicard the config (which is
# already done by the _safe_commit_config function), and
# return with the command and other details.
return loaded_result
scheduled_job_name = '__napalm_commit_{}'.format(current_jid)
scheduled = __salt__['schedule.add'](scheduled_job_name,
function='net.load_config',
job_kwargs={
'filename': temp_file,
'commit_jid': current_jid,
'replace': True
},
once=revert_time)
log.debug('Scheduling commit confirmed')
log.debug(scheduled)
saved = __salt__['schedule.save']()
loaded_result['comment'] = ('The commit ID is: {current_jid}.\n'
'This commit will be reverted at: {schedule_ts}, unless confirmed.\n'
'To confirm the commit and avoid reverting, you can execute:\n\n'
'salt {min_id} net.confirm_commit {current_jid}').format(schedule_ts=revert_time,
min_id=__opts__['id'],
current_jid=current_jid)
loaded_result['commit_id'] = current_jid
return loaded_result
committed = _safe_commit_config(loaded_result, napalm_device)
if not committed['result']:
return loaded_result
else:
# would like to commit, but there's no change
# need to call discard_config() to release the config DB
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
loaded_result['already_configured'] = True
loaded_result['comment'] = 'Already configured.'
_explicit_close(napalm_device)
if not loaded_result['result']:
__context__['retcode'] = 1
return loaded_result
# ----------------------------------------------------------------------------------------------------------------------
# callable functions
# ----------------------------------------------------------------------------------------------------------------------
@salt.utils.napalm.proxy_napalm_wrap
def connected(**kwargs): # pylint: disable=unused-argument
'''
Specifies if the connection to the device succeeded.
CLI Example:
.. code-block:: bash
salt '*' net.connected
'''
return {
'out': napalm_device.get('UP', False) # pylint: disable=undefined-variable
}
@salt.utils.napalm.proxy_napalm_wrap
def facts(**kwargs): # pylint: disable=unused-argument
'''
Returns characteristics of the network device.
:return: a dictionary with the following keys:
* uptime - Uptime of the device in seconds.
* vendor - Manufacturer of the device.
* model - Device model.
* hostname - Hostname of the device
* fqdn - Fqdn of the device
* os_version - String with the OS version running on the device.
* serial_number - Serial number of the device
* interface_list - List of the interfaces of the device
CLI Example:
.. code-block:: bash
salt '*' net.facts
Example output:
.. code-block:: python
{
'os_version': '13.3R6.5',
'uptime': 10117140,
'interface_list': [
'lc-0/0/0',
'pfe-0/0/0',
'pfh-0/0/0',
'xe-0/0/0',
'xe-0/0/1',
'xe-0/0/2',
'xe-0/0/3',
'gr-0/0/10',
'ip-0/0/10'
],
'vendor': 'Juniper',
'serial_number': 'JN131356FBFA',
'model': 'MX480',
'hostname': 're0.edge05.syd01',
'fqdn': 're0.edge05.syd01'
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_facts',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def environment(**kwargs): # pylint: disable=unused-argument
'''
Returns the environment of the device.
CLI Example:
.. code-block:: bash
salt '*' net.environment
Example output:
.. code-block:: python
{
'fans': {
'Bottom Rear Fan': {
'status': True
},
'Bottom Middle Fan': {
'status': True
},
'Top Middle Fan': {
'status': True
},
'Bottom Front Fan': {
'status': True
},
'Top Front Fan': {
'status': True
},
'Top Rear Fan': {
'status': True
}
},
'memory': {
'available_ram': 16349,
'used_ram': 4934
},
'temperature': {
'FPC 0 Exhaust A': {
'is_alert': False,
'temperature': 35.0,
'is_critical': False
}
},
'cpu': {
'1': {
'%usage': 19.0
},
'0': {
'%usage': 35.0
}
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_environment',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def cli(*commands, **kwargs): # pylint: disable=unused-argument
'''
Returns a dictionary with the raw output of all commands passed as arguments.
commands
List of commands to be executed on the device.
textfsm_parse: ``False``
Try parsing the outputs using the TextFSM templates.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``napalm_cli_textfsm_parse``.
textfsm_path
The path where the TextFSM templates can be found. This option implies
the usage of the TextFSM index file.
``textfsm_path`` can be either absolute path on the server,
either specified using the following URL mschemes: ``file://``,
``salt://``, ``http://``, ``https://``, ``ftp://``,
``s3://``, ``swift://``.
.. versionadded:: 2018.3.0
.. note::
This needs to be a directory with a flat structure, having an
index file (whose name can be specified using the ``index_file`` option)
and a number of TextFSM templates.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_path``.
textfsm_template
The path to a certain the TextFSM template.
This can be specified using the absolute path
to the file, or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
.. versionadded:: 2018.3.0
textfsm_template_dict
A dictionary with the mapping between a command
and the corresponding TextFSM path to use to extract the data.
The TextFSM paths can be specified as in ``textfsm_template``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``napalm_cli_textfsm_template_dict``.
platform_grain_name: ``os``
The name of the grain used to identify the platform name
in the TextFSM index file. Default: ``os``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_grain``.
platform_column_name: ``Platform``
The column name used to identify the platform,
exactly as specified in the TextFSM index file.
Default: ``Platform``.
.. versionadded:: 2018.3.0
.. note::
This is field is case sensitive, make sure
to assign the correct value to this option,
exactly as defined in the index file.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_column_name``.
index_file: ``index``
The name of the TextFSM index file, under the ``textfsm_path``. Default: ``index``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_index_file``.
saltenv: ``base``
Salt fileserver envrionment from which to retrieve the file.
Ignored if ``textfsm_path`` is not a ``salt://`` URL.
.. versionadded:: 2018.3.0
include_empty: ``False``
Include empty files under the ``textfsm_path``.
.. versionadded:: 2018.3.0
include_pat
Glob or regex to narrow down the files cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. versionadded:: 2018.3.0
exclude_pat
Glob or regex to exclude certain files from being cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. versionadded:: 2018.3.0
.. note::
If used with ``include_pat``, files matching this pattern will be
excluded from the subset of files defined by ``include_pat``.
CLI Example:
.. code-block:: bash
salt '*' net.cli "show version" "show chassis fan"
CLI Example with TextFSM template:
.. code-block:: bash
salt '*' net.cli textfsm_parse=True textfsm_path=salt://textfsm/
Example output:
.. code-block:: python
{
'show version and haiku': 'Hostname: re0.edge01.arn01
Model: mx480
Junos: 13.3R6.5
Help me, Obi-Wan
I just saw Episode Two
You're my only hope
',
'show chassis fan' : 'Item Status RPM Measurement
Top Rear Fan OK 3840 Spinning at intermediate-speed
Bottom Rear Fan OK 3840 Spinning at intermediate-speed
Top Middle Fan OK 3900 Spinning at intermediate-speed
Bottom Middle Fan OK 3840 Spinning at intermediate-speed
Top Front Fan OK 3810 Spinning at intermediate-speed
Bottom Front Fan OK 3840 Spinning at intermediate-speed
'
}
Example output with TextFSM parsing:
.. code-block:: json
{
"comment": "",
"result": true,
"out": {
"sh ver": [
{
"kernel": "9.1S3.5",
"documentation": "9.1S3.5",
"boot": "9.1S3.5",
"crypto": "9.1S3.5",
"chassis": "",
"routing": "9.1S3.5",
"base": "9.1S3.5",
"model": "mx960"
}
]
}
}
'''
raw_cli_outputs = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'cli',
**{
'commands': list(commands)
}
)
# thus we can display the output as is
# in case of errors, they'll be catched in the proxy
if not raw_cli_outputs['result']:
# Error -> dispaly the output as-is.
return raw_cli_outputs
textfsm_parse = kwargs.get('textfsm_parse') or __opts__.get('napalm_cli_textfsm_parse') or\
__pillar__.get('napalm_cli_textfsm_parse', False)
if not textfsm_parse:
# No TextFSM parsing required, return raw commands.
log.debug('No TextFSM parsing requested.')
return raw_cli_outputs
if 'textfsm.extract' not in __salt__ or 'textfsm.index' not in __salt__:
raw_cli_outputs['comment'] += 'Unable to process: is TextFSM installed?'
log.error(raw_cli_outputs['comment'])
return raw_cli_outputs
textfsm_template = kwargs.get('textfsm_template')
log.debug('textfsm_template: %s', textfsm_template)
textfsm_path = kwargs.get('textfsm_path') or __opts__.get('textfsm_path') or\
__pillar__.get('textfsm_path')
log.debug('textfsm_path: %s', textfsm_path)
textfsm_template_dict = kwargs.get('textfsm_template_dict') or __opts__.get('napalm_cli_textfsm_template_dict') or\
__pillar__.get('napalm_cli_textfsm_template_dict', {})
log.debug('TextFSM command-template mapping: %s', textfsm_template_dict)
index_file = kwargs.get('index_file') or __opts__.get('textfsm_index_file') or\
__pillar__.get('textfsm_index_file')
log.debug('index_file: %s', index_file)
platform_grain_name = kwargs.get('platform_grain_name') or __opts__.get('textfsm_platform_grain') or\
__pillar__.get('textfsm_platform_grain', 'os')
log.debug('platform_grain_name: %s', platform_grain_name)
platform_column_name = kwargs.get('platform_column_name') or __opts__.get('textfsm_platform_column_name') or\
__pillar__.get('textfsm_platform_column_name', 'Platform')
log.debug('platform_column_name: %s', platform_column_name)
saltenv = kwargs.get('saltenv', 'base')
include_empty = kwargs.get('include_empty', False)
include_pat = kwargs.get('include_pat')
exclude_pat = kwargs.get('exclude_pat')
processed_cli_outputs = {
'comment': raw_cli_outputs.get('comment', ''),
'result': raw_cli_outputs['result'],
'out': {}
}
log.debug('Starting to analyse the raw outputs')
for command in list(commands):
command_output = raw_cli_outputs['out'][command]
log.debug('Output from command: %s', command)
log.debug(command_output)
processed_command_output = None
if textfsm_path:
log.debug('Using the templates under %s', textfsm_path)
processed_cli_output = __salt__['textfsm.index'](command,
platform_grain_name=platform_grain_name,
platform_column_name=platform_column_name,
output=command_output.strip(),
textfsm_path=textfsm_path,
saltenv=saltenv,
include_empty=include_empty,
include_pat=include_pat,
exclude_pat=exclude_pat)
log.debug('Processed CLI output:')
log.debug(processed_cli_output)
if not processed_cli_output['result']:
log.debug('Apparently this didnt work, returnin the raw output')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {0}: {1}.'.format(command,
processed_cli_output['comment'])
log.error(processed_cli_outputs['comment'])
elif processed_cli_output['out']:
log.debug('All good, %s has a nice output!', command)
processed_command_output = processed_cli_output['out']
else:
comment = '''\nProcessing "{}" didn't fail, but didn't return anything either. Dumping raw.'''.format(
command)
processed_cli_outputs['comment'] += comment
log.error(comment)
processed_command_output = command_output
elif textfsm_template or command in textfsm_template_dict:
if command in textfsm_template_dict:
textfsm_template = textfsm_template_dict[command]
log.debug('Using %s to process the command: %s', textfsm_template, command)
processed_cli_output = __salt__['textfsm.extract'](textfsm_template,
raw_text=command_output,
saltenv=saltenv)
log.debug('Processed CLI output:')
log.debug(processed_cli_output)
if not processed_cli_output['result']:
log.debug('Apparently this didnt work, returning '
'the raw output')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {0}: {1}'.format(command,
processed_cli_output['comment'])
log.error(processed_cli_outputs['comment'])
elif processed_cli_output['out']:
log.debug('All good, %s has a nice output!', command)
processed_command_output = processed_cli_output['out']
else:
log.debug('Processing %s didnt fail, but didnt return'
' anything either. Dumping raw.', command)
processed_command_output = command_output
else:
log.error('No TextFSM template specified, or no TextFSM path defined')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {}.'.format(command)
processed_cli_outputs['out'][command] = processed_command_output
processed_cli_outputs['comment'] = processed_cli_outputs['comment'].strip()
return processed_cli_outputs
@salt.utils.napalm.proxy_napalm_wrap
def traceroute(destination, source=None, ttl=None, timeout=None, vrf=None, **kwargs): # pylint: disable=unused-argument
'''
Calls the method traceroute from the NAPALM driver object and returns a dictionary with the result of the traceroute
command executed on the device.
destination
Hostname or address of remote host
source
Source address to use in outgoing traceroute packets
ttl
IP maximum time-to-live value (or IPv6 maximum hop-limit value)
timeout
Number of seconds to wait for response (seconds)
vrf
VRF (routing instance) for traceroute attempt
.. versionadded:: 2016.11.4
CLI Example:
.. code-block:: bash
salt '*' net.traceroute 8.8.8.8
salt '*' net.traceroute 8.8.8.8 source=127.0.0.1 ttl=5 timeout=1
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'traceroute',
**{
'destination': destination,
'source': source,
'ttl': ttl,
'timeout': timeout,
'vrf': vrf
}
)
@salt.utils.napalm.proxy_napalm_wrap
def ping(destination, source=None, ttl=None, timeout=None, size=None, count=None, vrf=None, **kwargs): # pylint: disable=unused-argument
'''
Executes a ping on the network device and returns a dictionary as a result.
destination
Hostname or IP address of remote host
source
Source address of echo request
ttl
IP time-to-live value (IPv6 hop-limit value) (1..255 hops)
timeout
Maximum wait time after sending final packet (seconds)
size
Size of request packets (0..65468 bytes)
count
Number of ping requests to send (1..2000000000 packets)
vrf
VRF (routing instance) for ping attempt
.. versionadded:: 2016.11.4
CLI Example:
.. code-block:: bash
salt '*' net.ping 8.8.8.8
salt '*' net.ping 8.8.8.8 ttl=3 size=65468
salt '*' net.ping 8.8.8.8 source=127.0.0.1 timeout=1 count=100
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'ping',
**{
'destination': destination,
'source': source,
'ttl': ttl,
'timeout': timeout,
'size': size,
'count': count,
'vrf': vrf
}
)
@salt.utils.napalm.proxy_napalm_wrap
def arp(interface='', ipaddr='', macaddr='', **kwargs): # pylint: disable=unused-argument
'''
NAPALM returns a list of dictionaries with details of the ARP entries.
:param interface: interface name to filter on
:param ipaddr: IP address to filter on
:param macaddr: MAC address to filter on
:return: List of the entries in the ARP table
CLI Example:
.. code-block:: bash
salt '*' net.arp
salt '*' net.arp macaddr='5c:5e:ab:da:3c:f0'
Example output:
.. code-block:: python
[
{
'interface' : 'MgmtEth0/RSP0/CPU0/0',
'mac' : '5c:5e:ab:da:3c:f0',
'ip' : '172.17.17.1',
'age' : 1454496274.84
},
{
'interface': 'MgmtEth0/RSP0/CPU0/0',
'mac' : '66:0e:94:96:e0:ff',
'ip' : '172.17.17.2',
'age' : 1435641582.49
}
]
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_arp_table',
**{
}
)
if not proxy_output.get('result'):
return proxy_output
arp_table = proxy_output.get('out')
if interface:
arp_table = _filter_list(arp_table, 'interface', interface)
if ipaddr:
arp_table = _filter_list(arp_table, 'ip', ipaddr)
if macaddr:
arp_table = _filter_list(arp_table, 'mac', macaddr)
proxy_output.update({
'out': arp_table
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def ipaddrs(**kwargs): # pylint: disable=unused-argument
'''
Returns IP addresses configured on the device.
:return: A dictionary with the IPv4 and IPv6 addresses of the interfaces.
Returns all configured IP addresses on all interfaces as a dictionary
of dictionaries. Keys of the main dictionary represent the name of the
interface. Values of the main dictionary represent are dictionaries
that may consist of two keys 'ipv4' and 'ipv6' (one, both or none)
which are themselvs dictionaries with the IP addresses as keys.
CLI Example:
.. code-block:: bash
salt '*' net.ipaddrs
Example output:
.. code-block:: python
{
'FastEthernet8': {
'ipv4': {
'10.66.43.169': {
'prefix_length': 22
}
}
},
'Loopback555': {
'ipv4': {
'192.168.1.1': {
'prefix_length': 24
}
},
'ipv6': {
'1::1': {
'prefix_length': 64
},
'2001:DB8:1::1': {
'prefix_length': 64
},
'FE80::3': {
'prefix_length': 'N/A'
}
}
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_interfaces_ip',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def interfaces(**kwargs): # pylint: disable=unused-argument
'''
Returns details of the interfaces on the device.
:return: Returns a dictionary of dictionaries. The keys for the first
dictionary will be the interfaces in the devices.
CLI Example:
.. code-block:: bash
salt '*' net.interfaces
Example output:
.. code-block:: python
{
'Management1': {
'is_up': False,
'is_enabled': False,
'description': '',
'last_flapped': -1,
'speed': 1000,
'mac_address': 'dead:beef:dead',
},
'Ethernet1':{
'is_up': True,
'is_enabled': True,
'description': 'foo',
'last_flapped': 1429978575.1554043,
'speed': 1000,
'mac_address': 'beef:dead:beef',
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_interfaces',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def lldp(interface='', **kwargs): # pylint: disable=unused-argument
'''
Returns a detailed view of the LLDP neighbors.
:param interface: interface name to filter on
:return: A dictionary with the LLDL neighbors. The keys are the
interfaces with LLDP activated on.
CLI Example:
.. code-block:: bash
salt '*' net.lldp
salt '*' net.lldp interface='TenGigE0/0/0/8'
Example output:
.. code-block:: python
{
'TenGigE0/0/0/8': [
{
'parent_interface': 'Bundle-Ether8',
'interface_description': 'TenGigE0/0/0/8',
'remote_chassis_id': '8c60.4f69.e96c',
'remote_system_name': 'switch',
'remote_port': 'Eth2/2/1',
'remote_port_description': 'Ethernet2/2/1',
'remote_system_description': 'Cisco Nexus Operating System (NX-OS) Software 7.1(0)N1(1a)
TAC support: http://www.cisco.com/tac
Copyright (c) 2002-2015, Cisco Systems, Inc. All rights reserved.',
'remote_system_capab': 'B, R',
'remote_system_enable_capab': 'B'
}
]
}
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_lldp_neighbors_detail',
**{
}
)
if not proxy_output.get('result'):
return proxy_output
lldp_neighbors = proxy_output.get('out')
if interface:
lldp_neighbors = {interface: lldp_neighbors.get(interface)}
proxy_output.update({
'out': lldp_neighbors
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def mac(address='', interface='', vlan=0, **kwargs): # pylint: disable=unused-argument
'''
Returns the MAC Address Table on the device.
:param address: MAC address to filter on
:param interface: Interface name to filter on
:param vlan: VLAN identifier
:return: A list of dictionaries representing the entries in the MAC Address Table
CLI Example:
.. code-block:: bash
salt '*' net.mac
salt '*' net.mac vlan=10
Example output:
.. code-block:: python
[
{
'mac' : '00:1c:58:29:4a:71',
'interface' : 'xe-3/0/2',
'static' : False,
'active' : True,
'moves' : 1,
'vlan' : 10,
'last_move' : 1454417742.58
},
{
'mac' : '8c:60:4f:58:e1:c1',
'interface' : 'xe-1/0/1',
'static' : False,
'active' : True,
'moves' : 2,
'vlan' : 42,
'last_move' : 1453191948.11
}
]
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_mac_address_table',
**{
}
)
if not proxy_output.get('result'):
# if negative, leave the output unchanged
return proxy_output
mac_address_table = proxy_output.get('out')
if vlan and isinstance(vlan, int):
mac_address_table = _filter_list(mac_address_table, 'vlan', vlan)
if address:
mac_address_table = _filter_list(mac_address_table, 'mac', address)
if interface:
mac_address_table = _filter_list(mac_address_table, 'interface', interface)
proxy_output.update({
'out': mac_address_table
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def config(source=None, **kwargs): # pylint: disable=unused-argument
'''
.. versionadded:: 2017.7.0
Return the whole configuration of the network device. By default, it will
return all possible configuration sources supported by the network device.
At most, there will be:
- running config
- startup config
- candidate config
To return only one of the configurations, you can use the ``source``
argument.
source
Which configuration type you want to display, default is all of them.
Options:
- running
- candidate
- startup
:return:
The object returned is a dictionary with the following keys:
- running (string): Representation of the native running configuration.
- candidate (string): Representation of the native candidate configuration.
If the device doesn't differentiate between running and startup
configuration this will an empty string.
- startup (string): Representation of the native startup configuration.
If the device doesn't differentiate between running and startup
configuration this will an empty string.
CLI Example:
.. code-block:: bash
salt '*' net.config
salt '*' net.config source=candidate
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_config',
**{
'retrieve': source
}
)
@salt.utils.napalm.proxy_napalm_wrap
def optics(**kwargs): # pylint: disable=unused-argument
'''
.. versionadded:: 2017.7.0
Fetches the power usage on the various transceivers installed
on the network device (in dBm), and returns a view that conforms with the
OpenConfig model openconfig-platform-transceiver.yang.
:return:
Returns a dictionary where the keys are as listed below:
* intf_name (unicode)
* physical_channels
* channels (list of dicts)
* index (int)
* state
* input_power
* instant (float)
* avg (float)
* min (float)
* max (float)
* output_power
* instant (float)
* avg (float)
* min (float)
* max (float)
* laser_bias_current
* instant (float)
* avg (float)
* min (float)
* max (float)
CLI Example:
.. code-block:: bash
salt '*' net.optics
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_optics',
**{
}
)
# <---- Call NAPALM getters --------------------------------------------------------------------------------------------
# ----- Configuration specific functions ------------------------------------------------------------------------------>
@salt.utils.napalm.proxy_napalm_wrap
def load_config(filename=None,
text=None,
test=False,
commit=True,
debug=False,
replace=False,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
commit_jid=None,
inherit_napalm_device=None,
saltenv='base',
**kwargs): # pylint: disable=unused-argument
'''
Applies configuration changes on the device. It can be loaded from a file or from inline string.
If you send both a filename and a string containing the configuration, the file has higher precedence.
By default this function will commit the changes. If there are no changes, it does not commit and
the flag ``already_configured`` will be set as ``True`` to point this out.
To avoid committing the configuration, set the argument ``test`` to ``True`` and will discard (dry run).
To keep the changes but not commit, set ``commit`` to ``False``.
To replace the config, set ``replace`` to ``True``.
filename
Path to the file containing the desired configuration.
This can be specified using the absolute path to the file,
or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
.. versionchanged:: 2018.3.0
text
String containing the desired configuration.
This argument is ignored when ``filename`` is specified.
test: False
Dry run? If set as ``True``, will apply the config, discard and return the changes. Default: ``False``
and will commit the changes on the device.
commit: True
Commit? Default: ``True``.
debug: False
Debug mode. Will insert a new key under the output dictionary, as ``loaded_config`` containing the raw
configuration loaded on the device.
.. versionadded:: 2016.11.2
replace: False
Load and replace the configuration. Default: ``False``.
.. versionadded:: 2016.11.2
commit_in: ``None``
Commit the changes in a specific number of minutes / hours. Example of
accepted formats: ``5`` (commit in 5 minutes), ``2m`` (commit in 2
minutes), ``1h`` (commit the changes in 1 hour)`, ``5h30m`` (commit
the changes in 5 hours and 30 minutes).
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
commit_at: ``None``
Commit the changes at a specific time. Example of accepted formats:
``1am`` (will commit the changes at the next 1AM), ``13:20`` (will
commit at 13:20), ``1:20am``, etc.
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
revert_in: ``None``
Commit and revert the changes in a specific number of minutes / hours.
Example of accepted formats: ``5`` (revert in 5 minutes), ``2m`` (revert
in 2 minutes), ``1h`` (revert the changes in 1 hour)`, ``5h30m`` (revert
the changes in 5 hours and 30 minutes).
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
revert_at: ``None``
Commit and revert the changes at a specific time. Example of accepted
formats: ``1am`` (will commit and revert the changes at the next 1AM),
``13:20`` (will commit and revert at 13:20), ``1:20am``, etc.
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
saltenv: ``base``
Specifies the Salt environment name.
.. versionadded:: 2018.3.0
:return: a dictionary having the following keys:
* result (bool): if the config was applied successfully. It is ``False`` only in case of failure. In case \
there are no changes to be applied and successfully performs all operations it is still ``True`` and so will be \
the ``already_configured`` flag (example below)
* comment (str): a message for the user
* already_configured (bool): flag to check if there were no changes applied
* loaded_config (str): the configuration loaded on the device. Requires ``debug`` to be set as ``True``
* diff (str): returns the config changes applied
CLI Example:
.. code-block:: bash
salt '*' net.load_config text='ntp peer 192.168.0.1'
salt '*' net.load_config filename='/absolute/path/to/your/file'
salt '*' net.load_config filename='/absolute/path/to/your/file' test=True
salt '*' net.load_config filename='/absolute/path/to/your/file' commit=False
Example output:
.. code-block:: python
{
'comment': 'Configuration discarded.',
'already_configured': False,
'result': True,
'diff': '[edit interfaces xe-0/0/5]+ description "Adding a description";'
}
'''
fun = 'load_merge_candidate'
if replace:
fun = 'load_replace_candidate'
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
if filename:
text = __salt__['cp.get_file_str'](filename, saltenv=saltenv)
if text is False:
# When using salt:// or https://, if the resource is not available,
# it will either raise an exception, or return False.
ret = {
'result': False,
'out': None
}
ret['comment'] = 'Unable to read from {}. Please specify a valid file or text.'.format(filename)
log.error(ret['comment'])
return ret
if commit_jid:
# When the commit_jid argument is passed, it probably is a scheduled
# commit to be executed, and filename is a temporary file which
# can be removed after reading it.
salt.utils.files.safe_rm(filename)
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
fun,
**{
'config': text
}
)
return _config_logic(napalm_device, # pylint: disable=undefined-variable
_loaded,
test=test,
debug=debug,
replace=replace,
commit_config=commit,
loaded_config=text,
commit_at=commit_at,
commit_in=commit_in,
revert_in=revert_in,
revert_at=revert_at,
commit_jid=commit_jid,
**kwargs)
@salt.utils.napalm.proxy_napalm_wrap
def load_template(template_name=None,
template_source=None,
context=None,
defaults=None,
template_engine='jinja',
saltenv='base',
template_hash=None,
template_hash_name=None,
skip_verify=False,
test=False,
commit=True,
debug=False,
replace=False,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
inherit_napalm_device=None, # pylint: disable=unused-argument
**template_vars):
'''
Renders a configuration template (default: Jinja) and loads the result on the device.
By default this function will commit the changes. If there are no changes,
it does not commit, discards he config and the flag ``already_configured``
will be set as ``True`` to point this out.
To avoid committing the configuration, set the argument ``test`` to ``True``
and will discard (dry run).
To preserve the changes, set ``commit`` to ``False``.
However, this is recommended to be used only in exceptional cases
when there are applied few consecutive states
and/or configuration changes.
Otherwise the user might forget that the config DB is locked
and the candidate config buffer is not cleared/merged in the running config.
To replace the config, set ``replace`` to ``True``.
template_name
Identifies path to the template source.
The template can be either stored on the local machine, either remotely.
The recommended location is under the ``file_roots``
as specified in the master config file.
For example, let's suppose the ``file_roots`` is configured as:
.. code-block:: yaml
file_roots:
base:
- /etc/salt/states
Placing the template under ``/etc/salt/states/templates/example.jinja``,
it can be used as ``salt://templates/example.jinja``.
Alternatively, for local files, the user can specify the absolute path.
If remotely, the source can be retrieved via ``http``, ``https`` or ``ftp``.
Examples:
- ``salt://my_template.jinja``
- ``/absolute/path/to/my_template.jinja``
- ``http://example.com/template.cheetah``
- ``https:/example.com/template.mako``
- ``ftp://example.com/template.py``
.. versionchanged:: 2019.2.0
This argument can now support a list of templates to be rendered.
The resulting configuration text is loaded at once, as a single
configuration chunk.
template_source: None
Inline config template to be rendered and loaded on the device.
template_hash: None
Hash of the template file. Format: ``{hash_type: 'md5', 'hsum': <md5sum>}``
.. versionadded:: 2016.11.2
context: None
Overrides default context variables passed to the template.
.. versionadded:: 2019.2.0
template_hash_name: None
When ``template_hash`` refers to a remote file,
this specifies the filename to look for in that file.
.. versionadded:: 2016.11.2
saltenv: ``base``
Specifies the template environment.
This will influence the relative imports inside the templates.
.. versionadded:: 2016.11.2
template_engine: jinja
The following templates engines are supported:
- :mod:`cheetah<salt.renderers.cheetah>`
- :mod:`genshi<salt.renderers.genshi>`
- :mod:`jinja<salt.renderers.jinja>`
- :mod:`mako<salt.renderers.mako>`
- :mod:`py<salt.renderers.py>`
- :mod:`wempy<salt.renderers.wempy>`
.. versionadded:: 2016.11.2
skip_verify: True
If ``True``, hash verification of remote file sources
(``http://``, ``https://``, ``ftp://``) will be skipped,
and the ``source_hash`` argument will be ignored.
.. versionadded:: 2016.11.2
test: False
Dry run? If set to ``True``, will apply the config,
discard and return the changes.
Default: ``False`` and will commit the changes on the device.
commit: True
Commit? (default: ``True``)
debug: False
Debug mode. Will insert a new key under the output dictionary,
as ``loaded_config`` containing the raw result after the template was rendered.
.. versionadded:: 2016.11.2
replace: False
Load and replace the configuration.
.. versionadded:: 2016.11.2
commit_in: ``None``
Commit the changes in a specific number of minutes / hours. Example of
accepted formats: ``5`` (commit in 5 minutes), ``2m`` (commit in 2
minutes), ``1h`` (commit the changes in 1 hour)`, ``5h30m`` (commit
the changes in 5 hours and 30 minutes).
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
commit_at: ``None``
Commit the changes at a specific time. Example of accepted formats:
``1am`` (will commit the changes at the next 1AM), ``13:20`` (will
commit at 13:20), ``1:20am``, etc.
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
revert_in: ``None``
Commit and revert the changes in a specific number of minutes / hours.
Example of accepted formats: ``5`` (revert in 5 minutes), ``2m`` (revert
in 2 minutes), ``1h`` (revert the changes in 1 hour)`, ``5h30m`` (revert
the changes in 5 hours and 30 minutes).
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
revert_at: ``None``
Commit and revert the changes at a specific time. Example of accepted
formats: ``1am`` (will commit and revert the changes at the next 1AM),
``13:20`` (will commit and revert at 13:20), ``1:20am``, etc.
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
defaults: None
Default variables/context passed to the template.
.. versionadded:: 2016.11.2
template_vars
Dictionary with the arguments/context to be used when the template is rendered.
.. note::
Do not explicitly specify this argument. This represents any other
variable that will be sent to the template rendering system.
Please see the examples below!
.. note::
It is more recommended to use the ``context`` argument to avoid
conflicts between CLI arguments and template variables.
:return: a dictionary having the following keys:
- result (bool): if the config was applied successfully. It is ``False``
only in case of failure. In case there are no changes to be applied and
successfully performs all operations it is still ``True`` and so will be
the ``already_configured`` flag (example below)
- comment (str): a message for the user
- already_configured (bool): flag to check if there were no changes applied
- loaded_config (str): the configuration loaded on the device, after
rendering the template. Requires ``debug`` to be set as ``True``
- diff (str): returns the config changes applied
The template can use variables from the ``grains``, ``pillar`` or ``opts``, for example:
.. code-block:: jinja
{% set router_model = grains.get('model') -%}
{% set router_vendor = grains.get('vendor') -%}
{% set os_version = grains.get('version') -%}
{% set hostname = pillar.get('proxy', {}).get('host') -%}
{% if router_vendor|lower == 'juniper' %}
system {
host-name {{hostname}};
}
{% elif router_vendor|lower == 'cisco' %}
hostname {{hostname}}
{% endif %}
CLI Examples:
.. code-block:: bash
salt '*' net.load_template set_ntp_peers peers=[192.168.0.1] # uses NAPALM default templates
# inline template:
salt -G 'os:junos' net.load_template template_source='system { host-name {{host_name}}; }' \
host_name='MX480.lab'
# inline template using grains info:
salt -G 'os:junos' net.load_template \
template_source='system { host-name {{grains.model}}.lab; }'
# if the device is a MX480, the command above will set the hostname as: MX480.lab
# inline template using pillar data:
salt -G 'os:junos' net.load_template template_source='system { host-name {{pillar.proxy.host}}; }'
salt '*' net.load_template https://bit.ly/2OhSgqP hostname=example # will commit
salt '*' net.load_template https://bit.ly/2OhSgqP hostname=example test=True # dry run
salt '*' net.load_template salt://templates/example.jinja debug=True # Using the salt:// URI
# render a mako template:
salt '*' net.load_template salt://templates/example.mako template_engine=mako debug=True
# render remote template
salt -G 'os:junos' net.load_template http://bit.ly/2fReJg7 test=True debug=True peers=['192.168.0.1']
salt -G 'os:ios' net.load_template http://bit.ly/2gKOj20 test=True debug=True peers=['192.168.0.1']
# render multiple templates at once
salt '*' net.load_template "['https://bit.ly/2OhSgqP', 'salt://templates/example.jinja']" context="{'hostname': 'example'}"
Example output:
.. code-block:: python
{
'comment': '',
'already_configured': False,
'result': True,
'diff': '[edit system]+ host-name edge01.bjm01',
'loaded_config': 'system { host-name edge01.bjm01; }''
}
'''
_rendered = ''
_loaded = {
'result': True,
'comment': '',
'out': None
}
loaded_config = None
# prechecks
deprecated_args = ('template_user', 'template_attrs', 'template_group', 'template_mode')
for deprecated_arg in deprecated_args:
if template_vars.get(deprecated_arg):
del template_vars[deprecated_arg]
salt.utils.versions.warn_until(
'Sodium',
('The \'{arg}\' argument to \'net.load_template\' is deprecated '
'and has been ignored').format(arg=deprecated_arg)
)
if template_engine not in salt.utils.templates.TEMPLATE_REGISTRY:
_loaded.update({
'result': False,
'comment': 'Invalid templating engine! Choose between: {tpl_eng_opts}'.format(
tpl_eng_opts=', '.join(list(salt.utils.templates.TEMPLATE_REGISTRY.keys()))
)
})
return _loaded # exit
# to check if will be rendered by salt or NAPALM
salt_render_prefixes = ('salt://', 'http://', 'https://', 'ftp://')
salt_render = False
file_exists = False
if not isinstance(template_name, (tuple, list)):
for salt_render_prefix in salt_render_prefixes:
if not salt_render:
salt_render = salt_render or template_name.startswith(salt_render_prefix)
file_exists = __salt__['file.file_exists'](template_name)
if template_source or file_exists or salt_render or isinstance(template_name, (tuple, list)):
# either inline template
# either template in a custom path
# either abs path send
# either starts with salt:// and
# then use Salt render system
if context is None:
context = {}
context.update(template_vars)
# if needed to render the template send as inline arg
if template_source:
# render the content
_rendered = __salt__['file.apply_template_on_contents'](
contents=template_source,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv
)
if not isinstance(_rendered, six.string_types):
if 'result' in _rendered:
_loaded['result'] = _rendered['result']
else:
_loaded['result'] = False
if 'comment' in _rendered:
_loaded['comment'] = _rendered['comment']
else:
_loaded['comment'] = 'Error while rendering the template.'
return _loaded
else:
# render the file - either local, either remote
if not isinstance(template_name, (list, tuple)):
template_name = [template_name]
if template_hash_name and not isinstance(template_hash_name, (list, tuple)):
template_hash_name = [template_hash_name]
elif not template_hash_name:
template_hash_name = [None] * len(template_name)
if template_hash and isinstance(template_hash, six.string_types) and not\
(template_hash.startswith('salt://') or template_hash.startswith('file://')):
# If the template hash is passed as string, and it's not a file
# (starts with the salt:// or file:// URI), then make it a list
# of 1 element (for the iteration below)
template_hash = [template_hash]
elif template_hash and isinstance(template_hash, six.string_types) and\
(template_hash.startswith('salt://') or template_hash.startswith('file://')):
# If the template hash is a file URI, then provide the same value
# for each of the templates in the list, as probably they all
# share the same hash file, otherwise the user should provide
# this as a list
template_hash = [template_hash] * len(template_name)
elif not template_hash:
template_hash = [None] * len(template_name)
for tpl_index, tpl_name in enumerate(template_name):
tpl_hash = template_hash[tpl_index]
tpl_hash_name = template_hash_name[tpl_index]
_rand_filename = __salt__['random.hash'](tpl_name, 'md5')
_temp_file = __salt__['file.join']('/tmp', _rand_filename)
_managed = __salt__['file.get_managed'](name=_temp_file,
source=tpl_name,
source_hash=tpl_hash,
source_hash_name=tpl_hash_name,
user=None,
group=None,
mode=None,
attrs=None,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv,
skip_verify=skip_verify)
if not isinstance(_managed, (list, tuple)) and isinstance(_managed, six.string_types):
_loaded['comment'] += _managed
_loaded['result'] = False
elif isinstance(_managed, (list, tuple)) and not _managed:
_loaded['result'] = False
_loaded['comment'] += 'Error while rendering the template.'
elif isinstance(_managed, (list, tuple)) and not _managed[0]:
_loaded['result'] = False
_loaded['comment'] += _managed[-1] # contains the error message
if _loaded['result']: # all good
_temp_tpl_file = _managed[0]
_temp_tpl_file_exists = __salt__['file.file_exists'](_temp_tpl_file)
if not _temp_tpl_file_exists:
_loaded['result'] = False
_loaded['comment'] += 'Error while rendering the template.'
return _loaded
_rendered += __salt__['file.read'](_temp_tpl_file)
__salt__['file.remove'](_temp_tpl_file)
else:
return _loaded # exit
loaded_config = _rendered
if _loaded['result']: # all good
fun = 'load_merge_candidate'
if replace: # replace requested
fun = 'load_replace_candidate'
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
fun,
**{
'config': _rendered
}
)
else:
salt.utils.versions.warn_until(
'Sodium',
'Native NAPALM templates support will be removed in the Sodium '
'release. Please consider using the Salt rendering pipeline instead.'
'If you are using the \'netntp\', \'netsnmp\', or \'netusers\' Salt '
'State modules, you can ignore this message'
)
# otherwise, use NAPALM render system, injecting pillar/grains/opts vars
load_templates_params = defaults if defaults else {}
load_templates_params.update(template_vars)
load_templates_params.update(
{
'template_name': template_name,
'template_source': template_source, # inline template
'pillar': __pillar__, # inject pillar content
'grains': __grains__, # inject grains content
'opts': __opts__ # inject opts content
}
)
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
# so we'll set the CLOSE global explicitly as False
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'load_template',
**load_templates_params
)
return _config_logic(napalm_device, # pylint: disable=undefined-variable
_loaded,
test=test,
debug=debug,
replace=replace,
commit_config=commit,
loaded_config=loaded_config,
commit_at=commit_at,
commit_in=commit_in,
revert_in=revert_in,
revert_at=revert_at,
**template_vars)
@salt.utils.napalm.proxy_napalm_wrap
def commit(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Commits the configuration changes made on the network device.
CLI Example:
.. code-block:: bash
salt '*' net.commit
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'commit_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def discard_config(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
"""
Discards the changes applied.
CLI Example:
.. code-block:: bash
salt '*' net.discard_config
"""
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'discard_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def compare_config(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Returns the difference between the running config and the candidate config.
CLI Example:
.. code-block:: bash
salt '*' net.compare_config
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'compare_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def rollback(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Rollbacks the configuration.
CLI Example:
.. code-block:: bash
salt '*' net.rollback
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'rollback',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def config_changed(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Will prompt if the configuration has been changed.
:return: A tuple with a boolean that specifies if the config was changed on the device.\
And a string that provides more details of the reason why the configuration was not changed.
CLI Example:
.. code-block:: bash
salt '*' net.config_changed
'''
is_config_changed = False
reason = ''
try_compare = compare_config(inherit_napalm_device=napalm_device) # pylint: disable=undefined-variable
if try_compare.get('result'):
if try_compare.get('out'):
is_config_changed = True
else:
reason = 'Configuration was not changed on the device.'
else:
reason = try_compare.get('comment')
return is_config_changed, reason
@salt.utils.napalm.proxy_napalm_wrap
def config_control(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Will check if the configuration was changed.
If differences found, will try to commit.
In case commit unsuccessful, will try to rollback.
:return: A tuple with a boolean that specifies if the config was changed/committed/rollbacked on the device.\
And a string that provides more details of the reason why the configuration was not committed properly.
CLI Example:
.. code-block:: bash
salt '*' net.config_control
'''
result = True
comment = ''
changed, not_changed_rsn = config_changed(inherit_napalm_device=napalm_device) # pylint: disable=undefined-variable
if not changed:
return (changed, not_changed_rsn)
# config changed, thus let's try to commit
try_commit = commit()
if not try_commit.get('result'):
result = False
comment = 'Unable to commit the changes: {reason}.\n\
Will try to rollback now!'.format(
reason=try_commit.get('comment')
)
try_rollback = rollback()
if not try_rollback.get('result'):
comment += '\nCannot rollback! {reason}'.format(
reason=try_rollback.get('comment')
)
return result, comment
def cancel_commit(jid):
'''
.. versionadded:: 2019.2.0
Cancel a commit scheduled to be executed via the ``commit_in`` and
``commit_at`` arguments from the
:py:func:`net.load_template <salt.modules.napalm_network.load_template>` or
:py:func:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit ID is displayed when the commit is scheduled
via the functions named above.
CLI Example:
.. code-block:: bash
salt '*' net.cancel_commit 20180726083540640360
'''
job_name = '__napalm_commit_{}'.format(jid)
removed = __salt__['schedule.delete'](job_name)
if removed['result']:
saved = __salt__['schedule.save']()
removed['comment'] = 'Commit #{jid} cancelled.'.format(jid=jid)
else:
removed['comment'] = 'Unable to find commit #{jid}.'.format(jid=jid)
return removed
def confirm_commit(jid):
'''
.. versionadded:: 2019.2.0
Confirm a commit scheduled to be reverted via the ``revert_in`` and
``revert_at`` arguments from the
:mod:`net.load_template <salt.modules.napalm_network.load_template>` or
:mod:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit ID is displayed when the commit confirmed
is scheduled via the functions named above.
CLI Example:
.. code-block:: bash
salt '*' net.confirm_commit 20180726083540640360
'''
if __grains__['os'] == 'junos':
# Confirm the commit, by committing (i.e., invoking the RPC call)
confirmed = __salt__['napalm.junos_commit']()
confirmed['result'] = confirmed.pop('out')
confirmed['comment'] = confirmed.pop('message')
else:
confirmed = cancel_commit(jid)
if confirmed['result']:
confirmed['comment'] = 'Commit #{jid} confirmed.'.format(jid=jid)
return confirmed
def save_config(source=None,
path=None):
'''
.. versionadded:: 2019.2.0
Save the configuration to a file on the local file system.
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``,
``startup``. Default: ``running``.
path
Absolute path to file where to save the configuration.
To push the files to the Master, use
:mod:`cp.push <salt.modules.cp.push>` Execution function.
CLI Example:
.. code-block:: bash
salt '*' net.save_config source=running
'''
if not source:
source = 'running'
if not path:
path = salt.utils.files.mkstemp()
running_config = __salt__['net.config'](source=source)
if not running_config or not running_config['result']:
log.error('Unable to retrieve the config')
return running_config
with salt.utils.files.fopen(path, 'w') as fh_:
fh_.write(running_config['out'][source])
return {
'result': True,
'out': path,
'comment': '{source} config saved to {path}'.format(source=source, path=path)
}
def replace_pattern(pattern,
repl,
count=0,
flags=8,
bufsize=1,
append_if_not_found=False,
prepend_if_not_found=False,
not_found_content=None,
search_only=False,
show_changes=True,
backslash_literal=False,
source=None,
path=None,
test=False,
replace=True,
debug=False,
commit=True):
'''
.. versionadded:: 2019.2.0
Replace occurrences of a pattern in the configuration source. If
``show_changes`` is ``True``, then a diff of what changed will be returned,
otherwise a ``True`` will be returned when changes are made, and ``False``
when no changes are made.
This is a pure Python implementation that wraps Python's :py:func:`~re.sub`.
pattern
A regular expression, to be matched using Python's
:py:func:`~re.search`.
repl
The replacement text.
count: ``0``
Maximum number of pattern occurrences to be replaced. If count is a
positive integer ``n``, only ``n`` occurrences will be replaced,
otherwise all occurrences will be replaced.
flags (list or int): ``8``
A list of flags defined in the ``re`` module documentation from the
Python standard library. Each list item should be a string that will
correlate to the human-friendly flag name. E.g., ``['IGNORECASE',
'MULTILINE']``. Optionally, ``flags`` may be an int, with a value
corresponding to the XOR (``|``) of all the desired flags. Defaults to
8 (which supports 'MULTILINE').
bufsize (int or str): ``1``
How much of the configuration to buffer into memory at once. The
default value ``1`` processes one line at a time. The special value
``file`` may be specified which will read the entire file into memory
before processing.
append_if_not_found: ``False``
If set to ``True``, and pattern is not found, then the content will be
appended to the file.
prepend_if_not_found: ``False``
If set to ``True`` and pattern is not found, then the content will be
prepended to the file.
not_found_content
Content to use for append/prepend if not found. If None (default), uses
``repl``. Useful when ``repl`` uses references to group in pattern.
search_only: ``False``
If set to true, this no changes will be performed on the file, and this
function will simply return ``True`` if the pattern was matched, and
``False`` if not.
show_changes: ``True``
If ``True``, return a diff of changes made. Otherwise, return ``True``
if changes were made, and ``False`` if not.
backslash_literal: ``False``
Interpret backslashes as literal backslashes for the repl and not
escape characters. This will help when using append/prepend so that
the backslashes are not interpreted for the repl on the second run of
the state.
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path
Save the temporary configuration to a specific path, then read from
there.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' net.replace_pattern "bind-address\\s*=" "bind-address:"
CLI Example:
.. code-block:: bash
salt '*' net.replace_pattern PREFIX-LIST_NAME new-prefix-list-name
salt '*' net.replace_pattern bgp-group-name new-bgp-group-name count=1
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
replace_pattern = __salt__['file.replace'](path,
pattern,
repl,
count=count,
flags=flags,
bufsize=bufsize,
append_if_not_found=append_if_not_found,
prepend_if_not_found=prepend_if_not_found,
not_found_content=not_found_content,
search_only=search_only,
show_changes=show_changes,
backslash_literal=backslash_literal)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
def blockreplace(marker_start,
marker_end,
content='',
append_if_not_found=False,
prepend_if_not_found=False,
show_changes=True,
append_newline=False,
source='running',
path=None,
test=False,
commit=True,
debug=False,
replace=True):
'''
.. versionadded:: 2019.2.0
Replace content of the configuration source, delimited by the line markers.
A block of content delimited by comments can help you manage several lines
without worrying about old entries removal.
marker_start
The line content identifying a line as the start of the content block.
Note that the whole line containing this marker will be considered,
so whitespace or extra content before or after the marker is included
in final output.
marker_end
The line content identifying a line as the end of the content block.
Note that the whole line containing this marker will be considered,
so whitespace or extra content before or after the marker is included
in final output.
content
The content to be used between the two lines identified by
``marker_start`` and ``marker_stop``.
append_if_not_found: ``False``
If markers are not found and set to True then, the markers and content
will be appended to the file.
prepend_if_not_found: ``False``
If markers are not found and set to True then, the markers and content
will be prepended to the file.
append_newline: ``False``
Controls whether or not a newline is appended to the content block.
If the value of this argument is ``True`` then a newline will be added
to the content block. If it is ``False``, then a newline will not be
added to the content block. If it is ``None`` then a newline will only
be added to the content block if it does not already end in a newline.
show_changes: ``True``
Controls how changes are presented. If ``True``, this function will
return the of the changes made.
If ``False``, then it will return a boolean (``True`` if any changes
were made, otherwise False).
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path: ``None``
Save the temporary configuration to a specific path, then read from
there. This argument is optional, can be used when you prefers a
particular location of the temporary file.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
CLI Example:
.. code-block:: bash
salt '*' net.blockreplace 'ntp' 'interface' ''
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
replace_pattern = __salt__['file.blockreplace'](path,
marker_start=marker_start,
marker_end=marker_end,
content=content,
append_if_not_found=append_if_not_found,
prepend_if_not_found=prepend_if_not_found,
show_changes=show_changes,
append_newline=append_newline)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
def patch(patchfile,
options='',
saltenv='base',
source_hash=None,
show_changes=True,
source='running',
path=None,
test=False,
commit=True,
debug=False,
replace=True):
'''
.. versionadded:: 2019.2.0
Apply a patch to the configuration source, and load the result into the
running config of the device.
patchfile
A patch file to apply to the configuration source.
options
Options to pass to patch.
source_hash
If the patch file (specified via the ``patchfile`` argument) is an
HTTP(S) or FTP URL and the file exists in the minion's file cache, this
option can be passed to keep the minion from re-downloading the file if
the cached copy matches the specified hash.
show_changes: ``True``
Controls how changes are presented. If ``True``, this function will
return the of the changes made.
If ``False``, then it will return a boolean (``True`` if any changes
were made, otherwise False).
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path: ``None``
Save the temporary configuration to a specific path, then read from
there. This argument is optional, can the user prefers a particular
location of the temporary file.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
CLI Example:
.. code-block:: bash
salt '*' net.patch https://example.com/running_config.patch
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
patchfile_cache = __salt__['cp.cache_file'](patchfile)
if patchfile_cache is False:
return {
'out': None,
'result': False,
'comment': 'The file "{}" does not exist.'.format(patchfile)
}
replace_pattern = __salt__['file.patch'](path,
patchfile_cache,
options=options)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
# <---- Configuration specific functions -------------------------------------------------------------------------------
|
saltstack/salt
|
salt/modules/napalm_network.py
|
_config_logic
|
python
|
def _config_logic(napalm_device,
loaded_result,
test=False,
debug=False,
replace=False,
commit_config=True,
loaded_config=None,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
commit_jid=None,
**kwargs):
'''
Builds the config logic for `load_config` and `load_template` functions.
'''
# As the Salt logic is built around independent events
# when it comes to configuration changes in the
# candidate DB on the network devices, we need to
# make sure we're using the same session.
# Hence, we need to pass the same object around.
# the napalm_device object is inherited from
# the load_config or load_template functions
# and forwarded to compare, discard, commit etc.
# then the decorator will make sure that
# if not proxy (when the connection is always alive)
# and the `inherit_napalm_device` is set,
# `napalm_device` will be overridden.
# See `salt.utils.napalm.proxy_napalm_wrap` decorator.
current_jid = kwargs.get('__pub_jid')
if not current_jid:
current_jid = '{0:%Y%m%d%H%M%S%f}'.format(datetime.datetime.now())
loaded_result['already_configured'] = False
loaded_result['loaded_config'] = ''
if debug:
loaded_result['loaded_config'] = loaded_config
_compare = compare_config(inherit_napalm_device=napalm_device)
if _compare.get('result', False):
loaded_result['diff'] = _compare.get('out')
loaded_result.pop('out', '') # not needed
else:
loaded_result['diff'] = None
loaded_result['result'] = False
loaded_result['comment'] = _compare.get('comment')
__context__['retcode'] = 1
return loaded_result
_loaded_res = loaded_result.get('result', False)
if not _loaded_res or test:
# if unable to load the config (errors / warnings)
# or in testing mode,
# will discard the config
if loaded_result['comment']:
loaded_result['comment'] += '\n'
if not loaded_result.get('diff', ''):
loaded_result['already_configured'] = True
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
loaded_result['comment'] += 'Configuration discarded.'
# loaded_result['result'] = False not necessary
# as the result can be true when test=True
_explicit_close(napalm_device)
if not loaded_result['result']:
__context__['retcode'] = 1
return loaded_result
if not test and commit_config:
# if not in testing mode and trying to commit
if commit_jid:
log.info('Committing the JID: %s', str(commit_jid))
removed = cancel_commit(commit_jid)
log.debug('Cleaned up the commit from the schedule')
log.debug(removed['comment'])
if loaded_result.get('diff', ''):
# if not testing mode
# and also the user wants to commit (default)
# and there are changes to commit
if commit_in or commit_at:
commit_time = __utils__['timeutil.get_time_at'](time_in=commit_in,
time_at=commit_in)
# schedule job
scheduled_job_name = '__napalm_commit_{}'.format(current_jid)
temp_file = salt.utils.files.mkstemp()
with salt.utils.files.fopen(temp_file, 'w') as fp_:
fp_.write(loaded_config)
scheduled = __salt__['schedule.add'](scheduled_job_name,
function='net.load_config',
job_kwargs={
'filename': temp_file,
'commit_jid': current_jid,
'replace': replace
},
once=commit_time)
log.debug('Scheduling job')
log.debug(scheduled)
saved = __salt__['schedule.save']() # ensure the schedule is
# persistent cross Minion restart
discarded = _safe_dicard_config(loaded_result, napalm_device)
# discard the changes
if not discarded['result']:
discarded['comment'] += ('Scheduled the job to be executed at {schedule_ts}, '
'but was unable to discard the config: \n').format(schedule_ts=commit_time)
return discarded
loaded_result['comment'] = ('Changes discarded for now, and scheduled commit at: {schedule_ts}.\n'
'The commit ID is: {current_jid}.\n'
'To discard this commit, you can execute: \n\n'
'salt {min_id} net.cancel_commit {current_jid}').format(schedule_ts=commit_time,
min_id=__opts__['id'],
current_jid=current_jid)
loaded_result['commit_id'] = current_jid
return loaded_result
log.debug('About to commit:')
log.debug(loaded_result['diff'])
if revert_in or revert_at:
revert_time = __utils__['timeutil.get_time_at'](time_in=revert_in,
time_at=revert_at)
if __grains__['os'] == 'junos':
if not HAS_JXMLEASE:
loaded_result['comment'] = ('This feature requires the library jxmlease to be installed.\n'
'To install, please execute: ``pip install jxmlease``.')
loaded_result['result'] = False
return loaded_result
timestamp_at = __utils__['timeutil.get_timestamp_at'](time_in=revert_in,
time_at=revert_at)
minutes = int((timestamp_at - time.time())/60)
_comm = __salt__['napalm.junos_commit'](confirm=minutes)
if not _comm['out']:
# If unable to commit confirm, should try to bail out
loaded_result['comment'] = 'Unable to commit confirm: {}'.format(_comm['message'])
loaded_result['result'] = False
# But before exiting, we must gracefully discard the config
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
else:
temp_file = salt.utils.files.mkstemp()
running_config = __salt__['net.config'](source='running')['out']['running']
with salt.utils.files.fopen(temp_file, 'w') as fp_:
fp_.write(running_config)
committed = _safe_commit_config(loaded_result, napalm_device)
if not committed['result']:
# If unable to commit, dicard the config (which is
# already done by the _safe_commit_config function), and
# return with the command and other details.
return loaded_result
scheduled_job_name = '__napalm_commit_{}'.format(current_jid)
scheduled = __salt__['schedule.add'](scheduled_job_name,
function='net.load_config',
job_kwargs={
'filename': temp_file,
'commit_jid': current_jid,
'replace': True
},
once=revert_time)
log.debug('Scheduling commit confirmed')
log.debug(scheduled)
saved = __salt__['schedule.save']()
loaded_result['comment'] = ('The commit ID is: {current_jid}.\n'
'This commit will be reverted at: {schedule_ts}, unless confirmed.\n'
'To confirm the commit and avoid reverting, you can execute:\n\n'
'salt {min_id} net.confirm_commit {current_jid}').format(schedule_ts=revert_time,
min_id=__opts__['id'],
current_jid=current_jid)
loaded_result['commit_id'] = current_jid
return loaded_result
committed = _safe_commit_config(loaded_result, napalm_device)
if not committed['result']:
return loaded_result
else:
# would like to commit, but there's no change
# need to call discard_config() to release the config DB
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
loaded_result['already_configured'] = True
loaded_result['comment'] = 'Already configured.'
_explicit_close(napalm_device)
if not loaded_result['result']:
__context__['retcode'] = 1
return loaded_result
|
Builds the config logic for `load_config` and `load_template` functions.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_network.py#L161-L345
|
[
"def mkstemp(*args, **kwargs):\n '''\n Helper function which does exactly what ``tempfile.mkstemp()`` does but\n accepts another argument, ``close_fd``, which, by default, is true and closes\n the fd before returning the file path. Something commonly done throughout\n Salt's code.\n '''\n if 'prefix' not in kwargs:\n kwargs['prefix'] = '__salt.tmp.'\n close_fd = kwargs.pop('close_fd', True)\n fd_, f_path = tempfile.mkstemp(*args, **kwargs)\n if close_fd is False:\n return fd_, f_path\n os.close(fd_)\n del fd_\n return f_path\n",
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n",
"def _safe_commit_config(loaded_result, napalm_device):\n _commit = commit(inherit_napalm_device=napalm_device) # calls the function commit, defined below\n if not _commit.get('result', False):\n # if unable to commit\n loaded_result['comment'] += _commit['comment'] if _commit.get('comment') else 'Unable to commit.'\n loaded_result['result'] = False\n # unable to commit, something went wrong\n discarded = _safe_dicard_config(loaded_result, napalm_device)\n if not discarded['result']:\n return loaded_result\n return _commit\n",
"def _safe_dicard_config(loaded_result, napalm_device):\n '''\n '''\n log.debug('Discarding the config')\n log.debug(loaded_result)\n _discarded = discard_config(inherit_napalm_device=napalm_device)\n if not _discarded.get('result', False):\n loaded_result['comment'] += _discarded['comment'] if _discarded.get('comment') \\\n else 'Unable to discard config.'\n loaded_result['result'] = False\n # make sure it notifies\n # that something went wrong\n _explicit_close(napalm_device)\n __context__['retcode'] = 1\n return loaded_result\n return _discarded\n",
"def _explicit_close(napalm_device):\n '''\n Will explicily close the config session with the network device,\n when running in a now-always-alive proxy minion or regular minion.\n This helper must be used in configuration-related functions,\n as the session is preserved and not closed before making any changes.\n '''\n if salt.utils.napalm.not_always_alive(__opts__):\n # force closing the configuration session\n # when running in a non-always-alive proxy\n # or regular minion\n try:\n napalm_device['DRIVER'].close()\n except Exception as err:\n log.error('Unable to close the temp connection with the device:')\n log.error(err)\n log.error('Please report.')\n"
] |
# -*- coding: utf-8 -*-
'''
NAPALM Network
==============
Basic methods for interaction with the network device through the virtual proxy 'napalm'.
:codeauthor: Mircea Ulinic <mircea@cloudflare.com> & Jerome Fleury <jf@cloudflare.com>
:maturity: new
:depends: napalm
:platform: unix
Dependencies
------------
- :mod:`napalm proxy minion <salt.proxy.napalm>`
.. versionadded:: 2016.11.0
.. versionchanged:: 2017.7.0
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import time
import logging
import datetime
log = logging.getLogger(__name__)
# Import Salt libs
from salt.ext import six
import salt.utils.files
import salt.utils.napalm
import salt.utils.versions
import salt.utils.templates
# Import 3rd-party libs
try:
import jxmlease # pylint: disable=unused-import
HAS_JXMLEASE = True
except ImportError:
HAS_JXMLEASE = False
# ----------------------------------------------------------------------------------------------------------------------
# module properties
# ----------------------------------------------------------------------------------------------------------------------
__virtualname__ = 'net'
__proxyenabled__ = ['*']
__virtual_aliases__ = ('napalm_net',)
# uses NAPALM-based proxy to interact with network devices
# ----------------------------------------------------------------------------------------------------------------------
# property functions
# ----------------------------------------------------------------------------------------------------------------------
def __virtual__():
'''
NAPALM library must be installed for this module to work and run in a (proxy) minion.
'''
return salt.utils.napalm.virtual(__opts__, __virtualname__, __file__)
# ----------------------------------------------------------------------------------------------------------------------
# helper functions -- will not be exported
# ----------------------------------------------------------------------------------------------------------------------
def _filter_list(input_list, search_key, search_value):
'''
Filters a list of dictionary by a set of key-value pair.
:param input_list: is a list of dictionaries
:param search_key: is the key we are looking for
:param search_value: is the value we are looking for the key specified in search_key
:return: filered list of dictionaries
'''
output_list = list()
for dictionary in input_list:
if dictionary.get(search_key) == search_value:
output_list.append(dictionary)
return output_list
def _filter_dict(input_dict, search_key, search_value):
'''
Filters a dictionary of dictionaries by a key-value pair.
:param input_dict: is a dictionary whose values are lists of dictionaries
:param search_key: is the key in the leaf dictionaries
:param search_values: is the value in the leaf dictionaries
:return: filtered dictionary
'''
output_dict = dict()
for key, key_list in six.iteritems(input_dict):
key_list_filtered = _filter_list(key_list, search_key, search_value)
if key_list_filtered:
output_dict[key] = key_list_filtered
return output_dict
def _safe_commit_config(loaded_result, napalm_device):
_commit = commit(inherit_napalm_device=napalm_device) # calls the function commit, defined below
if not _commit.get('result', False):
# if unable to commit
loaded_result['comment'] += _commit['comment'] if _commit.get('comment') else 'Unable to commit.'
loaded_result['result'] = False
# unable to commit, something went wrong
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
return _commit
def _safe_dicard_config(loaded_result, napalm_device):
'''
'''
log.debug('Discarding the config')
log.debug(loaded_result)
_discarded = discard_config(inherit_napalm_device=napalm_device)
if not _discarded.get('result', False):
loaded_result['comment'] += _discarded['comment'] if _discarded.get('comment') \
else 'Unable to discard config.'
loaded_result['result'] = False
# make sure it notifies
# that something went wrong
_explicit_close(napalm_device)
__context__['retcode'] = 1
return loaded_result
return _discarded
def _explicit_close(napalm_device):
'''
Will explicily close the config session with the network device,
when running in a now-always-alive proxy minion or regular minion.
This helper must be used in configuration-related functions,
as the session is preserved and not closed before making any changes.
'''
if salt.utils.napalm.not_always_alive(__opts__):
# force closing the configuration session
# when running in a non-always-alive proxy
# or regular minion
try:
napalm_device['DRIVER'].close()
except Exception as err:
log.error('Unable to close the temp connection with the device:')
log.error(err)
log.error('Please report.')
# ----------------------------------------------------------------------------------------------------------------------
# callable functions
# ----------------------------------------------------------------------------------------------------------------------
@salt.utils.napalm.proxy_napalm_wrap
def connected(**kwargs): # pylint: disable=unused-argument
'''
Specifies if the connection to the device succeeded.
CLI Example:
.. code-block:: bash
salt '*' net.connected
'''
return {
'out': napalm_device.get('UP', False) # pylint: disable=undefined-variable
}
@salt.utils.napalm.proxy_napalm_wrap
def facts(**kwargs): # pylint: disable=unused-argument
'''
Returns characteristics of the network device.
:return: a dictionary with the following keys:
* uptime - Uptime of the device in seconds.
* vendor - Manufacturer of the device.
* model - Device model.
* hostname - Hostname of the device
* fqdn - Fqdn of the device
* os_version - String with the OS version running on the device.
* serial_number - Serial number of the device
* interface_list - List of the interfaces of the device
CLI Example:
.. code-block:: bash
salt '*' net.facts
Example output:
.. code-block:: python
{
'os_version': '13.3R6.5',
'uptime': 10117140,
'interface_list': [
'lc-0/0/0',
'pfe-0/0/0',
'pfh-0/0/0',
'xe-0/0/0',
'xe-0/0/1',
'xe-0/0/2',
'xe-0/0/3',
'gr-0/0/10',
'ip-0/0/10'
],
'vendor': 'Juniper',
'serial_number': 'JN131356FBFA',
'model': 'MX480',
'hostname': 're0.edge05.syd01',
'fqdn': 're0.edge05.syd01'
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_facts',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def environment(**kwargs): # pylint: disable=unused-argument
'''
Returns the environment of the device.
CLI Example:
.. code-block:: bash
salt '*' net.environment
Example output:
.. code-block:: python
{
'fans': {
'Bottom Rear Fan': {
'status': True
},
'Bottom Middle Fan': {
'status': True
},
'Top Middle Fan': {
'status': True
},
'Bottom Front Fan': {
'status': True
},
'Top Front Fan': {
'status': True
},
'Top Rear Fan': {
'status': True
}
},
'memory': {
'available_ram': 16349,
'used_ram': 4934
},
'temperature': {
'FPC 0 Exhaust A': {
'is_alert': False,
'temperature': 35.0,
'is_critical': False
}
},
'cpu': {
'1': {
'%usage': 19.0
},
'0': {
'%usage': 35.0
}
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_environment',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def cli(*commands, **kwargs): # pylint: disable=unused-argument
'''
Returns a dictionary with the raw output of all commands passed as arguments.
commands
List of commands to be executed on the device.
textfsm_parse: ``False``
Try parsing the outputs using the TextFSM templates.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``napalm_cli_textfsm_parse``.
textfsm_path
The path where the TextFSM templates can be found. This option implies
the usage of the TextFSM index file.
``textfsm_path`` can be either absolute path on the server,
either specified using the following URL mschemes: ``file://``,
``salt://``, ``http://``, ``https://``, ``ftp://``,
``s3://``, ``swift://``.
.. versionadded:: 2018.3.0
.. note::
This needs to be a directory with a flat structure, having an
index file (whose name can be specified using the ``index_file`` option)
and a number of TextFSM templates.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_path``.
textfsm_template
The path to a certain the TextFSM template.
This can be specified using the absolute path
to the file, or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
.. versionadded:: 2018.3.0
textfsm_template_dict
A dictionary with the mapping between a command
and the corresponding TextFSM path to use to extract the data.
The TextFSM paths can be specified as in ``textfsm_template``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``napalm_cli_textfsm_template_dict``.
platform_grain_name: ``os``
The name of the grain used to identify the platform name
in the TextFSM index file. Default: ``os``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_grain``.
platform_column_name: ``Platform``
The column name used to identify the platform,
exactly as specified in the TextFSM index file.
Default: ``Platform``.
.. versionadded:: 2018.3.0
.. note::
This is field is case sensitive, make sure
to assign the correct value to this option,
exactly as defined in the index file.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_column_name``.
index_file: ``index``
The name of the TextFSM index file, under the ``textfsm_path``. Default: ``index``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_index_file``.
saltenv: ``base``
Salt fileserver envrionment from which to retrieve the file.
Ignored if ``textfsm_path`` is not a ``salt://`` URL.
.. versionadded:: 2018.3.0
include_empty: ``False``
Include empty files under the ``textfsm_path``.
.. versionadded:: 2018.3.0
include_pat
Glob or regex to narrow down the files cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. versionadded:: 2018.3.0
exclude_pat
Glob or regex to exclude certain files from being cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. versionadded:: 2018.3.0
.. note::
If used with ``include_pat``, files matching this pattern will be
excluded from the subset of files defined by ``include_pat``.
CLI Example:
.. code-block:: bash
salt '*' net.cli "show version" "show chassis fan"
CLI Example with TextFSM template:
.. code-block:: bash
salt '*' net.cli textfsm_parse=True textfsm_path=salt://textfsm/
Example output:
.. code-block:: python
{
'show version and haiku': 'Hostname: re0.edge01.arn01
Model: mx480
Junos: 13.3R6.5
Help me, Obi-Wan
I just saw Episode Two
You're my only hope
',
'show chassis fan' : 'Item Status RPM Measurement
Top Rear Fan OK 3840 Spinning at intermediate-speed
Bottom Rear Fan OK 3840 Spinning at intermediate-speed
Top Middle Fan OK 3900 Spinning at intermediate-speed
Bottom Middle Fan OK 3840 Spinning at intermediate-speed
Top Front Fan OK 3810 Spinning at intermediate-speed
Bottom Front Fan OK 3840 Spinning at intermediate-speed
'
}
Example output with TextFSM parsing:
.. code-block:: json
{
"comment": "",
"result": true,
"out": {
"sh ver": [
{
"kernel": "9.1S3.5",
"documentation": "9.1S3.5",
"boot": "9.1S3.5",
"crypto": "9.1S3.5",
"chassis": "",
"routing": "9.1S3.5",
"base": "9.1S3.5",
"model": "mx960"
}
]
}
}
'''
raw_cli_outputs = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'cli',
**{
'commands': list(commands)
}
)
# thus we can display the output as is
# in case of errors, they'll be catched in the proxy
if not raw_cli_outputs['result']:
# Error -> dispaly the output as-is.
return raw_cli_outputs
textfsm_parse = kwargs.get('textfsm_parse') or __opts__.get('napalm_cli_textfsm_parse') or\
__pillar__.get('napalm_cli_textfsm_parse', False)
if not textfsm_parse:
# No TextFSM parsing required, return raw commands.
log.debug('No TextFSM parsing requested.')
return raw_cli_outputs
if 'textfsm.extract' not in __salt__ or 'textfsm.index' not in __salt__:
raw_cli_outputs['comment'] += 'Unable to process: is TextFSM installed?'
log.error(raw_cli_outputs['comment'])
return raw_cli_outputs
textfsm_template = kwargs.get('textfsm_template')
log.debug('textfsm_template: %s', textfsm_template)
textfsm_path = kwargs.get('textfsm_path') or __opts__.get('textfsm_path') or\
__pillar__.get('textfsm_path')
log.debug('textfsm_path: %s', textfsm_path)
textfsm_template_dict = kwargs.get('textfsm_template_dict') or __opts__.get('napalm_cli_textfsm_template_dict') or\
__pillar__.get('napalm_cli_textfsm_template_dict', {})
log.debug('TextFSM command-template mapping: %s', textfsm_template_dict)
index_file = kwargs.get('index_file') or __opts__.get('textfsm_index_file') or\
__pillar__.get('textfsm_index_file')
log.debug('index_file: %s', index_file)
platform_grain_name = kwargs.get('platform_grain_name') or __opts__.get('textfsm_platform_grain') or\
__pillar__.get('textfsm_platform_grain', 'os')
log.debug('platform_grain_name: %s', platform_grain_name)
platform_column_name = kwargs.get('platform_column_name') or __opts__.get('textfsm_platform_column_name') or\
__pillar__.get('textfsm_platform_column_name', 'Platform')
log.debug('platform_column_name: %s', platform_column_name)
saltenv = kwargs.get('saltenv', 'base')
include_empty = kwargs.get('include_empty', False)
include_pat = kwargs.get('include_pat')
exclude_pat = kwargs.get('exclude_pat')
processed_cli_outputs = {
'comment': raw_cli_outputs.get('comment', ''),
'result': raw_cli_outputs['result'],
'out': {}
}
log.debug('Starting to analyse the raw outputs')
for command in list(commands):
command_output = raw_cli_outputs['out'][command]
log.debug('Output from command: %s', command)
log.debug(command_output)
processed_command_output = None
if textfsm_path:
log.debug('Using the templates under %s', textfsm_path)
processed_cli_output = __salt__['textfsm.index'](command,
platform_grain_name=platform_grain_name,
platform_column_name=platform_column_name,
output=command_output.strip(),
textfsm_path=textfsm_path,
saltenv=saltenv,
include_empty=include_empty,
include_pat=include_pat,
exclude_pat=exclude_pat)
log.debug('Processed CLI output:')
log.debug(processed_cli_output)
if not processed_cli_output['result']:
log.debug('Apparently this didnt work, returnin the raw output')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {0}: {1}.'.format(command,
processed_cli_output['comment'])
log.error(processed_cli_outputs['comment'])
elif processed_cli_output['out']:
log.debug('All good, %s has a nice output!', command)
processed_command_output = processed_cli_output['out']
else:
comment = '''\nProcessing "{}" didn't fail, but didn't return anything either. Dumping raw.'''.format(
command)
processed_cli_outputs['comment'] += comment
log.error(comment)
processed_command_output = command_output
elif textfsm_template or command in textfsm_template_dict:
if command in textfsm_template_dict:
textfsm_template = textfsm_template_dict[command]
log.debug('Using %s to process the command: %s', textfsm_template, command)
processed_cli_output = __salt__['textfsm.extract'](textfsm_template,
raw_text=command_output,
saltenv=saltenv)
log.debug('Processed CLI output:')
log.debug(processed_cli_output)
if not processed_cli_output['result']:
log.debug('Apparently this didnt work, returning '
'the raw output')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {0}: {1}'.format(command,
processed_cli_output['comment'])
log.error(processed_cli_outputs['comment'])
elif processed_cli_output['out']:
log.debug('All good, %s has a nice output!', command)
processed_command_output = processed_cli_output['out']
else:
log.debug('Processing %s didnt fail, but didnt return'
' anything either. Dumping raw.', command)
processed_command_output = command_output
else:
log.error('No TextFSM template specified, or no TextFSM path defined')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {}.'.format(command)
processed_cli_outputs['out'][command] = processed_command_output
processed_cli_outputs['comment'] = processed_cli_outputs['comment'].strip()
return processed_cli_outputs
@salt.utils.napalm.proxy_napalm_wrap
def traceroute(destination, source=None, ttl=None, timeout=None, vrf=None, **kwargs): # pylint: disable=unused-argument
'''
Calls the method traceroute from the NAPALM driver object and returns a dictionary with the result of the traceroute
command executed on the device.
destination
Hostname or address of remote host
source
Source address to use in outgoing traceroute packets
ttl
IP maximum time-to-live value (or IPv6 maximum hop-limit value)
timeout
Number of seconds to wait for response (seconds)
vrf
VRF (routing instance) for traceroute attempt
.. versionadded:: 2016.11.4
CLI Example:
.. code-block:: bash
salt '*' net.traceroute 8.8.8.8
salt '*' net.traceroute 8.8.8.8 source=127.0.0.1 ttl=5 timeout=1
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'traceroute',
**{
'destination': destination,
'source': source,
'ttl': ttl,
'timeout': timeout,
'vrf': vrf
}
)
@salt.utils.napalm.proxy_napalm_wrap
def ping(destination, source=None, ttl=None, timeout=None, size=None, count=None, vrf=None, **kwargs): # pylint: disable=unused-argument
'''
Executes a ping on the network device and returns a dictionary as a result.
destination
Hostname or IP address of remote host
source
Source address of echo request
ttl
IP time-to-live value (IPv6 hop-limit value) (1..255 hops)
timeout
Maximum wait time after sending final packet (seconds)
size
Size of request packets (0..65468 bytes)
count
Number of ping requests to send (1..2000000000 packets)
vrf
VRF (routing instance) for ping attempt
.. versionadded:: 2016.11.4
CLI Example:
.. code-block:: bash
salt '*' net.ping 8.8.8.8
salt '*' net.ping 8.8.8.8 ttl=3 size=65468
salt '*' net.ping 8.8.8.8 source=127.0.0.1 timeout=1 count=100
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'ping',
**{
'destination': destination,
'source': source,
'ttl': ttl,
'timeout': timeout,
'size': size,
'count': count,
'vrf': vrf
}
)
@salt.utils.napalm.proxy_napalm_wrap
def arp(interface='', ipaddr='', macaddr='', **kwargs): # pylint: disable=unused-argument
'''
NAPALM returns a list of dictionaries with details of the ARP entries.
:param interface: interface name to filter on
:param ipaddr: IP address to filter on
:param macaddr: MAC address to filter on
:return: List of the entries in the ARP table
CLI Example:
.. code-block:: bash
salt '*' net.arp
salt '*' net.arp macaddr='5c:5e:ab:da:3c:f0'
Example output:
.. code-block:: python
[
{
'interface' : 'MgmtEth0/RSP0/CPU0/0',
'mac' : '5c:5e:ab:da:3c:f0',
'ip' : '172.17.17.1',
'age' : 1454496274.84
},
{
'interface': 'MgmtEth0/RSP0/CPU0/0',
'mac' : '66:0e:94:96:e0:ff',
'ip' : '172.17.17.2',
'age' : 1435641582.49
}
]
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_arp_table',
**{
}
)
if not proxy_output.get('result'):
return proxy_output
arp_table = proxy_output.get('out')
if interface:
arp_table = _filter_list(arp_table, 'interface', interface)
if ipaddr:
arp_table = _filter_list(arp_table, 'ip', ipaddr)
if macaddr:
arp_table = _filter_list(arp_table, 'mac', macaddr)
proxy_output.update({
'out': arp_table
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def ipaddrs(**kwargs): # pylint: disable=unused-argument
'''
Returns IP addresses configured on the device.
:return: A dictionary with the IPv4 and IPv6 addresses of the interfaces.
Returns all configured IP addresses on all interfaces as a dictionary
of dictionaries. Keys of the main dictionary represent the name of the
interface. Values of the main dictionary represent are dictionaries
that may consist of two keys 'ipv4' and 'ipv6' (one, both or none)
which are themselvs dictionaries with the IP addresses as keys.
CLI Example:
.. code-block:: bash
salt '*' net.ipaddrs
Example output:
.. code-block:: python
{
'FastEthernet8': {
'ipv4': {
'10.66.43.169': {
'prefix_length': 22
}
}
},
'Loopback555': {
'ipv4': {
'192.168.1.1': {
'prefix_length': 24
}
},
'ipv6': {
'1::1': {
'prefix_length': 64
},
'2001:DB8:1::1': {
'prefix_length': 64
},
'FE80::3': {
'prefix_length': 'N/A'
}
}
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_interfaces_ip',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def interfaces(**kwargs): # pylint: disable=unused-argument
'''
Returns details of the interfaces on the device.
:return: Returns a dictionary of dictionaries. The keys for the first
dictionary will be the interfaces in the devices.
CLI Example:
.. code-block:: bash
salt '*' net.interfaces
Example output:
.. code-block:: python
{
'Management1': {
'is_up': False,
'is_enabled': False,
'description': '',
'last_flapped': -1,
'speed': 1000,
'mac_address': 'dead:beef:dead',
},
'Ethernet1':{
'is_up': True,
'is_enabled': True,
'description': 'foo',
'last_flapped': 1429978575.1554043,
'speed': 1000,
'mac_address': 'beef:dead:beef',
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_interfaces',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def lldp(interface='', **kwargs): # pylint: disable=unused-argument
'''
Returns a detailed view of the LLDP neighbors.
:param interface: interface name to filter on
:return: A dictionary with the LLDL neighbors. The keys are the
interfaces with LLDP activated on.
CLI Example:
.. code-block:: bash
salt '*' net.lldp
salt '*' net.lldp interface='TenGigE0/0/0/8'
Example output:
.. code-block:: python
{
'TenGigE0/0/0/8': [
{
'parent_interface': 'Bundle-Ether8',
'interface_description': 'TenGigE0/0/0/8',
'remote_chassis_id': '8c60.4f69.e96c',
'remote_system_name': 'switch',
'remote_port': 'Eth2/2/1',
'remote_port_description': 'Ethernet2/2/1',
'remote_system_description': 'Cisco Nexus Operating System (NX-OS) Software 7.1(0)N1(1a)
TAC support: http://www.cisco.com/tac
Copyright (c) 2002-2015, Cisco Systems, Inc. All rights reserved.',
'remote_system_capab': 'B, R',
'remote_system_enable_capab': 'B'
}
]
}
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_lldp_neighbors_detail',
**{
}
)
if not proxy_output.get('result'):
return proxy_output
lldp_neighbors = proxy_output.get('out')
if interface:
lldp_neighbors = {interface: lldp_neighbors.get(interface)}
proxy_output.update({
'out': lldp_neighbors
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def mac(address='', interface='', vlan=0, **kwargs): # pylint: disable=unused-argument
'''
Returns the MAC Address Table on the device.
:param address: MAC address to filter on
:param interface: Interface name to filter on
:param vlan: VLAN identifier
:return: A list of dictionaries representing the entries in the MAC Address Table
CLI Example:
.. code-block:: bash
salt '*' net.mac
salt '*' net.mac vlan=10
Example output:
.. code-block:: python
[
{
'mac' : '00:1c:58:29:4a:71',
'interface' : 'xe-3/0/2',
'static' : False,
'active' : True,
'moves' : 1,
'vlan' : 10,
'last_move' : 1454417742.58
},
{
'mac' : '8c:60:4f:58:e1:c1',
'interface' : 'xe-1/0/1',
'static' : False,
'active' : True,
'moves' : 2,
'vlan' : 42,
'last_move' : 1453191948.11
}
]
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_mac_address_table',
**{
}
)
if not proxy_output.get('result'):
# if negative, leave the output unchanged
return proxy_output
mac_address_table = proxy_output.get('out')
if vlan and isinstance(vlan, int):
mac_address_table = _filter_list(mac_address_table, 'vlan', vlan)
if address:
mac_address_table = _filter_list(mac_address_table, 'mac', address)
if interface:
mac_address_table = _filter_list(mac_address_table, 'interface', interface)
proxy_output.update({
'out': mac_address_table
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def config(source=None, **kwargs): # pylint: disable=unused-argument
'''
.. versionadded:: 2017.7.0
Return the whole configuration of the network device. By default, it will
return all possible configuration sources supported by the network device.
At most, there will be:
- running config
- startup config
- candidate config
To return only one of the configurations, you can use the ``source``
argument.
source
Which configuration type you want to display, default is all of them.
Options:
- running
- candidate
- startup
:return:
The object returned is a dictionary with the following keys:
- running (string): Representation of the native running configuration.
- candidate (string): Representation of the native candidate configuration.
If the device doesn't differentiate between running and startup
configuration this will an empty string.
- startup (string): Representation of the native startup configuration.
If the device doesn't differentiate between running and startup
configuration this will an empty string.
CLI Example:
.. code-block:: bash
salt '*' net.config
salt '*' net.config source=candidate
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_config',
**{
'retrieve': source
}
)
@salt.utils.napalm.proxy_napalm_wrap
def optics(**kwargs): # pylint: disable=unused-argument
'''
.. versionadded:: 2017.7.0
Fetches the power usage on the various transceivers installed
on the network device (in dBm), and returns a view that conforms with the
OpenConfig model openconfig-platform-transceiver.yang.
:return:
Returns a dictionary where the keys are as listed below:
* intf_name (unicode)
* physical_channels
* channels (list of dicts)
* index (int)
* state
* input_power
* instant (float)
* avg (float)
* min (float)
* max (float)
* output_power
* instant (float)
* avg (float)
* min (float)
* max (float)
* laser_bias_current
* instant (float)
* avg (float)
* min (float)
* max (float)
CLI Example:
.. code-block:: bash
salt '*' net.optics
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_optics',
**{
}
)
# <---- Call NAPALM getters --------------------------------------------------------------------------------------------
# ----- Configuration specific functions ------------------------------------------------------------------------------>
@salt.utils.napalm.proxy_napalm_wrap
def load_config(filename=None,
text=None,
test=False,
commit=True,
debug=False,
replace=False,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
commit_jid=None,
inherit_napalm_device=None,
saltenv='base',
**kwargs): # pylint: disable=unused-argument
'''
Applies configuration changes on the device. It can be loaded from a file or from inline string.
If you send both a filename and a string containing the configuration, the file has higher precedence.
By default this function will commit the changes. If there are no changes, it does not commit and
the flag ``already_configured`` will be set as ``True`` to point this out.
To avoid committing the configuration, set the argument ``test`` to ``True`` and will discard (dry run).
To keep the changes but not commit, set ``commit`` to ``False``.
To replace the config, set ``replace`` to ``True``.
filename
Path to the file containing the desired configuration.
This can be specified using the absolute path to the file,
or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
.. versionchanged:: 2018.3.0
text
String containing the desired configuration.
This argument is ignored when ``filename`` is specified.
test: False
Dry run? If set as ``True``, will apply the config, discard and return the changes. Default: ``False``
and will commit the changes on the device.
commit: True
Commit? Default: ``True``.
debug: False
Debug mode. Will insert a new key under the output dictionary, as ``loaded_config`` containing the raw
configuration loaded on the device.
.. versionadded:: 2016.11.2
replace: False
Load and replace the configuration. Default: ``False``.
.. versionadded:: 2016.11.2
commit_in: ``None``
Commit the changes in a specific number of minutes / hours. Example of
accepted formats: ``5`` (commit in 5 minutes), ``2m`` (commit in 2
minutes), ``1h`` (commit the changes in 1 hour)`, ``5h30m`` (commit
the changes in 5 hours and 30 minutes).
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
commit_at: ``None``
Commit the changes at a specific time. Example of accepted formats:
``1am`` (will commit the changes at the next 1AM), ``13:20`` (will
commit at 13:20), ``1:20am``, etc.
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
revert_in: ``None``
Commit and revert the changes in a specific number of minutes / hours.
Example of accepted formats: ``5`` (revert in 5 minutes), ``2m`` (revert
in 2 minutes), ``1h`` (revert the changes in 1 hour)`, ``5h30m`` (revert
the changes in 5 hours and 30 minutes).
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
revert_at: ``None``
Commit and revert the changes at a specific time. Example of accepted
formats: ``1am`` (will commit and revert the changes at the next 1AM),
``13:20`` (will commit and revert at 13:20), ``1:20am``, etc.
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
saltenv: ``base``
Specifies the Salt environment name.
.. versionadded:: 2018.3.0
:return: a dictionary having the following keys:
* result (bool): if the config was applied successfully. It is ``False`` only in case of failure. In case \
there are no changes to be applied and successfully performs all operations it is still ``True`` and so will be \
the ``already_configured`` flag (example below)
* comment (str): a message for the user
* already_configured (bool): flag to check if there were no changes applied
* loaded_config (str): the configuration loaded on the device. Requires ``debug`` to be set as ``True``
* diff (str): returns the config changes applied
CLI Example:
.. code-block:: bash
salt '*' net.load_config text='ntp peer 192.168.0.1'
salt '*' net.load_config filename='/absolute/path/to/your/file'
salt '*' net.load_config filename='/absolute/path/to/your/file' test=True
salt '*' net.load_config filename='/absolute/path/to/your/file' commit=False
Example output:
.. code-block:: python
{
'comment': 'Configuration discarded.',
'already_configured': False,
'result': True,
'diff': '[edit interfaces xe-0/0/5]+ description "Adding a description";'
}
'''
fun = 'load_merge_candidate'
if replace:
fun = 'load_replace_candidate'
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
if filename:
text = __salt__['cp.get_file_str'](filename, saltenv=saltenv)
if text is False:
# When using salt:// or https://, if the resource is not available,
# it will either raise an exception, or return False.
ret = {
'result': False,
'out': None
}
ret['comment'] = 'Unable to read from {}. Please specify a valid file or text.'.format(filename)
log.error(ret['comment'])
return ret
if commit_jid:
# When the commit_jid argument is passed, it probably is a scheduled
# commit to be executed, and filename is a temporary file which
# can be removed after reading it.
salt.utils.files.safe_rm(filename)
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
fun,
**{
'config': text
}
)
return _config_logic(napalm_device, # pylint: disable=undefined-variable
_loaded,
test=test,
debug=debug,
replace=replace,
commit_config=commit,
loaded_config=text,
commit_at=commit_at,
commit_in=commit_in,
revert_in=revert_in,
revert_at=revert_at,
commit_jid=commit_jid,
**kwargs)
@salt.utils.napalm.proxy_napalm_wrap
def load_template(template_name=None,
template_source=None,
context=None,
defaults=None,
template_engine='jinja',
saltenv='base',
template_hash=None,
template_hash_name=None,
skip_verify=False,
test=False,
commit=True,
debug=False,
replace=False,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
inherit_napalm_device=None, # pylint: disable=unused-argument
**template_vars):
'''
Renders a configuration template (default: Jinja) and loads the result on the device.
By default this function will commit the changes. If there are no changes,
it does not commit, discards he config and the flag ``already_configured``
will be set as ``True`` to point this out.
To avoid committing the configuration, set the argument ``test`` to ``True``
and will discard (dry run).
To preserve the changes, set ``commit`` to ``False``.
However, this is recommended to be used only in exceptional cases
when there are applied few consecutive states
and/or configuration changes.
Otherwise the user might forget that the config DB is locked
and the candidate config buffer is not cleared/merged in the running config.
To replace the config, set ``replace`` to ``True``.
template_name
Identifies path to the template source.
The template can be either stored on the local machine, either remotely.
The recommended location is under the ``file_roots``
as specified in the master config file.
For example, let's suppose the ``file_roots`` is configured as:
.. code-block:: yaml
file_roots:
base:
- /etc/salt/states
Placing the template under ``/etc/salt/states/templates/example.jinja``,
it can be used as ``salt://templates/example.jinja``.
Alternatively, for local files, the user can specify the absolute path.
If remotely, the source can be retrieved via ``http``, ``https`` or ``ftp``.
Examples:
- ``salt://my_template.jinja``
- ``/absolute/path/to/my_template.jinja``
- ``http://example.com/template.cheetah``
- ``https:/example.com/template.mako``
- ``ftp://example.com/template.py``
.. versionchanged:: 2019.2.0
This argument can now support a list of templates to be rendered.
The resulting configuration text is loaded at once, as a single
configuration chunk.
template_source: None
Inline config template to be rendered and loaded on the device.
template_hash: None
Hash of the template file. Format: ``{hash_type: 'md5', 'hsum': <md5sum>}``
.. versionadded:: 2016.11.2
context: None
Overrides default context variables passed to the template.
.. versionadded:: 2019.2.0
template_hash_name: None
When ``template_hash`` refers to a remote file,
this specifies the filename to look for in that file.
.. versionadded:: 2016.11.2
saltenv: ``base``
Specifies the template environment.
This will influence the relative imports inside the templates.
.. versionadded:: 2016.11.2
template_engine: jinja
The following templates engines are supported:
- :mod:`cheetah<salt.renderers.cheetah>`
- :mod:`genshi<salt.renderers.genshi>`
- :mod:`jinja<salt.renderers.jinja>`
- :mod:`mako<salt.renderers.mako>`
- :mod:`py<salt.renderers.py>`
- :mod:`wempy<salt.renderers.wempy>`
.. versionadded:: 2016.11.2
skip_verify: True
If ``True``, hash verification of remote file sources
(``http://``, ``https://``, ``ftp://``) will be skipped,
and the ``source_hash`` argument will be ignored.
.. versionadded:: 2016.11.2
test: False
Dry run? If set to ``True``, will apply the config,
discard and return the changes.
Default: ``False`` and will commit the changes on the device.
commit: True
Commit? (default: ``True``)
debug: False
Debug mode. Will insert a new key under the output dictionary,
as ``loaded_config`` containing the raw result after the template was rendered.
.. versionadded:: 2016.11.2
replace: False
Load and replace the configuration.
.. versionadded:: 2016.11.2
commit_in: ``None``
Commit the changes in a specific number of minutes / hours. Example of
accepted formats: ``5`` (commit in 5 minutes), ``2m`` (commit in 2
minutes), ``1h`` (commit the changes in 1 hour)`, ``5h30m`` (commit
the changes in 5 hours and 30 minutes).
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
commit_at: ``None``
Commit the changes at a specific time. Example of accepted formats:
``1am`` (will commit the changes at the next 1AM), ``13:20`` (will
commit at 13:20), ``1:20am``, etc.
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
revert_in: ``None``
Commit and revert the changes in a specific number of minutes / hours.
Example of accepted formats: ``5`` (revert in 5 minutes), ``2m`` (revert
in 2 minutes), ``1h`` (revert the changes in 1 hour)`, ``5h30m`` (revert
the changes in 5 hours and 30 minutes).
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
revert_at: ``None``
Commit and revert the changes at a specific time. Example of accepted
formats: ``1am`` (will commit and revert the changes at the next 1AM),
``13:20`` (will commit and revert at 13:20), ``1:20am``, etc.
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
defaults: None
Default variables/context passed to the template.
.. versionadded:: 2016.11.2
template_vars
Dictionary with the arguments/context to be used when the template is rendered.
.. note::
Do not explicitly specify this argument. This represents any other
variable that will be sent to the template rendering system.
Please see the examples below!
.. note::
It is more recommended to use the ``context`` argument to avoid
conflicts between CLI arguments and template variables.
:return: a dictionary having the following keys:
- result (bool): if the config was applied successfully. It is ``False``
only in case of failure. In case there are no changes to be applied and
successfully performs all operations it is still ``True`` and so will be
the ``already_configured`` flag (example below)
- comment (str): a message for the user
- already_configured (bool): flag to check if there were no changes applied
- loaded_config (str): the configuration loaded on the device, after
rendering the template. Requires ``debug`` to be set as ``True``
- diff (str): returns the config changes applied
The template can use variables from the ``grains``, ``pillar`` or ``opts``, for example:
.. code-block:: jinja
{% set router_model = grains.get('model') -%}
{% set router_vendor = grains.get('vendor') -%}
{% set os_version = grains.get('version') -%}
{% set hostname = pillar.get('proxy', {}).get('host') -%}
{% if router_vendor|lower == 'juniper' %}
system {
host-name {{hostname}};
}
{% elif router_vendor|lower == 'cisco' %}
hostname {{hostname}}
{% endif %}
CLI Examples:
.. code-block:: bash
salt '*' net.load_template set_ntp_peers peers=[192.168.0.1] # uses NAPALM default templates
# inline template:
salt -G 'os:junos' net.load_template template_source='system { host-name {{host_name}}; }' \
host_name='MX480.lab'
# inline template using grains info:
salt -G 'os:junos' net.load_template \
template_source='system { host-name {{grains.model}}.lab; }'
# if the device is a MX480, the command above will set the hostname as: MX480.lab
# inline template using pillar data:
salt -G 'os:junos' net.load_template template_source='system { host-name {{pillar.proxy.host}}; }'
salt '*' net.load_template https://bit.ly/2OhSgqP hostname=example # will commit
salt '*' net.load_template https://bit.ly/2OhSgqP hostname=example test=True # dry run
salt '*' net.load_template salt://templates/example.jinja debug=True # Using the salt:// URI
# render a mako template:
salt '*' net.load_template salt://templates/example.mako template_engine=mako debug=True
# render remote template
salt -G 'os:junos' net.load_template http://bit.ly/2fReJg7 test=True debug=True peers=['192.168.0.1']
salt -G 'os:ios' net.load_template http://bit.ly/2gKOj20 test=True debug=True peers=['192.168.0.1']
# render multiple templates at once
salt '*' net.load_template "['https://bit.ly/2OhSgqP', 'salt://templates/example.jinja']" context="{'hostname': 'example'}"
Example output:
.. code-block:: python
{
'comment': '',
'already_configured': False,
'result': True,
'diff': '[edit system]+ host-name edge01.bjm01',
'loaded_config': 'system { host-name edge01.bjm01; }''
}
'''
_rendered = ''
_loaded = {
'result': True,
'comment': '',
'out': None
}
loaded_config = None
# prechecks
deprecated_args = ('template_user', 'template_attrs', 'template_group', 'template_mode')
for deprecated_arg in deprecated_args:
if template_vars.get(deprecated_arg):
del template_vars[deprecated_arg]
salt.utils.versions.warn_until(
'Sodium',
('The \'{arg}\' argument to \'net.load_template\' is deprecated '
'and has been ignored').format(arg=deprecated_arg)
)
if template_engine not in salt.utils.templates.TEMPLATE_REGISTRY:
_loaded.update({
'result': False,
'comment': 'Invalid templating engine! Choose between: {tpl_eng_opts}'.format(
tpl_eng_opts=', '.join(list(salt.utils.templates.TEMPLATE_REGISTRY.keys()))
)
})
return _loaded # exit
# to check if will be rendered by salt or NAPALM
salt_render_prefixes = ('salt://', 'http://', 'https://', 'ftp://')
salt_render = False
file_exists = False
if not isinstance(template_name, (tuple, list)):
for salt_render_prefix in salt_render_prefixes:
if not salt_render:
salt_render = salt_render or template_name.startswith(salt_render_prefix)
file_exists = __salt__['file.file_exists'](template_name)
if template_source or file_exists or salt_render or isinstance(template_name, (tuple, list)):
# either inline template
# either template in a custom path
# either abs path send
# either starts with salt:// and
# then use Salt render system
if context is None:
context = {}
context.update(template_vars)
# if needed to render the template send as inline arg
if template_source:
# render the content
_rendered = __salt__['file.apply_template_on_contents'](
contents=template_source,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv
)
if not isinstance(_rendered, six.string_types):
if 'result' in _rendered:
_loaded['result'] = _rendered['result']
else:
_loaded['result'] = False
if 'comment' in _rendered:
_loaded['comment'] = _rendered['comment']
else:
_loaded['comment'] = 'Error while rendering the template.'
return _loaded
else:
# render the file - either local, either remote
if not isinstance(template_name, (list, tuple)):
template_name = [template_name]
if template_hash_name and not isinstance(template_hash_name, (list, tuple)):
template_hash_name = [template_hash_name]
elif not template_hash_name:
template_hash_name = [None] * len(template_name)
if template_hash and isinstance(template_hash, six.string_types) and not\
(template_hash.startswith('salt://') or template_hash.startswith('file://')):
# If the template hash is passed as string, and it's not a file
# (starts with the salt:// or file:// URI), then make it a list
# of 1 element (for the iteration below)
template_hash = [template_hash]
elif template_hash and isinstance(template_hash, six.string_types) and\
(template_hash.startswith('salt://') or template_hash.startswith('file://')):
# If the template hash is a file URI, then provide the same value
# for each of the templates in the list, as probably they all
# share the same hash file, otherwise the user should provide
# this as a list
template_hash = [template_hash] * len(template_name)
elif not template_hash:
template_hash = [None] * len(template_name)
for tpl_index, tpl_name in enumerate(template_name):
tpl_hash = template_hash[tpl_index]
tpl_hash_name = template_hash_name[tpl_index]
_rand_filename = __salt__['random.hash'](tpl_name, 'md5')
_temp_file = __salt__['file.join']('/tmp', _rand_filename)
_managed = __salt__['file.get_managed'](name=_temp_file,
source=tpl_name,
source_hash=tpl_hash,
source_hash_name=tpl_hash_name,
user=None,
group=None,
mode=None,
attrs=None,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv,
skip_verify=skip_verify)
if not isinstance(_managed, (list, tuple)) and isinstance(_managed, six.string_types):
_loaded['comment'] += _managed
_loaded['result'] = False
elif isinstance(_managed, (list, tuple)) and not _managed:
_loaded['result'] = False
_loaded['comment'] += 'Error while rendering the template.'
elif isinstance(_managed, (list, tuple)) and not _managed[0]:
_loaded['result'] = False
_loaded['comment'] += _managed[-1] # contains the error message
if _loaded['result']: # all good
_temp_tpl_file = _managed[0]
_temp_tpl_file_exists = __salt__['file.file_exists'](_temp_tpl_file)
if not _temp_tpl_file_exists:
_loaded['result'] = False
_loaded['comment'] += 'Error while rendering the template.'
return _loaded
_rendered += __salt__['file.read'](_temp_tpl_file)
__salt__['file.remove'](_temp_tpl_file)
else:
return _loaded # exit
loaded_config = _rendered
if _loaded['result']: # all good
fun = 'load_merge_candidate'
if replace: # replace requested
fun = 'load_replace_candidate'
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
fun,
**{
'config': _rendered
}
)
else:
salt.utils.versions.warn_until(
'Sodium',
'Native NAPALM templates support will be removed in the Sodium '
'release. Please consider using the Salt rendering pipeline instead.'
'If you are using the \'netntp\', \'netsnmp\', or \'netusers\' Salt '
'State modules, you can ignore this message'
)
# otherwise, use NAPALM render system, injecting pillar/grains/opts vars
load_templates_params = defaults if defaults else {}
load_templates_params.update(template_vars)
load_templates_params.update(
{
'template_name': template_name,
'template_source': template_source, # inline template
'pillar': __pillar__, # inject pillar content
'grains': __grains__, # inject grains content
'opts': __opts__ # inject opts content
}
)
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
# so we'll set the CLOSE global explicitly as False
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'load_template',
**load_templates_params
)
return _config_logic(napalm_device, # pylint: disable=undefined-variable
_loaded,
test=test,
debug=debug,
replace=replace,
commit_config=commit,
loaded_config=loaded_config,
commit_at=commit_at,
commit_in=commit_in,
revert_in=revert_in,
revert_at=revert_at,
**template_vars)
@salt.utils.napalm.proxy_napalm_wrap
def commit(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Commits the configuration changes made on the network device.
CLI Example:
.. code-block:: bash
salt '*' net.commit
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'commit_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def discard_config(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
"""
Discards the changes applied.
CLI Example:
.. code-block:: bash
salt '*' net.discard_config
"""
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'discard_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def compare_config(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Returns the difference between the running config and the candidate config.
CLI Example:
.. code-block:: bash
salt '*' net.compare_config
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'compare_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def rollback(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Rollbacks the configuration.
CLI Example:
.. code-block:: bash
salt '*' net.rollback
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'rollback',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def config_changed(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Will prompt if the configuration has been changed.
:return: A tuple with a boolean that specifies if the config was changed on the device.\
And a string that provides more details of the reason why the configuration was not changed.
CLI Example:
.. code-block:: bash
salt '*' net.config_changed
'''
is_config_changed = False
reason = ''
try_compare = compare_config(inherit_napalm_device=napalm_device) # pylint: disable=undefined-variable
if try_compare.get('result'):
if try_compare.get('out'):
is_config_changed = True
else:
reason = 'Configuration was not changed on the device.'
else:
reason = try_compare.get('comment')
return is_config_changed, reason
@salt.utils.napalm.proxy_napalm_wrap
def config_control(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Will check if the configuration was changed.
If differences found, will try to commit.
In case commit unsuccessful, will try to rollback.
:return: A tuple with a boolean that specifies if the config was changed/committed/rollbacked on the device.\
And a string that provides more details of the reason why the configuration was not committed properly.
CLI Example:
.. code-block:: bash
salt '*' net.config_control
'''
result = True
comment = ''
changed, not_changed_rsn = config_changed(inherit_napalm_device=napalm_device) # pylint: disable=undefined-variable
if not changed:
return (changed, not_changed_rsn)
# config changed, thus let's try to commit
try_commit = commit()
if not try_commit.get('result'):
result = False
comment = 'Unable to commit the changes: {reason}.\n\
Will try to rollback now!'.format(
reason=try_commit.get('comment')
)
try_rollback = rollback()
if not try_rollback.get('result'):
comment += '\nCannot rollback! {reason}'.format(
reason=try_rollback.get('comment')
)
return result, comment
def cancel_commit(jid):
'''
.. versionadded:: 2019.2.0
Cancel a commit scheduled to be executed via the ``commit_in`` and
``commit_at`` arguments from the
:py:func:`net.load_template <salt.modules.napalm_network.load_template>` or
:py:func:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit ID is displayed when the commit is scheduled
via the functions named above.
CLI Example:
.. code-block:: bash
salt '*' net.cancel_commit 20180726083540640360
'''
job_name = '__napalm_commit_{}'.format(jid)
removed = __salt__['schedule.delete'](job_name)
if removed['result']:
saved = __salt__['schedule.save']()
removed['comment'] = 'Commit #{jid} cancelled.'.format(jid=jid)
else:
removed['comment'] = 'Unable to find commit #{jid}.'.format(jid=jid)
return removed
def confirm_commit(jid):
'''
.. versionadded:: 2019.2.0
Confirm a commit scheduled to be reverted via the ``revert_in`` and
``revert_at`` arguments from the
:mod:`net.load_template <salt.modules.napalm_network.load_template>` or
:mod:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit ID is displayed when the commit confirmed
is scheduled via the functions named above.
CLI Example:
.. code-block:: bash
salt '*' net.confirm_commit 20180726083540640360
'''
if __grains__['os'] == 'junos':
# Confirm the commit, by committing (i.e., invoking the RPC call)
confirmed = __salt__['napalm.junos_commit']()
confirmed['result'] = confirmed.pop('out')
confirmed['comment'] = confirmed.pop('message')
else:
confirmed = cancel_commit(jid)
if confirmed['result']:
confirmed['comment'] = 'Commit #{jid} confirmed.'.format(jid=jid)
return confirmed
def save_config(source=None,
path=None):
'''
.. versionadded:: 2019.2.0
Save the configuration to a file on the local file system.
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``,
``startup``. Default: ``running``.
path
Absolute path to file where to save the configuration.
To push the files to the Master, use
:mod:`cp.push <salt.modules.cp.push>` Execution function.
CLI Example:
.. code-block:: bash
salt '*' net.save_config source=running
'''
if not source:
source = 'running'
if not path:
path = salt.utils.files.mkstemp()
running_config = __salt__['net.config'](source=source)
if not running_config or not running_config['result']:
log.error('Unable to retrieve the config')
return running_config
with salt.utils.files.fopen(path, 'w') as fh_:
fh_.write(running_config['out'][source])
return {
'result': True,
'out': path,
'comment': '{source} config saved to {path}'.format(source=source, path=path)
}
def replace_pattern(pattern,
repl,
count=0,
flags=8,
bufsize=1,
append_if_not_found=False,
prepend_if_not_found=False,
not_found_content=None,
search_only=False,
show_changes=True,
backslash_literal=False,
source=None,
path=None,
test=False,
replace=True,
debug=False,
commit=True):
'''
.. versionadded:: 2019.2.0
Replace occurrences of a pattern in the configuration source. If
``show_changes`` is ``True``, then a diff of what changed will be returned,
otherwise a ``True`` will be returned when changes are made, and ``False``
when no changes are made.
This is a pure Python implementation that wraps Python's :py:func:`~re.sub`.
pattern
A regular expression, to be matched using Python's
:py:func:`~re.search`.
repl
The replacement text.
count: ``0``
Maximum number of pattern occurrences to be replaced. If count is a
positive integer ``n``, only ``n`` occurrences will be replaced,
otherwise all occurrences will be replaced.
flags (list or int): ``8``
A list of flags defined in the ``re`` module documentation from the
Python standard library. Each list item should be a string that will
correlate to the human-friendly flag name. E.g., ``['IGNORECASE',
'MULTILINE']``. Optionally, ``flags`` may be an int, with a value
corresponding to the XOR (``|``) of all the desired flags. Defaults to
8 (which supports 'MULTILINE').
bufsize (int or str): ``1``
How much of the configuration to buffer into memory at once. The
default value ``1`` processes one line at a time. The special value
``file`` may be specified which will read the entire file into memory
before processing.
append_if_not_found: ``False``
If set to ``True``, and pattern is not found, then the content will be
appended to the file.
prepend_if_not_found: ``False``
If set to ``True`` and pattern is not found, then the content will be
prepended to the file.
not_found_content
Content to use for append/prepend if not found. If None (default), uses
``repl``. Useful when ``repl`` uses references to group in pattern.
search_only: ``False``
If set to true, this no changes will be performed on the file, and this
function will simply return ``True`` if the pattern was matched, and
``False`` if not.
show_changes: ``True``
If ``True``, return a diff of changes made. Otherwise, return ``True``
if changes were made, and ``False`` if not.
backslash_literal: ``False``
Interpret backslashes as literal backslashes for the repl and not
escape characters. This will help when using append/prepend so that
the backslashes are not interpreted for the repl on the second run of
the state.
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path
Save the temporary configuration to a specific path, then read from
there.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' net.replace_pattern "bind-address\\s*=" "bind-address:"
CLI Example:
.. code-block:: bash
salt '*' net.replace_pattern PREFIX-LIST_NAME new-prefix-list-name
salt '*' net.replace_pattern bgp-group-name new-bgp-group-name count=1
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
replace_pattern = __salt__['file.replace'](path,
pattern,
repl,
count=count,
flags=flags,
bufsize=bufsize,
append_if_not_found=append_if_not_found,
prepend_if_not_found=prepend_if_not_found,
not_found_content=not_found_content,
search_only=search_only,
show_changes=show_changes,
backslash_literal=backslash_literal)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
def blockreplace(marker_start,
marker_end,
content='',
append_if_not_found=False,
prepend_if_not_found=False,
show_changes=True,
append_newline=False,
source='running',
path=None,
test=False,
commit=True,
debug=False,
replace=True):
'''
.. versionadded:: 2019.2.0
Replace content of the configuration source, delimited by the line markers.
A block of content delimited by comments can help you manage several lines
without worrying about old entries removal.
marker_start
The line content identifying a line as the start of the content block.
Note that the whole line containing this marker will be considered,
so whitespace or extra content before or after the marker is included
in final output.
marker_end
The line content identifying a line as the end of the content block.
Note that the whole line containing this marker will be considered,
so whitespace or extra content before or after the marker is included
in final output.
content
The content to be used between the two lines identified by
``marker_start`` and ``marker_stop``.
append_if_not_found: ``False``
If markers are not found and set to True then, the markers and content
will be appended to the file.
prepend_if_not_found: ``False``
If markers are not found and set to True then, the markers and content
will be prepended to the file.
append_newline: ``False``
Controls whether or not a newline is appended to the content block.
If the value of this argument is ``True`` then a newline will be added
to the content block. If it is ``False``, then a newline will not be
added to the content block. If it is ``None`` then a newline will only
be added to the content block if it does not already end in a newline.
show_changes: ``True``
Controls how changes are presented. If ``True``, this function will
return the of the changes made.
If ``False``, then it will return a boolean (``True`` if any changes
were made, otherwise False).
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path: ``None``
Save the temporary configuration to a specific path, then read from
there. This argument is optional, can be used when you prefers a
particular location of the temporary file.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
CLI Example:
.. code-block:: bash
salt '*' net.blockreplace 'ntp' 'interface' ''
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
replace_pattern = __salt__['file.blockreplace'](path,
marker_start=marker_start,
marker_end=marker_end,
content=content,
append_if_not_found=append_if_not_found,
prepend_if_not_found=prepend_if_not_found,
show_changes=show_changes,
append_newline=append_newline)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
def patch(patchfile,
options='',
saltenv='base',
source_hash=None,
show_changes=True,
source='running',
path=None,
test=False,
commit=True,
debug=False,
replace=True):
'''
.. versionadded:: 2019.2.0
Apply a patch to the configuration source, and load the result into the
running config of the device.
patchfile
A patch file to apply to the configuration source.
options
Options to pass to patch.
source_hash
If the patch file (specified via the ``patchfile`` argument) is an
HTTP(S) or FTP URL and the file exists in the minion's file cache, this
option can be passed to keep the minion from re-downloading the file if
the cached copy matches the specified hash.
show_changes: ``True``
Controls how changes are presented. If ``True``, this function will
return the of the changes made.
If ``False``, then it will return a boolean (``True`` if any changes
were made, otherwise False).
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path: ``None``
Save the temporary configuration to a specific path, then read from
there. This argument is optional, can the user prefers a particular
location of the temporary file.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
CLI Example:
.. code-block:: bash
salt '*' net.patch https://example.com/running_config.patch
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
patchfile_cache = __salt__['cp.cache_file'](patchfile)
if patchfile_cache is False:
return {
'out': None,
'result': False,
'comment': 'The file "{}" does not exist.'.format(patchfile)
}
replace_pattern = __salt__['file.patch'](path,
patchfile_cache,
options=options)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
# <---- Configuration specific functions -------------------------------------------------------------------------------
|
saltstack/salt
|
salt/modules/napalm_network.py
|
cli
|
python
|
def cli(*commands, **kwargs): # pylint: disable=unused-argument
'''
Returns a dictionary with the raw output of all commands passed as arguments.
commands
List of commands to be executed on the device.
textfsm_parse: ``False``
Try parsing the outputs using the TextFSM templates.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``napalm_cli_textfsm_parse``.
textfsm_path
The path where the TextFSM templates can be found. This option implies
the usage of the TextFSM index file.
``textfsm_path`` can be either absolute path on the server,
either specified using the following URL mschemes: ``file://``,
``salt://``, ``http://``, ``https://``, ``ftp://``,
``s3://``, ``swift://``.
.. versionadded:: 2018.3.0
.. note::
This needs to be a directory with a flat structure, having an
index file (whose name can be specified using the ``index_file`` option)
and a number of TextFSM templates.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_path``.
textfsm_template
The path to a certain the TextFSM template.
This can be specified using the absolute path
to the file, or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
.. versionadded:: 2018.3.0
textfsm_template_dict
A dictionary with the mapping between a command
and the corresponding TextFSM path to use to extract the data.
The TextFSM paths can be specified as in ``textfsm_template``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``napalm_cli_textfsm_template_dict``.
platform_grain_name: ``os``
The name of the grain used to identify the platform name
in the TextFSM index file. Default: ``os``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_grain``.
platform_column_name: ``Platform``
The column name used to identify the platform,
exactly as specified in the TextFSM index file.
Default: ``Platform``.
.. versionadded:: 2018.3.0
.. note::
This is field is case sensitive, make sure
to assign the correct value to this option,
exactly as defined in the index file.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_column_name``.
index_file: ``index``
The name of the TextFSM index file, under the ``textfsm_path``. Default: ``index``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_index_file``.
saltenv: ``base``
Salt fileserver envrionment from which to retrieve the file.
Ignored if ``textfsm_path`` is not a ``salt://`` URL.
.. versionadded:: 2018.3.0
include_empty: ``False``
Include empty files under the ``textfsm_path``.
.. versionadded:: 2018.3.0
include_pat
Glob or regex to narrow down the files cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. versionadded:: 2018.3.0
exclude_pat
Glob or regex to exclude certain files from being cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. versionadded:: 2018.3.0
.. note::
If used with ``include_pat``, files matching this pattern will be
excluded from the subset of files defined by ``include_pat``.
CLI Example:
.. code-block:: bash
salt '*' net.cli "show version" "show chassis fan"
CLI Example with TextFSM template:
.. code-block:: bash
salt '*' net.cli textfsm_parse=True textfsm_path=salt://textfsm/
Example output:
.. code-block:: python
{
'show version and haiku': 'Hostname: re0.edge01.arn01
Model: mx480
Junos: 13.3R6.5
Help me, Obi-Wan
I just saw Episode Two
You're my only hope
',
'show chassis fan' : 'Item Status RPM Measurement
Top Rear Fan OK 3840 Spinning at intermediate-speed
Bottom Rear Fan OK 3840 Spinning at intermediate-speed
Top Middle Fan OK 3900 Spinning at intermediate-speed
Bottom Middle Fan OK 3840 Spinning at intermediate-speed
Top Front Fan OK 3810 Spinning at intermediate-speed
Bottom Front Fan OK 3840 Spinning at intermediate-speed
'
}
Example output with TextFSM parsing:
.. code-block:: json
{
"comment": "",
"result": true,
"out": {
"sh ver": [
{
"kernel": "9.1S3.5",
"documentation": "9.1S3.5",
"boot": "9.1S3.5",
"crypto": "9.1S3.5",
"chassis": "",
"routing": "9.1S3.5",
"base": "9.1S3.5",
"model": "mx960"
}
]
}
}
'''
raw_cli_outputs = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'cli',
**{
'commands': list(commands)
}
)
# thus we can display the output as is
# in case of errors, they'll be catched in the proxy
if not raw_cli_outputs['result']:
# Error -> dispaly the output as-is.
return raw_cli_outputs
textfsm_parse = kwargs.get('textfsm_parse') or __opts__.get('napalm_cli_textfsm_parse') or\
__pillar__.get('napalm_cli_textfsm_parse', False)
if not textfsm_parse:
# No TextFSM parsing required, return raw commands.
log.debug('No TextFSM parsing requested.')
return raw_cli_outputs
if 'textfsm.extract' not in __salt__ or 'textfsm.index' not in __salt__:
raw_cli_outputs['comment'] += 'Unable to process: is TextFSM installed?'
log.error(raw_cli_outputs['comment'])
return raw_cli_outputs
textfsm_template = kwargs.get('textfsm_template')
log.debug('textfsm_template: %s', textfsm_template)
textfsm_path = kwargs.get('textfsm_path') or __opts__.get('textfsm_path') or\
__pillar__.get('textfsm_path')
log.debug('textfsm_path: %s', textfsm_path)
textfsm_template_dict = kwargs.get('textfsm_template_dict') or __opts__.get('napalm_cli_textfsm_template_dict') or\
__pillar__.get('napalm_cli_textfsm_template_dict', {})
log.debug('TextFSM command-template mapping: %s', textfsm_template_dict)
index_file = kwargs.get('index_file') or __opts__.get('textfsm_index_file') or\
__pillar__.get('textfsm_index_file')
log.debug('index_file: %s', index_file)
platform_grain_name = kwargs.get('platform_grain_name') or __opts__.get('textfsm_platform_grain') or\
__pillar__.get('textfsm_platform_grain', 'os')
log.debug('platform_grain_name: %s', platform_grain_name)
platform_column_name = kwargs.get('platform_column_name') or __opts__.get('textfsm_platform_column_name') or\
__pillar__.get('textfsm_platform_column_name', 'Platform')
log.debug('platform_column_name: %s', platform_column_name)
saltenv = kwargs.get('saltenv', 'base')
include_empty = kwargs.get('include_empty', False)
include_pat = kwargs.get('include_pat')
exclude_pat = kwargs.get('exclude_pat')
processed_cli_outputs = {
'comment': raw_cli_outputs.get('comment', ''),
'result': raw_cli_outputs['result'],
'out': {}
}
log.debug('Starting to analyse the raw outputs')
for command in list(commands):
command_output = raw_cli_outputs['out'][command]
log.debug('Output from command: %s', command)
log.debug(command_output)
processed_command_output = None
if textfsm_path:
log.debug('Using the templates under %s', textfsm_path)
processed_cli_output = __salt__['textfsm.index'](command,
platform_grain_name=platform_grain_name,
platform_column_name=platform_column_name,
output=command_output.strip(),
textfsm_path=textfsm_path,
saltenv=saltenv,
include_empty=include_empty,
include_pat=include_pat,
exclude_pat=exclude_pat)
log.debug('Processed CLI output:')
log.debug(processed_cli_output)
if not processed_cli_output['result']:
log.debug('Apparently this didnt work, returnin the raw output')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {0}: {1}.'.format(command,
processed_cli_output['comment'])
log.error(processed_cli_outputs['comment'])
elif processed_cli_output['out']:
log.debug('All good, %s has a nice output!', command)
processed_command_output = processed_cli_output['out']
else:
comment = '''\nProcessing "{}" didn't fail, but didn't return anything either. Dumping raw.'''.format(
command)
processed_cli_outputs['comment'] += comment
log.error(comment)
processed_command_output = command_output
elif textfsm_template or command in textfsm_template_dict:
if command in textfsm_template_dict:
textfsm_template = textfsm_template_dict[command]
log.debug('Using %s to process the command: %s', textfsm_template, command)
processed_cli_output = __salt__['textfsm.extract'](textfsm_template,
raw_text=command_output,
saltenv=saltenv)
log.debug('Processed CLI output:')
log.debug(processed_cli_output)
if not processed_cli_output['result']:
log.debug('Apparently this didnt work, returning '
'the raw output')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {0}: {1}'.format(command,
processed_cli_output['comment'])
log.error(processed_cli_outputs['comment'])
elif processed_cli_output['out']:
log.debug('All good, %s has a nice output!', command)
processed_command_output = processed_cli_output['out']
else:
log.debug('Processing %s didnt fail, but didnt return'
' anything either. Dumping raw.', command)
processed_command_output = command_output
else:
log.error('No TextFSM template specified, or no TextFSM path defined')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {}.'.format(command)
processed_cli_outputs['out'][command] = processed_command_output
processed_cli_outputs['comment'] = processed_cli_outputs['comment'].strip()
return processed_cli_outputs
|
Returns a dictionary with the raw output of all commands passed as arguments.
commands
List of commands to be executed on the device.
textfsm_parse: ``False``
Try parsing the outputs using the TextFSM templates.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``napalm_cli_textfsm_parse``.
textfsm_path
The path where the TextFSM templates can be found. This option implies
the usage of the TextFSM index file.
``textfsm_path`` can be either absolute path on the server,
either specified using the following URL mschemes: ``file://``,
``salt://``, ``http://``, ``https://``, ``ftp://``,
``s3://``, ``swift://``.
.. versionadded:: 2018.3.0
.. note::
This needs to be a directory with a flat structure, having an
index file (whose name can be specified using the ``index_file`` option)
and a number of TextFSM templates.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_path``.
textfsm_template
The path to a certain the TextFSM template.
This can be specified using the absolute path
to the file, or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
.. versionadded:: 2018.3.0
textfsm_template_dict
A dictionary with the mapping between a command
and the corresponding TextFSM path to use to extract the data.
The TextFSM paths can be specified as in ``textfsm_template``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``napalm_cli_textfsm_template_dict``.
platform_grain_name: ``os``
The name of the grain used to identify the platform name
in the TextFSM index file. Default: ``os``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_grain``.
platform_column_name: ``Platform``
The column name used to identify the platform,
exactly as specified in the TextFSM index file.
Default: ``Platform``.
.. versionadded:: 2018.3.0
.. note::
This is field is case sensitive, make sure
to assign the correct value to this option,
exactly as defined in the index file.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_column_name``.
index_file: ``index``
The name of the TextFSM index file, under the ``textfsm_path``. Default: ``index``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_index_file``.
saltenv: ``base``
Salt fileserver envrionment from which to retrieve the file.
Ignored if ``textfsm_path`` is not a ``salt://`` URL.
.. versionadded:: 2018.3.0
include_empty: ``False``
Include empty files under the ``textfsm_path``.
.. versionadded:: 2018.3.0
include_pat
Glob or regex to narrow down the files cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. versionadded:: 2018.3.0
exclude_pat
Glob or regex to exclude certain files from being cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. versionadded:: 2018.3.0
.. note::
If used with ``include_pat``, files matching this pattern will be
excluded from the subset of files defined by ``include_pat``.
CLI Example:
.. code-block:: bash
salt '*' net.cli "show version" "show chassis fan"
CLI Example with TextFSM template:
.. code-block:: bash
salt '*' net.cli textfsm_parse=True textfsm_path=salt://textfsm/
Example output:
.. code-block:: python
{
'show version and haiku': 'Hostname: re0.edge01.arn01
Model: mx480
Junos: 13.3R6.5
Help me, Obi-Wan
I just saw Episode Two
You're my only hope
',
'show chassis fan' : 'Item Status RPM Measurement
Top Rear Fan OK 3840 Spinning at intermediate-speed
Bottom Rear Fan OK 3840 Spinning at intermediate-speed
Top Middle Fan OK 3900 Spinning at intermediate-speed
Bottom Middle Fan OK 3840 Spinning at intermediate-speed
Top Front Fan OK 3810 Spinning at intermediate-speed
Bottom Front Fan OK 3840 Spinning at intermediate-speed
'
}
Example output with TextFSM parsing:
.. code-block:: json
{
"comment": "",
"result": true,
"out": {
"sh ver": [
{
"kernel": "9.1S3.5",
"documentation": "9.1S3.5",
"boot": "9.1S3.5",
"crypto": "9.1S3.5",
"chassis": "",
"routing": "9.1S3.5",
"base": "9.1S3.5",
"model": "mx960"
}
]
}
}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_network.py#L492-L783
|
[
"def call(napalm_device, method, *args, **kwargs):\n '''\n Calls arbitrary methods from the network driver instance.\n Please check the readthedocs_ page for the updated list of getters.\n\n .. _readthedocs: http://napalm.readthedocs.org/en/latest/support/index.html#getters-support-matrix\n\n method\n Specifies the name of the method to be called.\n\n *args\n Arguments.\n\n **kwargs\n More arguments.\n\n :return: A dictionary with three keys:\n\n * result (True/False): if the operation succeeded\n * out (object): returns the object as-is from the call\n * comment (string): provides more details in case the call failed\n * traceback (string): complete traceback in case of exception. \\\n Please submit an issue including this traceback \\\n on the `correct driver repo`_ and make sure to read the FAQ_\n\n .. _`correct driver repo`: https://github.com/napalm-automation/napalm/issues/new\n .. FAQ_: https://github.com/napalm-automation/napalm#faq\n\n Example:\n\n .. code-block:: python\n\n salt.utils.napalm.call(\n napalm_object,\n 'cli',\n [\n 'show version',\n 'show chassis fan'\n ]\n )\n '''\n result = False\n out = None\n opts = napalm_device.get('__opts__', {})\n retry = kwargs.pop('__retry', True) # retry executing the task?\n force_reconnect = kwargs.get('force_reconnect', False)\n if force_reconnect:\n log.debug('Forced reconnection initiated')\n log.debug('The current opts (under the proxy key):')\n log.debug(opts['proxy'])\n opts['proxy'].update(**kwargs)\n log.debug('Updated to:')\n log.debug(opts['proxy'])\n napalm_device = get_device(opts)\n try:\n if not napalm_device.get('UP', False):\n raise Exception('not connected')\n # if connected will try to execute desired command\n kwargs_copy = {}\n kwargs_copy.update(kwargs)\n for karg, warg in six.iteritems(kwargs_copy):\n # lets clear None arguments\n # to not be sent to NAPALM methods\n if warg is None:\n kwargs.pop(karg)\n out = getattr(napalm_device.get('DRIVER'), method)(*args, **kwargs)\n # calls the method with the specified parameters\n result = True\n except Exception as error:\n # either not connected\n # either unable to execute the command\n hostname = napalm_device.get('HOSTNAME', '[unspecified hostname]')\n err_tb = traceback.format_exc() # let's get the full traceback and display for debugging reasons.\n if isinstance(error, NotImplementedError):\n comment = '{method} is not implemented for the NAPALM {driver} driver!'.format(\n method=method,\n driver=napalm_device.get('DRIVER_NAME')\n )\n elif retry and HAS_CONN_CLOSED_EXC_CLASS and isinstance(error, ConnectionClosedException):\n # Received disconection whilst executing the operation.\n # Instructed to retry (default behaviour)\n # thus trying to re-establish the connection\n # and re-execute the command\n # if any of the operations (close, open, call) will rise again ConnectionClosedException\n # it will fail loudly.\n kwargs['__retry'] = False # do not attempt re-executing\n comment = 'Disconnected from {device}. Trying to reconnect.'.format(device=hostname)\n log.error(err_tb)\n log.error(comment)\n log.debug('Clearing the connection with %s', hostname)\n call(napalm_device, 'close', __retry=False) # safely close the connection\n # Make sure we don't leave any TCP connection open behind\n # if we fail to close properly, we might not be able to access the\n log.debug('Re-opening the connection with %s', hostname)\n call(napalm_device, 'open', __retry=False)\n log.debug('Connection re-opened with %s', hostname)\n log.debug('Re-executing %s', method)\n return call(napalm_device, method, *args, **kwargs)\n # If still not able to reconnect and execute the task,\n # the proxy keepalive feature (if enabled) will attempt\n # to reconnect.\n # If the device is using a SSH-based connection, the failure\n # will also notify the paramiko transport and the `is_alive` flag\n # is going to be set correctly.\n # More background: the network device may decide to disconnect,\n # although the SSH session itself is alive and usable, the reason\n # being the lack of activity on the CLI.\n # Paramiko's keepalive doesn't help in this case, as the ServerAliveInterval\n # are targeting the transport layer, whilst the device takes the decision\n # when there isn't any activity on the CLI, thus at the application layer.\n # Moreover, the disconnect is silent and paramiko's is_alive flag will\n # continue to return True, although the connection is already unusable.\n # For more info, see https://github.com/paramiko/paramiko/issues/813.\n # But after a command fails, the `is_alive` flag becomes aware of these\n # changes and will return False from there on. And this is how the\n # Salt proxy keepalive helps: immediately after the first failure, it\n # will know the state of the connection and will try reconnecting.\n else:\n comment = 'Cannot execute \"{method}\" on {device}{port} as {user}. Reason: {error}!'.format(\n device=napalm_device.get('HOSTNAME', '[unspecified hostname]'),\n port=(':{port}'.format(port=napalm_device.get('OPTIONAL_ARGS', {}).get('port'))\n if napalm_device.get('OPTIONAL_ARGS', {}).get('port') else ''),\n user=napalm_device.get('USERNAME', ''),\n method=method,\n error=error\n )\n log.error(comment)\n log.error(err_tb)\n return {\n 'out': {},\n 'result': False,\n 'comment': comment,\n 'traceback': err_tb\n }\n finally:\n if opts and not_always_alive(opts) and napalm_device.get('CLOSE', True):\n # either running in a not-always-alive proxy\n # either running in a regular minion\n # close the connection when the call is over\n # unless the CLOSE is explicitly set as False\n napalm_device['DRIVER'].close()\n return {\n 'out': out,\n 'result': result,\n 'comment': ''\n }\n"
] |
# -*- coding: utf-8 -*-
'''
NAPALM Network
==============
Basic methods for interaction with the network device through the virtual proxy 'napalm'.
:codeauthor: Mircea Ulinic <mircea@cloudflare.com> & Jerome Fleury <jf@cloudflare.com>
:maturity: new
:depends: napalm
:platform: unix
Dependencies
------------
- :mod:`napalm proxy minion <salt.proxy.napalm>`
.. versionadded:: 2016.11.0
.. versionchanged:: 2017.7.0
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import time
import logging
import datetime
log = logging.getLogger(__name__)
# Import Salt libs
from salt.ext import six
import salt.utils.files
import salt.utils.napalm
import salt.utils.versions
import salt.utils.templates
# Import 3rd-party libs
try:
import jxmlease # pylint: disable=unused-import
HAS_JXMLEASE = True
except ImportError:
HAS_JXMLEASE = False
# ----------------------------------------------------------------------------------------------------------------------
# module properties
# ----------------------------------------------------------------------------------------------------------------------
__virtualname__ = 'net'
__proxyenabled__ = ['*']
__virtual_aliases__ = ('napalm_net',)
# uses NAPALM-based proxy to interact with network devices
# ----------------------------------------------------------------------------------------------------------------------
# property functions
# ----------------------------------------------------------------------------------------------------------------------
def __virtual__():
'''
NAPALM library must be installed for this module to work and run in a (proxy) minion.
'''
return salt.utils.napalm.virtual(__opts__, __virtualname__, __file__)
# ----------------------------------------------------------------------------------------------------------------------
# helper functions -- will not be exported
# ----------------------------------------------------------------------------------------------------------------------
def _filter_list(input_list, search_key, search_value):
'''
Filters a list of dictionary by a set of key-value pair.
:param input_list: is a list of dictionaries
:param search_key: is the key we are looking for
:param search_value: is the value we are looking for the key specified in search_key
:return: filered list of dictionaries
'''
output_list = list()
for dictionary in input_list:
if dictionary.get(search_key) == search_value:
output_list.append(dictionary)
return output_list
def _filter_dict(input_dict, search_key, search_value):
'''
Filters a dictionary of dictionaries by a key-value pair.
:param input_dict: is a dictionary whose values are lists of dictionaries
:param search_key: is the key in the leaf dictionaries
:param search_values: is the value in the leaf dictionaries
:return: filtered dictionary
'''
output_dict = dict()
for key, key_list in six.iteritems(input_dict):
key_list_filtered = _filter_list(key_list, search_key, search_value)
if key_list_filtered:
output_dict[key] = key_list_filtered
return output_dict
def _safe_commit_config(loaded_result, napalm_device):
_commit = commit(inherit_napalm_device=napalm_device) # calls the function commit, defined below
if not _commit.get('result', False):
# if unable to commit
loaded_result['comment'] += _commit['comment'] if _commit.get('comment') else 'Unable to commit.'
loaded_result['result'] = False
# unable to commit, something went wrong
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
return _commit
def _safe_dicard_config(loaded_result, napalm_device):
'''
'''
log.debug('Discarding the config')
log.debug(loaded_result)
_discarded = discard_config(inherit_napalm_device=napalm_device)
if not _discarded.get('result', False):
loaded_result['comment'] += _discarded['comment'] if _discarded.get('comment') \
else 'Unable to discard config.'
loaded_result['result'] = False
# make sure it notifies
# that something went wrong
_explicit_close(napalm_device)
__context__['retcode'] = 1
return loaded_result
return _discarded
def _explicit_close(napalm_device):
'''
Will explicily close the config session with the network device,
when running in a now-always-alive proxy minion or regular minion.
This helper must be used in configuration-related functions,
as the session is preserved and not closed before making any changes.
'''
if salt.utils.napalm.not_always_alive(__opts__):
# force closing the configuration session
# when running in a non-always-alive proxy
# or regular minion
try:
napalm_device['DRIVER'].close()
except Exception as err:
log.error('Unable to close the temp connection with the device:')
log.error(err)
log.error('Please report.')
def _config_logic(napalm_device,
loaded_result,
test=False,
debug=False,
replace=False,
commit_config=True,
loaded_config=None,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
commit_jid=None,
**kwargs):
'''
Builds the config logic for `load_config` and `load_template` functions.
'''
# As the Salt logic is built around independent events
# when it comes to configuration changes in the
# candidate DB on the network devices, we need to
# make sure we're using the same session.
# Hence, we need to pass the same object around.
# the napalm_device object is inherited from
# the load_config or load_template functions
# and forwarded to compare, discard, commit etc.
# then the decorator will make sure that
# if not proxy (when the connection is always alive)
# and the `inherit_napalm_device` is set,
# `napalm_device` will be overridden.
# See `salt.utils.napalm.proxy_napalm_wrap` decorator.
current_jid = kwargs.get('__pub_jid')
if not current_jid:
current_jid = '{0:%Y%m%d%H%M%S%f}'.format(datetime.datetime.now())
loaded_result['already_configured'] = False
loaded_result['loaded_config'] = ''
if debug:
loaded_result['loaded_config'] = loaded_config
_compare = compare_config(inherit_napalm_device=napalm_device)
if _compare.get('result', False):
loaded_result['diff'] = _compare.get('out')
loaded_result.pop('out', '') # not needed
else:
loaded_result['diff'] = None
loaded_result['result'] = False
loaded_result['comment'] = _compare.get('comment')
__context__['retcode'] = 1
return loaded_result
_loaded_res = loaded_result.get('result', False)
if not _loaded_res or test:
# if unable to load the config (errors / warnings)
# or in testing mode,
# will discard the config
if loaded_result['comment']:
loaded_result['comment'] += '\n'
if not loaded_result.get('diff', ''):
loaded_result['already_configured'] = True
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
loaded_result['comment'] += 'Configuration discarded.'
# loaded_result['result'] = False not necessary
# as the result can be true when test=True
_explicit_close(napalm_device)
if not loaded_result['result']:
__context__['retcode'] = 1
return loaded_result
if not test and commit_config:
# if not in testing mode and trying to commit
if commit_jid:
log.info('Committing the JID: %s', str(commit_jid))
removed = cancel_commit(commit_jid)
log.debug('Cleaned up the commit from the schedule')
log.debug(removed['comment'])
if loaded_result.get('diff', ''):
# if not testing mode
# and also the user wants to commit (default)
# and there are changes to commit
if commit_in or commit_at:
commit_time = __utils__['timeutil.get_time_at'](time_in=commit_in,
time_at=commit_in)
# schedule job
scheduled_job_name = '__napalm_commit_{}'.format(current_jid)
temp_file = salt.utils.files.mkstemp()
with salt.utils.files.fopen(temp_file, 'w') as fp_:
fp_.write(loaded_config)
scheduled = __salt__['schedule.add'](scheduled_job_name,
function='net.load_config',
job_kwargs={
'filename': temp_file,
'commit_jid': current_jid,
'replace': replace
},
once=commit_time)
log.debug('Scheduling job')
log.debug(scheduled)
saved = __salt__['schedule.save']() # ensure the schedule is
# persistent cross Minion restart
discarded = _safe_dicard_config(loaded_result, napalm_device)
# discard the changes
if not discarded['result']:
discarded['comment'] += ('Scheduled the job to be executed at {schedule_ts}, '
'but was unable to discard the config: \n').format(schedule_ts=commit_time)
return discarded
loaded_result['comment'] = ('Changes discarded for now, and scheduled commit at: {schedule_ts}.\n'
'The commit ID is: {current_jid}.\n'
'To discard this commit, you can execute: \n\n'
'salt {min_id} net.cancel_commit {current_jid}').format(schedule_ts=commit_time,
min_id=__opts__['id'],
current_jid=current_jid)
loaded_result['commit_id'] = current_jid
return loaded_result
log.debug('About to commit:')
log.debug(loaded_result['diff'])
if revert_in or revert_at:
revert_time = __utils__['timeutil.get_time_at'](time_in=revert_in,
time_at=revert_at)
if __grains__['os'] == 'junos':
if not HAS_JXMLEASE:
loaded_result['comment'] = ('This feature requires the library jxmlease to be installed.\n'
'To install, please execute: ``pip install jxmlease``.')
loaded_result['result'] = False
return loaded_result
timestamp_at = __utils__['timeutil.get_timestamp_at'](time_in=revert_in,
time_at=revert_at)
minutes = int((timestamp_at - time.time())/60)
_comm = __salt__['napalm.junos_commit'](confirm=minutes)
if not _comm['out']:
# If unable to commit confirm, should try to bail out
loaded_result['comment'] = 'Unable to commit confirm: {}'.format(_comm['message'])
loaded_result['result'] = False
# But before exiting, we must gracefully discard the config
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
else:
temp_file = salt.utils.files.mkstemp()
running_config = __salt__['net.config'](source='running')['out']['running']
with salt.utils.files.fopen(temp_file, 'w') as fp_:
fp_.write(running_config)
committed = _safe_commit_config(loaded_result, napalm_device)
if not committed['result']:
# If unable to commit, dicard the config (which is
# already done by the _safe_commit_config function), and
# return with the command and other details.
return loaded_result
scheduled_job_name = '__napalm_commit_{}'.format(current_jid)
scheduled = __salt__['schedule.add'](scheduled_job_name,
function='net.load_config',
job_kwargs={
'filename': temp_file,
'commit_jid': current_jid,
'replace': True
},
once=revert_time)
log.debug('Scheduling commit confirmed')
log.debug(scheduled)
saved = __salt__['schedule.save']()
loaded_result['comment'] = ('The commit ID is: {current_jid}.\n'
'This commit will be reverted at: {schedule_ts}, unless confirmed.\n'
'To confirm the commit and avoid reverting, you can execute:\n\n'
'salt {min_id} net.confirm_commit {current_jid}').format(schedule_ts=revert_time,
min_id=__opts__['id'],
current_jid=current_jid)
loaded_result['commit_id'] = current_jid
return loaded_result
committed = _safe_commit_config(loaded_result, napalm_device)
if not committed['result']:
return loaded_result
else:
# would like to commit, but there's no change
# need to call discard_config() to release the config DB
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
loaded_result['already_configured'] = True
loaded_result['comment'] = 'Already configured.'
_explicit_close(napalm_device)
if not loaded_result['result']:
__context__['retcode'] = 1
return loaded_result
# ----------------------------------------------------------------------------------------------------------------------
# callable functions
# ----------------------------------------------------------------------------------------------------------------------
@salt.utils.napalm.proxy_napalm_wrap
def connected(**kwargs): # pylint: disable=unused-argument
'''
Specifies if the connection to the device succeeded.
CLI Example:
.. code-block:: bash
salt '*' net.connected
'''
return {
'out': napalm_device.get('UP', False) # pylint: disable=undefined-variable
}
@salt.utils.napalm.proxy_napalm_wrap
def facts(**kwargs): # pylint: disable=unused-argument
'''
Returns characteristics of the network device.
:return: a dictionary with the following keys:
* uptime - Uptime of the device in seconds.
* vendor - Manufacturer of the device.
* model - Device model.
* hostname - Hostname of the device
* fqdn - Fqdn of the device
* os_version - String with the OS version running on the device.
* serial_number - Serial number of the device
* interface_list - List of the interfaces of the device
CLI Example:
.. code-block:: bash
salt '*' net.facts
Example output:
.. code-block:: python
{
'os_version': '13.3R6.5',
'uptime': 10117140,
'interface_list': [
'lc-0/0/0',
'pfe-0/0/0',
'pfh-0/0/0',
'xe-0/0/0',
'xe-0/0/1',
'xe-0/0/2',
'xe-0/0/3',
'gr-0/0/10',
'ip-0/0/10'
],
'vendor': 'Juniper',
'serial_number': 'JN131356FBFA',
'model': 'MX480',
'hostname': 're0.edge05.syd01',
'fqdn': 're0.edge05.syd01'
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_facts',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def environment(**kwargs): # pylint: disable=unused-argument
'''
Returns the environment of the device.
CLI Example:
.. code-block:: bash
salt '*' net.environment
Example output:
.. code-block:: python
{
'fans': {
'Bottom Rear Fan': {
'status': True
},
'Bottom Middle Fan': {
'status': True
},
'Top Middle Fan': {
'status': True
},
'Bottom Front Fan': {
'status': True
},
'Top Front Fan': {
'status': True
},
'Top Rear Fan': {
'status': True
}
},
'memory': {
'available_ram': 16349,
'used_ram': 4934
},
'temperature': {
'FPC 0 Exhaust A': {
'is_alert': False,
'temperature': 35.0,
'is_critical': False
}
},
'cpu': {
'1': {
'%usage': 19.0
},
'0': {
'%usage': 35.0
}
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_environment',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
@salt.utils.napalm.proxy_napalm_wrap
def traceroute(destination, source=None, ttl=None, timeout=None, vrf=None, **kwargs): # pylint: disable=unused-argument
'''
Calls the method traceroute from the NAPALM driver object and returns a dictionary with the result of the traceroute
command executed on the device.
destination
Hostname or address of remote host
source
Source address to use in outgoing traceroute packets
ttl
IP maximum time-to-live value (or IPv6 maximum hop-limit value)
timeout
Number of seconds to wait for response (seconds)
vrf
VRF (routing instance) for traceroute attempt
.. versionadded:: 2016.11.4
CLI Example:
.. code-block:: bash
salt '*' net.traceroute 8.8.8.8
salt '*' net.traceroute 8.8.8.8 source=127.0.0.1 ttl=5 timeout=1
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'traceroute',
**{
'destination': destination,
'source': source,
'ttl': ttl,
'timeout': timeout,
'vrf': vrf
}
)
@salt.utils.napalm.proxy_napalm_wrap
def ping(destination, source=None, ttl=None, timeout=None, size=None, count=None, vrf=None, **kwargs): # pylint: disable=unused-argument
'''
Executes a ping on the network device and returns a dictionary as a result.
destination
Hostname or IP address of remote host
source
Source address of echo request
ttl
IP time-to-live value (IPv6 hop-limit value) (1..255 hops)
timeout
Maximum wait time after sending final packet (seconds)
size
Size of request packets (0..65468 bytes)
count
Number of ping requests to send (1..2000000000 packets)
vrf
VRF (routing instance) for ping attempt
.. versionadded:: 2016.11.4
CLI Example:
.. code-block:: bash
salt '*' net.ping 8.8.8.8
salt '*' net.ping 8.8.8.8 ttl=3 size=65468
salt '*' net.ping 8.8.8.8 source=127.0.0.1 timeout=1 count=100
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'ping',
**{
'destination': destination,
'source': source,
'ttl': ttl,
'timeout': timeout,
'size': size,
'count': count,
'vrf': vrf
}
)
@salt.utils.napalm.proxy_napalm_wrap
def arp(interface='', ipaddr='', macaddr='', **kwargs): # pylint: disable=unused-argument
'''
NAPALM returns a list of dictionaries with details of the ARP entries.
:param interface: interface name to filter on
:param ipaddr: IP address to filter on
:param macaddr: MAC address to filter on
:return: List of the entries in the ARP table
CLI Example:
.. code-block:: bash
salt '*' net.arp
salt '*' net.arp macaddr='5c:5e:ab:da:3c:f0'
Example output:
.. code-block:: python
[
{
'interface' : 'MgmtEth0/RSP0/CPU0/0',
'mac' : '5c:5e:ab:da:3c:f0',
'ip' : '172.17.17.1',
'age' : 1454496274.84
},
{
'interface': 'MgmtEth0/RSP0/CPU0/0',
'mac' : '66:0e:94:96:e0:ff',
'ip' : '172.17.17.2',
'age' : 1435641582.49
}
]
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_arp_table',
**{
}
)
if not proxy_output.get('result'):
return proxy_output
arp_table = proxy_output.get('out')
if interface:
arp_table = _filter_list(arp_table, 'interface', interface)
if ipaddr:
arp_table = _filter_list(arp_table, 'ip', ipaddr)
if macaddr:
arp_table = _filter_list(arp_table, 'mac', macaddr)
proxy_output.update({
'out': arp_table
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def ipaddrs(**kwargs): # pylint: disable=unused-argument
'''
Returns IP addresses configured on the device.
:return: A dictionary with the IPv4 and IPv6 addresses of the interfaces.
Returns all configured IP addresses on all interfaces as a dictionary
of dictionaries. Keys of the main dictionary represent the name of the
interface. Values of the main dictionary represent are dictionaries
that may consist of two keys 'ipv4' and 'ipv6' (one, both or none)
which are themselvs dictionaries with the IP addresses as keys.
CLI Example:
.. code-block:: bash
salt '*' net.ipaddrs
Example output:
.. code-block:: python
{
'FastEthernet8': {
'ipv4': {
'10.66.43.169': {
'prefix_length': 22
}
}
},
'Loopback555': {
'ipv4': {
'192.168.1.1': {
'prefix_length': 24
}
},
'ipv6': {
'1::1': {
'prefix_length': 64
},
'2001:DB8:1::1': {
'prefix_length': 64
},
'FE80::3': {
'prefix_length': 'N/A'
}
}
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_interfaces_ip',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def interfaces(**kwargs): # pylint: disable=unused-argument
'''
Returns details of the interfaces on the device.
:return: Returns a dictionary of dictionaries. The keys for the first
dictionary will be the interfaces in the devices.
CLI Example:
.. code-block:: bash
salt '*' net.interfaces
Example output:
.. code-block:: python
{
'Management1': {
'is_up': False,
'is_enabled': False,
'description': '',
'last_flapped': -1,
'speed': 1000,
'mac_address': 'dead:beef:dead',
},
'Ethernet1':{
'is_up': True,
'is_enabled': True,
'description': 'foo',
'last_flapped': 1429978575.1554043,
'speed': 1000,
'mac_address': 'beef:dead:beef',
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_interfaces',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def lldp(interface='', **kwargs): # pylint: disable=unused-argument
'''
Returns a detailed view of the LLDP neighbors.
:param interface: interface name to filter on
:return: A dictionary with the LLDL neighbors. The keys are the
interfaces with LLDP activated on.
CLI Example:
.. code-block:: bash
salt '*' net.lldp
salt '*' net.lldp interface='TenGigE0/0/0/8'
Example output:
.. code-block:: python
{
'TenGigE0/0/0/8': [
{
'parent_interface': 'Bundle-Ether8',
'interface_description': 'TenGigE0/0/0/8',
'remote_chassis_id': '8c60.4f69.e96c',
'remote_system_name': 'switch',
'remote_port': 'Eth2/2/1',
'remote_port_description': 'Ethernet2/2/1',
'remote_system_description': 'Cisco Nexus Operating System (NX-OS) Software 7.1(0)N1(1a)
TAC support: http://www.cisco.com/tac
Copyright (c) 2002-2015, Cisco Systems, Inc. All rights reserved.',
'remote_system_capab': 'B, R',
'remote_system_enable_capab': 'B'
}
]
}
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_lldp_neighbors_detail',
**{
}
)
if not proxy_output.get('result'):
return proxy_output
lldp_neighbors = proxy_output.get('out')
if interface:
lldp_neighbors = {interface: lldp_neighbors.get(interface)}
proxy_output.update({
'out': lldp_neighbors
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def mac(address='', interface='', vlan=0, **kwargs): # pylint: disable=unused-argument
'''
Returns the MAC Address Table on the device.
:param address: MAC address to filter on
:param interface: Interface name to filter on
:param vlan: VLAN identifier
:return: A list of dictionaries representing the entries in the MAC Address Table
CLI Example:
.. code-block:: bash
salt '*' net.mac
salt '*' net.mac vlan=10
Example output:
.. code-block:: python
[
{
'mac' : '00:1c:58:29:4a:71',
'interface' : 'xe-3/0/2',
'static' : False,
'active' : True,
'moves' : 1,
'vlan' : 10,
'last_move' : 1454417742.58
},
{
'mac' : '8c:60:4f:58:e1:c1',
'interface' : 'xe-1/0/1',
'static' : False,
'active' : True,
'moves' : 2,
'vlan' : 42,
'last_move' : 1453191948.11
}
]
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_mac_address_table',
**{
}
)
if not proxy_output.get('result'):
# if negative, leave the output unchanged
return proxy_output
mac_address_table = proxy_output.get('out')
if vlan and isinstance(vlan, int):
mac_address_table = _filter_list(mac_address_table, 'vlan', vlan)
if address:
mac_address_table = _filter_list(mac_address_table, 'mac', address)
if interface:
mac_address_table = _filter_list(mac_address_table, 'interface', interface)
proxy_output.update({
'out': mac_address_table
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def config(source=None, **kwargs): # pylint: disable=unused-argument
'''
.. versionadded:: 2017.7.0
Return the whole configuration of the network device. By default, it will
return all possible configuration sources supported by the network device.
At most, there will be:
- running config
- startup config
- candidate config
To return only one of the configurations, you can use the ``source``
argument.
source
Which configuration type you want to display, default is all of them.
Options:
- running
- candidate
- startup
:return:
The object returned is a dictionary with the following keys:
- running (string): Representation of the native running configuration.
- candidate (string): Representation of the native candidate configuration.
If the device doesn't differentiate between running and startup
configuration this will an empty string.
- startup (string): Representation of the native startup configuration.
If the device doesn't differentiate between running and startup
configuration this will an empty string.
CLI Example:
.. code-block:: bash
salt '*' net.config
salt '*' net.config source=candidate
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_config',
**{
'retrieve': source
}
)
@salt.utils.napalm.proxy_napalm_wrap
def optics(**kwargs): # pylint: disable=unused-argument
'''
.. versionadded:: 2017.7.0
Fetches the power usage on the various transceivers installed
on the network device (in dBm), and returns a view that conforms with the
OpenConfig model openconfig-platform-transceiver.yang.
:return:
Returns a dictionary where the keys are as listed below:
* intf_name (unicode)
* physical_channels
* channels (list of dicts)
* index (int)
* state
* input_power
* instant (float)
* avg (float)
* min (float)
* max (float)
* output_power
* instant (float)
* avg (float)
* min (float)
* max (float)
* laser_bias_current
* instant (float)
* avg (float)
* min (float)
* max (float)
CLI Example:
.. code-block:: bash
salt '*' net.optics
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_optics',
**{
}
)
# <---- Call NAPALM getters --------------------------------------------------------------------------------------------
# ----- Configuration specific functions ------------------------------------------------------------------------------>
@salt.utils.napalm.proxy_napalm_wrap
def load_config(filename=None,
text=None,
test=False,
commit=True,
debug=False,
replace=False,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
commit_jid=None,
inherit_napalm_device=None,
saltenv='base',
**kwargs): # pylint: disable=unused-argument
'''
Applies configuration changes on the device. It can be loaded from a file or from inline string.
If you send both a filename and a string containing the configuration, the file has higher precedence.
By default this function will commit the changes. If there are no changes, it does not commit and
the flag ``already_configured`` will be set as ``True`` to point this out.
To avoid committing the configuration, set the argument ``test`` to ``True`` and will discard (dry run).
To keep the changes but not commit, set ``commit`` to ``False``.
To replace the config, set ``replace`` to ``True``.
filename
Path to the file containing the desired configuration.
This can be specified using the absolute path to the file,
or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
.. versionchanged:: 2018.3.0
text
String containing the desired configuration.
This argument is ignored when ``filename`` is specified.
test: False
Dry run? If set as ``True``, will apply the config, discard and return the changes. Default: ``False``
and will commit the changes on the device.
commit: True
Commit? Default: ``True``.
debug: False
Debug mode. Will insert a new key under the output dictionary, as ``loaded_config`` containing the raw
configuration loaded on the device.
.. versionadded:: 2016.11.2
replace: False
Load and replace the configuration. Default: ``False``.
.. versionadded:: 2016.11.2
commit_in: ``None``
Commit the changes in a specific number of minutes / hours. Example of
accepted formats: ``5`` (commit in 5 minutes), ``2m`` (commit in 2
minutes), ``1h`` (commit the changes in 1 hour)`, ``5h30m`` (commit
the changes in 5 hours and 30 minutes).
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
commit_at: ``None``
Commit the changes at a specific time. Example of accepted formats:
``1am`` (will commit the changes at the next 1AM), ``13:20`` (will
commit at 13:20), ``1:20am``, etc.
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
revert_in: ``None``
Commit and revert the changes in a specific number of minutes / hours.
Example of accepted formats: ``5`` (revert in 5 minutes), ``2m`` (revert
in 2 minutes), ``1h`` (revert the changes in 1 hour)`, ``5h30m`` (revert
the changes in 5 hours and 30 minutes).
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
revert_at: ``None``
Commit and revert the changes at a specific time. Example of accepted
formats: ``1am`` (will commit and revert the changes at the next 1AM),
``13:20`` (will commit and revert at 13:20), ``1:20am``, etc.
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
saltenv: ``base``
Specifies the Salt environment name.
.. versionadded:: 2018.3.0
:return: a dictionary having the following keys:
* result (bool): if the config was applied successfully. It is ``False`` only in case of failure. In case \
there are no changes to be applied and successfully performs all operations it is still ``True`` and so will be \
the ``already_configured`` flag (example below)
* comment (str): a message for the user
* already_configured (bool): flag to check if there were no changes applied
* loaded_config (str): the configuration loaded on the device. Requires ``debug`` to be set as ``True``
* diff (str): returns the config changes applied
CLI Example:
.. code-block:: bash
salt '*' net.load_config text='ntp peer 192.168.0.1'
salt '*' net.load_config filename='/absolute/path/to/your/file'
salt '*' net.load_config filename='/absolute/path/to/your/file' test=True
salt '*' net.load_config filename='/absolute/path/to/your/file' commit=False
Example output:
.. code-block:: python
{
'comment': 'Configuration discarded.',
'already_configured': False,
'result': True,
'diff': '[edit interfaces xe-0/0/5]+ description "Adding a description";'
}
'''
fun = 'load_merge_candidate'
if replace:
fun = 'load_replace_candidate'
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
if filename:
text = __salt__['cp.get_file_str'](filename, saltenv=saltenv)
if text is False:
# When using salt:// or https://, if the resource is not available,
# it will either raise an exception, or return False.
ret = {
'result': False,
'out': None
}
ret['comment'] = 'Unable to read from {}. Please specify a valid file or text.'.format(filename)
log.error(ret['comment'])
return ret
if commit_jid:
# When the commit_jid argument is passed, it probably is a scheduled
# commit to be executed, and filename is a temporary file which
# can be removed after reading it.
salt.utils.files.safe_rm(filename)
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
fun,
**{
'config': text
}
)
return _config_logic(napalm_device, # pylint: disable=undefined-variable
_loaded,
test=test,
debug=debug,
replace=replace,
commit_config=commit,
loaded_config=text,
commit_at=commit_at,
commit_in=commit_in,
revert_in=revert_in,
revert_at=revert_at,
commit_jid=commit_jid,
**kwargs)
@salt.utils.napalm.proxy_napalm_wrap
def load_template(template_name=None,
template_source=None,
context=None,
defaults=None,
template_engine='jinja',
saltenv='base',
template_hash=None,
template_hash_name=None,
skip_verify=False,
test=False,
commit=True,
debug=False,
replace=False,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
inherit_napalm_device=None, # pylint: disable=unused-argument
**template_vars):
'''
Renders a configuration template (default: Jinja) and loads the result on the device.
By default this function will commit the changes. If there are no changes,
it does not commit, discards he config and the flag ``already_configured``
will be set as ``True`` to point this out.
To avoid committing the configuration, set the argument ``test`` to ``True``
and will discard (dry run).
To preserve the changes, set ``commit`` to ``False``.
However, this is recommended to be used only in exceptional cases
when there are applied few consecutive states
and/or configuration changes.
Otherwise the user might forget that the config DB is locked
and the candidate config buffer is not cleared/merged in the running config.
To replace the config, set ``replace`` to ``True``.
template_name
Identifies path to the template source.
The template can be either stored on the local machine, either remotely.
The recommended location is under the ``file_roots``
as specified in the master config file.
For example, let's suppose the ``file_roots`` is configured as:
.. code-block:: yaml
file_roots:
base:
- /etc/salt/states
Placing the template under ``/etc/salt/states/templates/example.jinja``,
it can be used as ``salt://templates/example.jinja``.
Alternatively, for local files, the user can specify the absolute path.
If remotely, the source can be retrieved via ``http``, ``https`` or ``ftp``.
Examples:
- ``salt://my_template.jinja``
- ``/absolute/path/to/my_template.jinja``
- ``http://example.com/template.cheetah``
- ``https:/example.com/template.mako``
- ``ftp://example.com/template.py``
.. versionchanged:: 2019.2.0
This argument can now support a list of templates to be rendered.
The resulting configuration text is loaded at once, as a single
configuration chunk.
template_source: None
Inline config template to be rendered and loaded on the device.
template_hash: None
Hash of the template file. Format: ``{hash_type: 'md5', 'hsum': <md5sum>}``
.. versionadded:: 2016.11.2
context: None
Overrides default context variables passed to the template.
.. versionadded:: 2019.2.0
template_hash_name: None
When ``template_hash`` refers to a remote file,
this specifies the filename to look for in that file.
.. versionadded:: 2016.11.2
saltenv: ``base``
Specifies the template environment.
This will influence the relative imports inside the templates.
.. versionadded:: 2016.11.2
template_engine: jinja
The following templates engines are supported:
- :mod:`cheetah<salt.renderers.cheetah>`
- :mod:`genshi<salt.renderers.genshi>`
- :mod:`jinja<salt.renderers.jinja>`
- :mod:`mako<salt.renderers.mako>`
- :mod:`py<salt.renderers.py>`
- :mod:`wempy<salt.renderers.wempy>`
.. versionadded:: 2016.11.2
skip_verify: True
If ``True``, hash verification of remote file sources
(``http://``, ``https://``, ``ftp://``) will be skipped,
and the ``source_hash`` argument will be ignored.
.. versionadded:: 2016.11.2
test: False
Dry run? If set to ``True``, will apply the config,
discard and return the changes.
Default: ``False`` and will commit the changes on the device.
commit: True
Commit? (default: ``True``)
debug: False
Debug mode. Will insert a new key under the output dictionary,
as ``loaded_config`` containing the raw result after the template was rendered.
.. versionadded:: 2016.11.2
replace: False
Load and replace the configuration.
.. versionadded:: 2016.11.2
commit_in: ``None``
Commit the changes in a specific number of minutes / hours. Example of
accepted formats: ``5`` (commit in 5 minutes), ``2m`` (commit in 2
minutes), ``1h`` (commit the changes in 1 hour)`, ``5h30m`` (commit
the changes in 5 hours and 30 minutes).
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
commit_at: ``None``
Commit the changes at a specific time. Example of accepted formats:
``1am`` (will commit the changes at the next 1AM), ``13:20`` (will
commit at 13:20), ``1:20am``, etc.
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
revert_in: ``None``
Commit and revert the changes in a specific number of minutes / hours.
Example of accepted formats: ``5`` (revert in 5 minutes), ``2m`` (revert
in 2 minutes), ``1h`` (revert the changes in 1 hour)`, ``5h30m`` (revert
the changes in 5 hours and 30 minutes).
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
revert_at: ``None``
Commit and revert the changes at a specific time. Example of accepted
formats: ``1am`` (will commit and revert the changes at the next 1AM),
``13:20`` (will commit and revert at 13:20), ``1:20am``, etc.
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
defaults: None
Default variables/context passed to the template.
.. versionadded:: 2016.11.2
template_vars
Dictionary with the arguments/context to be used when the template is rendered.
.. note::
Do not explicitly specify this argument. This represents any other
variable that will be sent to the template rendering system.
Please see the examples below!
.. note::
It is more recommended to use the ``context`` argument to avoid
conflicts between CLI arguments and template variables.
:return: a dictionary having the following keys:
- result (bool): if the config was applied successfully. It is ``False``
only in case of failure. In case there are no changes to be applied and
successfully performs all operations it is still ``True`` and so will be
the ``already_configured`` flag (example below)
- comment (str): a message for the user
- already_configured (bool): flag to check if there were no changes applied
- loaded_config (str): the configuration loaded on the device, after
rendering the template. Requires ``debug`` to be set as ``True``
- diff (str): returns the config changes applied
The template can use variables from the ``grains``, ``pillar`` or ``opts``, for example:
.. code-block:: jinja
{% set router_model = grains.get('model') -%}
{% set router_vendor = grains.get('vendor') -%}
{% set os_version = grains.get('version') -%}
{% set hostname = pillar.get('proxy', {}).get('host') -%}
{% if router_vendor|lower == 'juniper' %}
system {
host-name {{hostname}};
}
{% elif router_vendor|lower == 'cisco' %}
hostname {{hostname}}
{% endif %}
CLI Examples:
.. code-block:: bash
salt '*' net.load_template set_ntp_peers peers=[192.168.0.1] # uses NAPALM default templates
# inline template:
salt -G 'os:junos' net.load_template template_source='system { host-name {{host_name}}; }' \
host_name='MX480.lab'
# inline template using grains info:
salt -G 'os:junos' net.load_template \
template_source='system { host-name {{grains.model}}.lab; }'
# if the device is a MX480, the command above will set the hostname as: MX480.lab
# inline template using pillar data:
salt -G 'os:junos' net.load_template template_source='system { host-name {{pillar.proxy.host}}; }'
salt '*' net.load_template https://bit.ly/2OhSgqP hostname=example # will commit
salt '*' net.load_template https://bit.ly/2OhSgqP hostname=example test=True # dry run
salt '*' net.load_template salt://templates/example.jinja debug=True # Using the salt:// URI
# render a mako template:
salt '*' net.load_template salt://templates/example.mako template_engine=mako debug=True
# render remote template
salt -G 'os:junos' net.load_template http://bit.ly/2fReJg7 test=True debug=True peers=['192.168.0.1']
salt -G 'os:ios' net.load_template http://bit.ly/2gKOj20 test=True debug=True peers=['192.168.0.1']
# render multiple templates at once
salt '*' net.load_template "['https://bit.ly/2OhSgqP', 'salt://templates/example.jinja']" context="{'hostname': 'example'}"
Example output:
.. code-block:: python
{
'comment': '',
'already_configured': False,
'result': True,
'diff': '[edit system]+ host-name edge01.bjm01',
'loaded_config': 'system { host-name edge01.bjm01; }''
}
'''
_rendered = ''
_loaded = {
'result': True,
'comment': '',
'out': None
}
loaded_config = None
# prechecks
deprecated_args = ('template_user', 'template_attrs', 'template_group', 'template_mode')
for deprecated_arg in deprecated_args:
if template_vars.get(deprecated_arg):
del template_vars[deprecated_arg]
salt.utils.versions.warn_until(
'Sodium',
('The \'{arg}\' argument to \'net.load_template\' is deprecated '
'and has been ignored').format(arg=deprecated_arg)
)
if template_engine not in salt.utils.templates.TEMPLATE_REGISTRY:
_loaded.update({
'result': False,
'comment': 'Invalid templating engine! Choose between: {tpl_eng_opts}'.format(
tpl_eng_opts=', '.join(list(salt.utils.templates.TEMPLATE_REGISTRY.keys()))
)
})
return _loaded # exit
# to check if will be rendered by salt or NAPALM
salt_render_prefixes = ('salt://', 'http://', 'https://', 'ftp://')
salt_render = False
file_exists = False
if not isinstance(template_name, (tuple, list)):
for salt_render_prefix in salt_render_prefixes:
if not salt_render:
salt_render = salt_render or template_name.startswith(salt_render_prefix)
file_exists = __salt__['file.file_exists'](template_name)
if template_source or file_exists or salt_render or isinstance(template_name, (tuple, list)):
# either inline template
# either template in a custom path
# either abs path send
# either starts with salt:// and
# then use Salt render system
if context is None:
context = {}
context.update(template_vars)
# if needed to render the template send as inline arg
if template_source:
# render the content
_rendered = __salt__['file.apply_template_on_contents'](
contents=template_source,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv
)
if not isinstance(_rendered, six.string_types):
if 'result' in _rendered:
_loaded['result'] = _rendered['result']
else:
_loaded['result'] = False
if 'comment' in _rendered:
_loaded['comment'] = _rendered['comment']
else:
_loaded['comment'] = 'Error while rendering the template.'
return _loaded
else:
# render the file - either local, either remote
if not isinstance(template_name, (list, tuple)):
template_name = [template_name]
if template_hash_name and not isinstance(template_hash_name, (list, tuple)):
template_hash_name = [template_hash_name]
elif not template_hash_name:
template_hash_name = [None] * len(template_name)
if template_hash and isinstance(template_hash, six.string_types) and not\
(template_hash.startswith('salt://') or template_hash.startswith('file://')):
# If the template hash is passed as string, and it's not a file
# (starts with the salt:// or file:// URI), then make it a list
# of 1 element (for the iteration below)
template_hash = [template_hash]
elif template_hash and isinstance(template_hash, six.string_types) and\
(template_hash.startswith('salt://') or template_hash.startswith('file://')):
# If the template hash is a file URI, then provide the same value
# for each of the templates in the list, as probably they all
# share the same hash file, otherwise the user should provide
# this as a list
template_hash = [template_hash] * len(template_name)
elif not template_hash:
template_hash = [None] * len(template_name)
for tpl_index, tpl_name in enumerate(template_name):
tpl_hash = template_hash[tpl_index]
tpl_hash_name = template_hash_name[tpl_index]
_rand_filename = __salt__['random.hash'](tpl_name, 'md5')
_temp_file = __salt__['file.join']('/tmp', _rand_filename)
_managed = __salt__['file.get_managed'](name=_temp_file,
source=tpl_name,
source_hash=tpl_hash,
source_hash_name=tpl_hash_name,
user=None,
group=None,
mode=None,
attrs=None,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv,
skip_verify=skip_verify)
if not isinstance(_managed, (list, tuple)) and isinstance(_managed, six.string_types):
_loaded['comment'] += _managed
_loaded['result'] = False
elif isinstance(_managed, (list, tuple)) and not _managed:
_loaded['result'] = False
_loaded['comment'] += 'Error while rendering the template.'
elif isinstance(_managed, (list, tuple)) and not _managed[0]:
_loaded['result'] = False
_loaded['comment'] += _managed[-1] # contains the error message
if _loaded['result']: # all good
_temp_tpl_file = _managed[0]
_temp_tpl_file_exists = __salt__['file.file_exists'](_temp_tpl_file)
if not _temp_tpl_file_exists:
_loaded['result'] = False
_loaded['comment'] += 'Error while rendering the template.'
return _loaded
_rendered += __salt__['file.read'](_temp_tpl_file)
__salt__['file.remove'](_temp_tpl_file)
else:
return _loaded # exit
loaded_config = _rendered
if _loaded['result']: # all good
fun = 'load_merge_candidate'
if replace: # replace requested
fun = 'load_replace_candidate'
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
fun,
**{
'config': _rendered
}
)
else:
salt.utils.versions.warn_until(
'Sodium',
'Native NAPALM templates support will be removed in the Sodium '
'release. Please consider using the Salt rendering pipeline instead.'
'If you are using the \'netntp\', \'netsnmp\', or \'netusers\' Salt '
'State modules, you can ignore this message'
)
# otherwise, use NAPALM render system, injecting pillar/grains/opts vars
load_templates_params = defaults if defaults else {}
load_templates_params.update(template_vars)
load_templates_params.update(
{
'template_name': template_name,
'template_source': template_source, # inline template
'pillar': __pillar__, # inject pillar content
'grains': __grains__, # inject grains content
'opts': __opts__ # inject opts content
}
)
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
# so we'll set the CLOSE global explicitly as False
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'load_template',
**load_templates_params
)
return _config_logic(napalm_device, # pylint: disable=undefined-variable
_loaded,
test=test,
debug=debug,
replace=replace,
commit_config=commit,
loaded_config=loaded_config,
commit_at=commit_at,
commit_in=commit_in,
revert_in=revert_in,
revert_at=revert_at,
**template_vars)
@salt.utils.napalm.proxy_napalm_wrap
def commit(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Commits the configuration changes made on the network device.
CLI Example:
.. code-block:: bash
salt '*' net.commit
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'commit_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def discard_config(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
"""
Discards the changes applied.
CLI Example:
.. code-block:: bash
salt '*' net.discard_config
"""
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'discard_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def compare_config(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Returns the difference between the running config and the candidate config.
CLI Example:
.. code-block:: bash
salt '*' net.compare_config
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'compare_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def rollback(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Rollbacks the configuration.
CLI Example:
.. code-block:: bash
salt '*' net.rollback
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'rollback',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def config_changed(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Will prompt if the configuration has been changed.
:return: A tuple with a boolean that specifies if the config was changed on the device.\
And a string that provides more details of the reason why the configuration was not changed.
CLI Example:
.. code-block:: bash
salt '*' net.config_changed
'''
is_config_changed = False
reason = ''
try_compare = compare_config(inherit_napalm_device=napalm_device) # pylint: disable=undefined-variable
if try_compare.get('result'):
if try_compare.get('out'):
is_config_changed = True
else:
reason = 'Configuration was not changed on the device.'
else:
reason = try_compare.get('comment')
return is_config_changed, reason
@salt.utils.napalm.proxy_napalm_wrap
def config_control(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Will check if the configuration was changed.
If differences found, will try to commit.
In case commit unsuccessful, will try to rollback.
:return: A tuple with a boolean that specifies if the config was changed/committed/rollbacked on the device.\
And a string that provides more details of the reason why the configuration was not committed properly.
CLI Example:
.. code-block:: bash
salt '*' net.config_control
'''
result = True
comment = ''
changed, not_changed_rsn = config_changed(inherit_napalm_device=napalm_device) # pylint: disable=undefined-variable
if not changed:
return (changed, not_changed_rsn)
# config changed, thus let's try to commit
try_commit = commit()
if not try_commit.get('result'):
result = False
comment = 'Unable to commit the changes: {reason}.\n\
Will try to rollback now!'.format(
reason=try_commit.get('comment')
)
try_rollback = rollback()
if not try_rollback.get('result'):
comment += '\nCannot rollback! {reason}'.format(
reason=try_rollback.get('comment')
)
return result, comment
def cancel_commit(jid):
'''
.. versionadded:: 2019.2.0
Cancel a commit scheduled to be executed via the ``commit_in`` and
``commit_at`` arguments from the
:py:func:`net.load_template <salt.modules.napalm_network.load_template>` or
:py:func:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit ID is displayed when the commit is scheduled
via the functions named above.
CLI Example:
.. code-block:: bash
salt '*' net.cancel_commit 20180726083540640360
'''
job_name = '__napalm_commit_{}'.format(jid)
removed = __salt__['schedule.delete'](job_name)
if removed['result']:
saved = __salt__['schedule.save']()
removed['comment'] = 'Commit #{jid} cancelled.'.format(jid=jid)
else:
removed['comment'] = 'Unable to find commit #{jid}.'.format(jid=jid)
return removed
def confirm_commit(jid):
'''
.. versionadded:: 2019.2.0
Confirm a commit scheduled to be reverted via the ``revert_in`` and
``revert_at`` arguments from the
:mod:`net.load_template <salt.modules.napalm_network.load_template>` or
:mod:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit ID is displayed when the commit confirmed
is scheduled via the functions named above.
CLI Example:
.. code-block:: bash
salt '*' net.confirm_commit 20180726083540640360
'''
if __grains__['os'] == 'junos':
# Confirm the commit, by committing (i.e., invoking the RPC call)
confirmed = __salt__['napalm.junos_commit']()
confirmed['result'] = confirmed.pop('out')
confirmed['comment'] = confirmed.pop('message')
else:
confirmed = cancel_commit(jid)
if confirmed['result']:
confirmed['comment'] = 'Commit #{jid} confirmed.'.format(jid=jid)
return confirmed
def save_config(source=None,
path=None):
'''
.. versionadded:: 2019.2.0
Save the configuration to a file on the local file system.
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``,
``startup``. Default: ``running``.
path
Absolute path to file where to save the configuration.
To push the files to the Master, use
:mod:`cp.push <salt.modules.cp.push>` Execution function.
CLI Example:
.. code-block:: bash
salt '*' net.save_config source=running
'''
if not source:
source = 'running'
if not path:
path = salt.utils.files.mkstemp()
running_config = __salt__['net.config'](source=source)
if not running_config or not running_config['result']:
log.error('Unable to retrieve the config')
return running_config
with salt.utils.files.fopen(path, 'w') as fh_:
fh_.write(running_config['out'][source])
return {
'result': True,
'out': path,
'comment': '{source} config saved to {path}'.format(source=source, path=path)
}
def replace_pattern(pattern,
repl,
count=0,
flags=8,
bufsize=1,
append_if_not_found=False,
prepend_if_not_found=False,
not_found_content=None,
search_only=False,
show_changes=True,
backslash_literal=False,
source=None,
path=None,
test=False,
replace=True,
debug=False,
commit=True):
'''
.. versionadded:: 2019.2.0
Replace occurrences of a pattern in the configuration source. If
``show_changes`` is ``True``, then a diff of what changed will be returned,
otherwise a ``True`` will be returned when changes are made, and ``False``
when no changes are made.
This is a pure Python implementation that wraps Python's :py:func:`~re.sub`.
pattern
A regular expression, to be matched using Python's
:py:func:`~re.search`.
repl
The replacement text.
count: ``0``
Maximum number of pattern occurrences to be replaced. If count is a
positive integer ``n``, only ``n`` occurrences will be replaced,
otherwise all occurrences will be replaced.
flags (list or int): ``8``
A list of flags defined in the ``re`` module documentation from the
Python standard library. Each list item should be a string that will
correlate to the human-friendly flag name. E.g., ``['IGNORECASE',
'MULTILINE']``. Optionally, ``flags`` may be an int, with a value
corresponding to the XOR (``|``) of all the desired flags. Defaults to
8 (which supports 'MULTILINE').
bufsize (int or str): ``1``
How much of the configuration to buffer into memory at once. The
default value ``1`` processes one line at a time. The special value
``file`` may be specified which will read the entire file into memory
before processing.
append_if_not_found: ``False``
If set to ``True``, and pattern is not found, then the content will be
appended to the file.
prepend_if_not_found: ``False``
If set to ``True`` and pattern is not found, then the content will be
prepended to the file.
not_found_content
Content to use for append/prepend if not found. If None (default), uses
``repl``. Useful when ``repl`` uses references to group in pattern.
search_only: ``False``
If set to true, this no changes will be performed on the file, and this
function will simply return ``True`` if the pattern was matched, and
``False`` if not.
show_changes: ``True``
If ``True``, return a diff of changes made. Otherwise, return ``True``
if changes were made, and ``False`` if not.
backslash_literal: ``False``
Interpret backslashes as literal backslashes for the repl and not
escape characters. This will help when using append/prepend so that
the backslashes are not interpreted for the repl on the second run of
the state.
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path
Save the temporary configuration to a specific path, then read from
there.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' net.replace_pattern "bind-address\\s*=" "bind-address:"
CLI Example:
.. code-block:: bash
salt '*' net.replace_pattern PREFIX-LIST_NAME new-prefix-list-name
salt '*' net.replace_pattern bgp-group-name new-bgp-group-name count=1
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
replace_pattern = __salt__['file.replace'](path,
pattern,
repl,
count=count,
flags=flags,
bufsize=bufsize,
append_if_not_found=append_if_not_found,
prepend_if_not_found=prepend_if_not_found,
not_found_content=not_found_content,
search_only=search_only,
show_changes=show_changes,
backslash_literal=backslash_literal)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
def blockreplace(marker_start,
marker_end,
content='',
append_if_not_found=False,
prepend_if_not_found=False,
show_changes=True,
append_newline=False,
source='running',
path=None,
test=False,
commit=True,
debug=False,
replace=True):
'''
.. versionadded:: 2019.2.0
Replace content of the configuration source, delimited by the line markers.
A block of content delimited by comments can help you manage several lines
without worrying about old entries removal.
marker_start
The line content identifying a line as the start of the content block.
Note that the whole line containing this marker will be considered,
so whitespace or extra content before or after the marker is included
in final output.
marker_end
The line content identifying a line as the end of the content block.
Note that the whole line containing this marker will be considered,
so whitespace or extra content before or after the marker is included
in final output.
content
The content to be used between the two lines identified by
``marker_start`` and ``marker_stop``.
append_if_not_found: ``False``
If markers are not found and set to True then, the markers and content
will be appended to the file.
prepend_if_not_found: ``False``
If markers are not found and set to True then, the markers and content
will be prepended to the file.
append_newline: ``False``
Controls whether or not a newline is appended to the content block.
If the value of this argument is ``True`` then a newline will be added
to the content block. If it is ``False``, then a newline will not be
added to the content block. If it is ``None`` then a newline will only
be added to the content block if it does not already end in a newline.
show_changes: ``True``
Controls how changes are presented. If ``True``, this function will
return the of the changes made.
If ``False``, then it will return a boolean (``True`` if any changes
were made, otherwise False).
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path: ``None``
Save the temporary configuration to a specific path, then read from
there. This argument is optional, can be used when you prefers a
particular location of the temporary file.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
CLI Example:
.. code-block:: bash
salt '*' net.blockreplace 'ntp' 'interface' ''
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
replace_pattern = __salt__['file.blockreplace'](path,
marker_start=marker_start,
marker_end=marker_end,
content=content,
append_if_not_found=append_if_not_found,
prepend_if_not_found=prepend_if_not_found,
show_changes=show_changes,
append_newline=append_newline)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
def patch(patchfile,
options='',
saltenv='base',
source_hash=None,
show_changes=True,
source='running',
path=None,
test=False,
commit=True,
debug=False,
replace=True):
'''
.. versionadded:: 2019.2.0
Apply a patch to the configuration source, and load the result into the
running config of the device.
patchfile
A patch file to apply to the configuration source.
options
Options to pass to patch.
source_hash
If the patch file (specified via the ``patchfile`` argument) is an
HTTP(S) or FTP URL and the file exists in the minion's file cache, this
option can be passed to keep the minion from re-downloading the file if
the cached copy matches the specified hash.
show_changes: ``True``
Controls how changes are presented. If ``True``, this function will
return the of the changes made.
If ``False``, then it will return a boolean (``True`` if any changes
were made, otherwise False).
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path: ``None``
Save the temporary configuration to a specific path, then read from
there. This argument is optional, can the user prefers a particular
location of the temporary file.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
CLI Example:
.. code-block:: bash
salt '*' net.patch https://example.com/running_config.patch
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
patchfile_cache = __salt__['cp.cache_file'](patchfile)
if patchfile_cache is False:
return {
'out': None,
'result': False,
'comment': 'The file "{}" does not exist.'.format(patchfile)
}
replace_pattern = __salt__['file.patch'](path,
patchfile_cache,
options=options)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
# <---- Configuration specific functions -------------------------------------------------------------------------------
|
saltstack/salt
|
salt/modules/napalm_network.py
|
traceroute
|
python
|
def traceroute(destination, source=None, ttl=None, timeout=None, vrf=None, **kwargs): # pylint: disable=unused-argument
'''
Calls the method traceroute from the NAPALM driver object and returns a dictionary with the result of the traceroute
command executed on the device.
destination
Hostname or address of remote host
source
Source address to use in outgoing traceroute packets
ttl
IP maximum time-to-live value (or IPv6 maximum hop-limit value)
timeout
Number of seconds to wait for response (seconds)
vrf
VRF (routing instance) for traceroute attempt
.. versionadded:: 2016.11.4
CLI Example:
.. code-block:: bash
salt '*' net.traceroute 8.8.8.8
salt '*' net.traceroute 8.8.8.8 source=127.0.0.1 ttl=5 timeout=1
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'traceroute',
**{
'destination': destination,
'source': source,
'ttl': ttl,
'timeout': timeout,
'vrf': vrf
}
)
|
Calls the method traceroute from the NAPALM driver object and returns a dictionary with the result of the traceroute
command executed on the device.
destination
Hostname or address of remote host
source
Source address to use in outgoing traceroute packets
ttl
IP maximum time-to-live value (or IPv6 maximum hop-limit value)
timeout
Number of seconds to wait for response (seconds)
vrf
VRF (routing instance) for traceroute attempt
.. versionadded:: 2016.11.4
CLI Example:
.. code-block:: bash
salt '*' net.traceroute 8.8.8.8
salt '*' net.traceroute 8.8.8.8 source=127.0.0.1 ttl=5 timeout=1
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_network.py#L787-L828
|
[
"def call(napalm_device, method, *args, **kwargs):\n '''\n Calls arbitrary methods from the network driver instance.\n Please check the readthedocs_ page for the updated list of getters.\n\n .. _readthedocs: http://napalm.readthedocs.org/en/latest/support/index.html#getters-support-matrix\n\n method\n Specifies the name of the method to be called.\n\n *args\n Arguments.\n\n **kwargs\n More arguments.\n\n :return: A dictionary with three keys:\n\n * result (True/False): if the operation succeeded\n * out (object): returns the object as-is from the call\n * comment (string): provides more details in case the call failed\n * traceback (string): complete traceback in case of exception. \\\n Please submit an issue including this traceback \\\n on the `correct driver repo`_ and make sure to read the FAQ_\n\n .. _`correct driver repo`: https://github.com/napalm-automation/napalm/issues/new\n .. FAQ_: https://github.com/napalm-automation/napalm#faq\n\n Example:\n\n .. code-block:: python\n\n salt.utils.napalm.call(\n napalm_object,\n 'cli',\n [\n 'show version',\n 'show chassis fan'\n ]\n )\n '''\n result = False\n out = None\n opts = napalm_device.get('__opts__', {})\n retry = kwargs.pop('__retry', True) # retry executing the task?\n force_reconnect = kwargs.get('force_reconnect', False)\n if force_reconnect:\n log.debug('Forced reconnection initiated')\n log.debug('The current opts (under the proxy key):')\n log.debug(opts['proxy'])\n opts['proxy'].update(**kwargs)\n log.debug('Updated to:')\n log.debug(opts['proxy'])\n napalm_device = get_device(opts)\n try:\n if not napalm_device.get('UP', False):\n raise Exception('not connected')\n # if connected will try to execute desired command\n kwargs_copy = {}\n kwargs_copy.update(kwargs)\n for karg, warg in six.iteritems(kwargs_copy):\n # lets clear None arguments\n # to not be sent to NAPALM methods\n if warg is None:\n kwargs.pop(karg)\n out = getattr(napalm_device.get('DRIVER'), method)(*args, **kwargs)\n # calls the method with the specified parameters\n result = True\n except Exception as error:\n # either not connected\n # either unable to execute the command\n hostname = napalm_device.get('HOSTNAME', '[unspecified hostname]')\n err_tb = traceback.format_exc() # let's get the full traceback and display for debugging reasons.\n if isinstance(error, NotImplementedError):\n comment = '{method} is not implemented for the NAPALM {driver} driver!'.format(\n method=method,\n driver=napalm_device.get('DRIVER_NAME')\n )\n elif retry and HAS_CONN_CLOSED_EXC_CLASS and isinstance(error, ConnectionClosedException):\n # Received disconection whilst executing the operation.\n # Instructed to retry (default behaviour)\n # thus trying to re-establish the connection\n # and re-execute the command\n # if any of the operations (close, open, call) will rise again ConnectionClosedException\n # it will fail loudly.\n kwargs['__retry'] = False # do not attempt re-executing\n comment = 'Disconnected from {device}. Trying to reconnect.'.format(device=hostname)\n log.error(err_tb)\n log.error(comment)\n log.debug('Clearing the connection with %s', hostname)\n call(napalm_device, 'close', __retry=False) # safely close the connection\n # Make sure we don't leave any TCP connection open behind\n # if we fail to close properly, we might not be able to access the\n log.debug('Re-opening the connection with %s', hostname)\n call(napalm_device, 'open', __retry=False)\n log.debug('Connection re-opened with %s', hostname)\n log.debug('Re-executing %s', method)\n return call(napalm_device, method, *args, **kwargs)\n # If still not able to reconnect and execute the task,\n # the proxy keepalive feature (if enabled) will attempt\n # to reconnect.\n # If the device is using a SSH-based connection, the failure\n # will also notify the paramiko transport and the `is_alive` flag\n # is going to be set correctly.\n # More background: the network device may decide to disconnect,\n # although the SSH session itself is alive and usable, the reason\n # being the lack of activity on the CLI.\n # Paramiko's keepalive doesn't help in this case, as the ServerAliveInterval\n # are targeting the transport layer, whilst the device takes the decision\n # when there isn't any activity on the CLI, thus at the application layer.\n # Moreover, the disconnect is silent and paramiko's is_alive flag will\n # continue to return True, although the connection is already unusable.\n # For more info, see https://github.com/paramiko/paramiko/issues/813.\n # But after a command fails, the `is_alive` flag becomes aware of these\n # changes and will return False from there on. And this is how the\n # Salt proxy keepalive helps: immediately after the first failure, it\n # will know the state of the connection and will try reconnecting.\n else:\n comment = 'Cannot execute \"{method}\" on {device}{port} as {user}. Reason: {error}!'.format(\n device=napalm_device.get('HOSTNAME', '[unspecified hostname]'),\n port=(':{port}'.format(port=napalm_device.get('OPTIONAL_ARGS', {}).get('port'))\n if napalm_device.get('OPTIONAL_ARGS', {}).get('port') else ''),\n user=napalm_device.get('USERNAME', ''),\n method=method,\n error=error\n )\n log.error(comment)\n log.error(err_tb)\n return {\n 'out': {},\n 'result': False,\n 'comment': comment,\n 'traceback': err_tb\n }\n finally:\n if opts and not_always_alive(opts) and napalm_device.get('CLOSE', True):\n # either running in a not-always-alive proxy\n # either running in a regular minion\n # close the connection when the call is over\n # unless the CLOSE is explicitly set as False\n napalm_device['DRIVER'].close()\n return {\n 'out': out,\n 'result': result,\n 'comment': ''\n }\n"
] |
# -*- coding: utf-8 -*-
'''
NAPALM Network
==============
Basic methods for interaction with the network device through the virtual proxy 'napalm'.
:codeauthor: Mircea Ulinic <mircea@cloudflare.com> & Jerome Fleury <jf@cloudflare.com>
:maturity: new
:depends: napalm
:platform: unix
Dependencies
------------
- :mod:`napalm proxy minion <salt.proxy.napalm>`
.. versionadded:: 2016.11.0
.. versionchanged:: 2017.7.0
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import time
import logging
import datetime
log = logging.getLogger(__name__)
# Import Salt libs
from salt.ext import six
import salt.utils.files
import salt.utils.napalm
import salt.utils.versions
import salt.utils.templates
# Import 3rd-party libs
try:
import jxmlease # pylint: disable=unused-import
HAS_JXMLEASE = True
except ImportError:
HAS_JXMLEASE = False
# ----------------------------------------------------------------------------------------------------------------------
# module properties
# ----------------------------------------------------------------------------------------------------------------------
__virtualname__ = 'net'
__proxyenabled__ = ['*']
__virtual_aliases__ = ('napalm_net',)
# uses NAPALM-based proxy to interact with network devices
# ----------------------------------------------------------------------------------------------------------------------
# property functions
# ----------------------------------------------------------------------------------------------------------------------
def __virtual__():
'''
NAPALM library must be installed for this module to work and run in a (proxy) minion.
'''
return salt.utils.napalm.virtual(__opts__, __virtualname__, __file__)
# ----------------------------------------------------------------------------------------------------------------------
# helper functions -- will not be exported
# ----------------------------------------------------------------------------------------------------------------------
def _filter_list(input_list, search_key, search_value):
'''
Filters a list of dictionary by a set of key-value pair.
:param input_list: is a list of dictionaries
:param search_key: is the key we are looking for
:param search_value: is the value we are looking for the key specified in search_key
:return: filered list of dictionaries
'''
output_list = list()
for dictionary in input_list:
if dictionary.get(search_key) == search_value:
output_list.append(dictionary)
return output_list
def _filter_dict(input_dict, search_key, search_value):
'''
Filters a dictionary of dictionaries by a key-value pair.
:param input_dict: is a dictionary whose values are lists of dictionaries
:param search_key: is the key in the leaf dictionaries
:param search_values: is the value in the leaf dictionaries
:return: filtered dictionary
'''
output_dict = dict()
for key, key_list in six.iteritems(input_dict):
key_list_filtered = _filter_list(key_list, search_key, search_value)
if key_list_filtered:
output_dict[key] = key_list_filtered
return output_dict
def _safe_commit_config(loaded_result, napalm_device):
_commit = commit(inherit_napalm_device=napalm_device) # calls the function commit, defined below
if not _commit.get('result', False):
# if unable to commit
loaded_result['comment'] += _commit['comment'] if _commit.get('comment') else 'Unable to commit.'
loaded_result['result'] = False
# unable to commit, something went wrong
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
return _commit
def _safe_dicard_config(loaded_result, napalm_device):
'''
'''
log.debug('Discarding the config')
log.debug(loaded_result)
_discarded = discard_config(inherit_napalm_device=napalm_device)
if not _discarded.get('result', False):
loaded_result['comment'] += _discarded['comment'] if _discarded.get('comment') \
else 'Unable to discard config.'
loaded_result['result'] = False
# make sure it notifies
# that something went wrong
_explicit_close(napalm_device)
__context__['retcode'] = 1
return loaded_result
return _discarded
def _explicit_close(napalm_device):
'''
Will explicily close the config session with the network device,
when running in a now-always-alive proxy minion or regular minion.
This helper must be used in configuration-related functions,
as the session is preserved and not closed before making any changes.
'''
if salt.utils.napalm.not_always_alive(__opts__):
# force closing the configuration session
# when running in a non-always-alive proxy
# or regular minion
try:
napalm_device['DRIVER'].close()
except Exception as err:
log.error('Unable to close the temp connection with the device:')
log.error(err)
log.error('Please report.')
def _config_logic(napalm_device,
loaded_result,
test=False,
debug=False,
replace=False,
commit_config=True,
loaded_config=None,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
commit_jid=None,
**kwargs):
'''
Builds the config logic for `load_config` and `load_template` functions.
'''
# As the Salt logic is built around independent events
# when it comes to configuration changes in the
# candidate DB on the network devices, we need to
# make sure we're using the same session.
# Hence, we need to pass the same object around.
# the napalm_device object is inherited from
# the load_config or load_template functions
# and forwarded to compare, discard, commit etc.
# then the decorator will make sure that
# if not proxy (when the connection is always alive)
# and the `inherit_napalm_device` is set,
# `napalm_device` will be overridden.
# See `salt.utils.napalm.proxy_napalm_wrap` decorator.
current_jid = kwargs.get('__pub_jid')
if not current_jid:
current_jid = '{0:%Y%m%d%H%M%S%f}'.format(datetime.datetime.now())
loaded_result['already_configured'] = False
loaded_result['loaded_config'] = ''
if debug:
loaded_result['loaded_config'] = loaded_config
_compare = compare_config(inherit_napalm_device=napalm_device)
if _compare.get('result', False):
loaded_result['diff'] = _compare.get('out')
loaded_result.pop('out', '') # not needed
else:
loaded_result['diff'] = None
loaded_result['result'] = False
loaded_result['comment'] = _compare.get('comment')
__context__['retcode'] = 1
return loaded_result
_loaded_res = loaded_result.get('result', False)
if not _loaded_res or test:
# if unable to load the config (errors / warnings)
# or in testing mode,
# will discard the config
if loaded_result['comment']:
loaded_result['comment'] += '\n'
if not loaded_result.get('diff', ''):
loaded_result['already_configured'] = True
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
loaded_result['comment'] += 'Configuration discarded.'
# loaded_result['result'] = False not necessary
# as the result can be true when test=True
_explicit_close(napalm_device)
if not loaded_result['result']:
__context__['retcode'] = 1
return loaded_result
if not test and commit_config:
# if not in testing mode and trying to commit
if commit_jid:
log.info('Committing the JID: %s', str(commit_jid))
removed = cancel_commit(commit_jid)
log.debug('Cleaned up the commit from the schedule')
log.debug(removed['comment'])
if loaded_result.get('diff', ''):
# if not testing mode
# and also the user wants to commit (default)
# and there are changes to commit
if commit_in or commit_at:
commit_time = __utils__['timeutil.get_time_at'](time_in=commit_in,
time_at=commit_in)
# schedule job
scheduled_job_name = '__napalm_commit_{}'.format(current_jid)
temp_file = salt.utils.files.mkstemp()
with salt.utils.files.fopen(temp_file, 'w') as fp_:
fp_.write(loaded_config)
scheduled = __salt__['schedule.add'](scheduled_job_name,
function='net.load_config',
job_kwargs={
'filename': temp_file,
'commit_jid': current_jid,
'replace': replace
},
once=commit_time)
log.debug('Scheduling job')
log.debug(scheduled)
saved = __salt__['schedule.save']() # ensure the schedule is
# persistent cross Minion restart
discarded = _safe_dicard_config(loaded_result, napalm_device)
# discard the changes
if not discarded['result']:
discarded['comment'] += ('Scheduled the job to be executed at {schedule_ts}, '
'but was unable to discard the config: \n').format(schedule_ts=commit_time)
return discarded
loaded_result['comment'] = ('Changes discarded for now, and scheduled commit at: {schedule_ts}.\n'
'The commit ID is: {current_jid}.\n'
'To discard this commit, you can execute: \n\n'
'salt {min_id} net.cancel_commit {current_jid}').format(schedule_ts=commit_time,
min_id=__opts__['id'],
current_jid=current_jid)
loaded_result['commit_id'] = current_jid
return loaded_result
log.debug('About to commit:')
log.debug(loaded_result['diff'])
if revert_in or revert_at:
revert_time = __utils__['timeutil.get_time_at'](time_in=revert_in,
time_at=revert_at)
if __grains__['os'] == 'junos':
if not HAS_JXMLEASE:
loaded_result['comment'] = ('This feature requires the library jxmlease to be installed.\n'
'To install, please execute: ``pip install jxmlease``.')
loaded_result['result'] = False
return loaded_result
timestamp_at = __utils__['timeutil.get_timestamp_at'](time_in=revert_in,
time_at=revert_at)
minutes = int((timestamp_at - time.time())/60)
_comm = __salt__['napalm.junos_commit'](confirm=minutes)
if not _comm['out']:
# If unable to commit confirm, should try to bail out
loaded_result['comment'] = 'Unable to commit confirm: {}'.format(_comm['message'])
loaded_result['result'] = False
# But before exiting, we must gracefully discard the config
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
else:
temp_file = salt.utils.files.mkstemp()
running_config = __salt__['net.config'](source='running')['out']['running']
with salt.utils.files.fopen(temp_file, 'w') as fp_:
fp_.write(running_config)
committed = _safe_commit_config(loaded_result, napalm_device)
if not committed['result']:
# If unable to commit, dicard the config (which is
# already done by the _safe_commit_config function), and
# return with the command and other details.
return loaded_result
scheduled_job_name = '__napalm_commit_{}'.format(current_jid)
scheduled = __salt__['schedule.add'](scheduled_job_name,
function='net.load_config',
job_kwargs={
'filename': temp_file,
'commit_jid': current_jid,
'replace': True
},
once=revert_time)
log.debug('Scheduling commit confirmed')
log.debug(scheduled)
saved = __salt__['schedule.save']()
loaded_result['comment'] = ('The commit ID is: {current_jid}.\n'
'This commit will be reverted at: {schedule_ts}, unless confirmed.\n'
'To confirm the commit and avoid reverting, you can execute:\n\n'
'salt {min_id} net.confirm_commit {current_jid}').format(schedule_ts=revert_time,
min_id=__opts__['id'],
current_jid=current_jid)
loaded_result['commit_id'] = current_jid
return loaded_result
committed = _safe_commit_config(loaded_result, napalm_device)
if not committed['result']:
return loaded_result
else:
# would like to commit, but there's no change
# need to call discard_config() to release the config DB
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
loaded_result['already_configured'] = True
loaded_result['comment'] = 'Already configured.'
_explicit_close(napalm_device)
if not loaded_result['result']:
__context__['retcode'] = 1
return loaded_result
# ----------------------------------------------------------------------------------------------------------------------
# callable functions
# ----------------------------------------------------------------------------------------------------------------------
@salt.utils.napalm.proxy_napalm_wrap
def connected(**kwargs): # pylint: disable=unused-argument
'''
Specifies if the connection to the device succeeded.
CLI Example:
.. code-block:: bash
salt '*' net.connected
'''
return {
'out': napalm_device.get('UP', False) # pylint: disable=undefined-variable
}
@salt.utils.napalm.proxy_napalm_wrap
def facts(**kwargs): # pylint: disable=unused-argument
'''
Returns characteristics of the network device.
:return: a dictionary with the following keys:
* uptime - Uptime of the device in seconds.
* vendor - Manufacturer of the device.
* model - Device model.
* hostname - Hostname of the device
* fqdn - Fqdn of the device
* os_version - String with the OS version running on the device.
* serial_number - Serial number of the device
* interface_list - List of the interfaces of the device
CLI Example:
.. code-block:: bash
salt '*' net.facts
Example output:
.. code-block:: python
{
'os_version': '13.3R6.5',
'uptime': 10117140,
'interface_list': [
'lc-0/0/0',
'pfe-0/0/0',
'pfh-0/0/0',
'xe-0/0/0',
'xe-0/0/1',
'xe-0/0/2',
'xe-0/0/3',
'gr-0/0/10',
'ip-0/0/10'
],
'vendor': 'Juniper',
'serial_number': 'JN131356FBFA',
'model': 'MX480',
'hostname': 're0.edge05.syd01',
'fqdn': 're0.edge05.syd01'
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_facts',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def environment(**kwargs): # pylint: disable=unused-argument
'''
Returns the environment of the device.
CLI Example:
.. code-block:: bash
salt '*' net.environment
Example output:
.. code-block:: python
{
'fans': {
'Bottom Rear Fan': {
'status': True
},
'Bottom Middle Fan': {
'status': True
},
'Top Middle Fan': {
'status': True
},
'Bottom Front Fan': {
'status': True
},
'Top Front Fan': {
'status': True
},
'Top Rear Fan': {
'status': True
}
},
'memory': {
'available_ram': 16349,
'used_ram': 4934
},
'temperature': {
'FPC 0 Exhaust A': {
'is_alert': False,
'temperature': 35.0,
'is_critical': False
}
},
'cpu': {
'1': {
'%usage': 19.0
},
'0': {
'%usage': 35.0
}
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_environment',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def cli(*commands, **kwargs): # pylint: disable=unused-argument
'''
Returns a dictionary with the raw output of all commands passed as arguments.
commands
List of commands to be executed on the device.
textfsm_parse: ``False``
Try parsing the outputs using the TextFSM templates.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``napalm_cli_textfsm_parse``.
textfsm_path
The path where the TextFSM templates can be found. This option implies
the usage of the TextFSM index file.
``textfsm_path`` can be either absolute path on the server,
either specified using the following URL mschemes: ``file://``,
``salt://``, ``http://``, ``https://``, ``ftp://``,
``s3://``, ``swift://``.
.. versionadded:: 2018.3.0
.. note::
This needs to be a directory with a flat structure, having an
index file (whose name can be specified using the ``index_file`` option)
and a number of TextFSM templates.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_path``.
textfsm_template
The path to a certain the TextFSM template.
This can be specified using the absolute path
to the file, or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
.. versionadded:: 2018.3.0
textfsm_template_dict
A dictionary with the mapping between a command
and the corresponding TextFSM path to use to extract the data.
The TextFSM paths can be specified as in ``textfsm_template``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``napalm_cli_textfsm_template_dict``.
platform_grain_name: ``os``
The name of the grain used to identify the platform name
in the TextFSM index file. Default: ``os``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_grain``.
platform_column_name: ``Platform``
The column name used to identify the platform,
exactly as specified in the TextFSM index file.
Default: ``Platform``.
.. versionadded:: 2018.3.0
.. note::
This is field is case sensitive, make sure
to assign the correct value to this option,
exactly as defined in the index file.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_column_name``.
index_file: ``index``
The name of the TextFSM index file, under the ``textfsm_path``. Default: ``index``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_index_file``.
saltenv: ``base``
Salt fileserver envrionment from which to retrieve the file.
Ignored if ``textfsm_path`` is not a ``salt://`` URL.
.. versionadded:: 2018.3.0
include_empty: ``False``
Include empty files under the ``textfsm_path``.
.. versionadded:: 2018.3.0
include_pat
Glob or regex to narrow down the files cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. versionadded:: 2018.3.0
exclude_pat
Glob or regex to exclude certain files from being cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. versionadded:: 2018.3.0
.. note::
If used with ``include_pat``, files matching this pattern will be
excluded from the subset of files defined by ``include_pat``.
CLI Example:
.. code-block:: bash
salt '*' net.cli "show version" "show chassis fan"
CLI Example with TextFSM template:
.. code-block:: bash
salt '*' net.cli textfsm_parse=True textfsm_path=salt://textfsm/
Example output:
.. code-block:: python
{
'show version and haiku': 'Hostname: re0.edge01.arn01
Model: mx480
Junos: 13.3R6.5
Help me, Obi-Wan
I just saw Episode Two
You're my only hope
',
'show chassis fan' : 'Item Status RPM Measurement
Top Rear Fan OK 3840 Spinning at intermediate-speed
Bottom Rear Fan OK 3840 Spinning at intermediate-speed
Top Middle Fan OK 3900 Spinning at intermediate-speed
Bottom Middle Fan OK 3840 Spinning at intermediate-speed
Top Front Fan OK 3810 Spinning at intermediate-speed
Bottom Front Fan OK 3840 Spinning at intermediate-speed
'
}
Example output with TextFSM parsing:
.. code-block:: json
{
"comment": "",
"result": true,
"out": {
"sh ver": [
{
"kernel": "9.1S3.5",
"documentation": "9.1S3.5",
"boot": "9.1S3.5",
"crypto": "9.1S3.5",
"chassis": "",
"routing": "9.1S3.5",
"base": "9.1S3.5",
"model": "mx960"
}
]
}
}
'''
raw_cli_outputs = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'cli',
**{
'commands': list(commands)
}
)
# thus we can display the output as is
# in case of errors, they'll be catched in the proxy
if not raw_cli_outputs['result']:
# Error -> dispaly the output as-is.
return raw_cli_outputs
textfsm_parse = kwargs.get('textfsm_parse') or __opts__.get('napalm_cli_textfsm_parse') or\
__pillar__.get('napalm_cli_textfsm_parse', False)
if not textfsm_parse:
# No TextFSM parsing required, return raw commands.
log.debug('No TextFSM parsing requested.')
return raw_cli_outputs
if 'textfsm.extract' not in __salt__ or 'textfsm.index' not in __salt__:
raw_cli_outputs['comment'] += 'Unable to process: is TextFSM installed?'
log.error(raw_cli_outputs['comment'])
return raw_cli_outputs
textfsm_template = kwargs.get('textfsm_template')
log.debug('textfsm_template: %s', textfsm_template)
textfsm_path = kwargs.get('textfsm_path') or __opts__.get('textfsm_path') or\
__pillar__.get('textfsm_path')
log.debug('textfsm_path: %s', textfsm_path)
textfsm_template_dict = kwargs.get('textfsm_template_dict') or __opts__.get('napalm_cli_textfsm_template_dict') or\
__pillar__.get('napalm_cli_textfsm_template_dict', {})
log.debug('TextFSM command-template mapping: %s', textfsm_template_dict)
index_file = kwargs.get('index_file') or __opts__.get('textfsm_index_file') or\
__pillar__.get('textfsm_index_file')
log.debug('index_file: %s', index_file)
platform_grain_name = kwargs.get('platform_grain_name') or __opts__.get('textfsm_platform_grain') or\
__pillar__.get('textfsm_platform_grain', 'os')
log.debug('platform_grain_name: %s', platform_grain_name)
platform_column_name = kwargs.get('platform_column_name') or __opts__.get('textfsm_platform_column_name') or\
__pillar__.get('textfsm_platform_column_name', 'Platform')
log.debug('platform_column_name: %s', platform_column_name)
saltenv = kwargs.get('saltenv', 'base')
include_empty = kwargs.get('include_empty', False)
include_pat = kwargs.get('include_pat')
exclude_pat = kwargs.get('exclude_pat')
processed_cli_outputs = {
'comment': raw_cli_outputs.get('comment', ''),
'result': raw_cli_outputs['result'],
'out': {}
}
log.debug('Starting to analyse the raw outputs')
for command in list(commands):
command_output = raw_cli_outputs['out'][command]
log.debug('Output from command: %s', command)
log.debug(command_output)
processed_command_output = None
if textfsm_path:
log.debug('Using the templates under %s', textfsm_path)
processed_cli_output = __salt__['textfsm.index'](command,
platform_grain_name=platform_grain_name,
platform_column_name=platform_column_name,
output=command_output.strip(),
textfsm_path=textfsm_path,
saltenv=saltenv,
include_empty=include_empty,
include_pat=include_pat,
exclude_pat=exclude_pat)
log.debug('Processed CLI output:')
log.debug(processed_cli_output)
if not processed_cli_output['result']:
log.debug('Apparently this didnt work, returnin the raw output')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {0}: {1}.'.format(command,
processed_cli_output['comment'])
log.error(processed_cli_outputs['comment'])
elif processed_cli_output['out']:
log.debug('All good, %s has a nice output!', command)
processed_command_output = processed_cli_output['out']
else:
comment = '''\nProcessing "{}" didn't fail, but didn't return anything either. Dumping raw.'''.format(
command)
processed_cli_outputs['comment'] += comment
log.error(comment)
processed_command_output = command_output
elif textfsm_template or command in textfsm_template_dict:
if command in textfsm_template_dict:
textfsm_template = textfsm_template_dict[command]
log.debug('Using %s to process the command: %s', textfsm_template, command)
processed_cli_output = __salt__['textfsm.extract'](textfsm_template,
raw_text=command_output,
saltenv=saltenv)
log.debug('Processed CLI output:')
log.debug(processed_cli_output)
if not processed_cli_output['result']:
log.debug('Apparently this didnt work, returning '
'the raw output')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {0}: {1}'.format(command,
processed_cli_output['comment'])
log.error(processed_cli_outputs['comment'])
elif processed_cli_output['out']:
log.debug('All good, %s has a nice output!', command)
processed_command_output = processed_cli_output['out']
else:
log.debug('Processing %s didnt fail, but didnt return'
' anything either. Dumping raw.', command)
processed_command_output = command_output
else:
log.error('No TextFSM template specified, or no TextFSM path defined')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {}.'.format(command)
processed_cli_outputs['out'][command] = processed_command_output
processed_cli_outputs['comment'] = processed_cli_outputs['comment'].strip()
return processed_cli_outputs
@salt.utils.napalm.proxy_napalm_wrap
@salt.utils.napalm.proxy_napalm_wrap
def ping(destination, source=None, ttl=None, timeout=None, size=None, count=None, vrf=None, **kwargs): # pylint: disable=unused-argument
'''
Executes a ping on the network device and returns a dictionary as a result.
destination
Hostname or IP address of remote host
source
Source address of echo request
ttl
IP time-to-live value (IPv6 hop-limit value) (1..255 hops)
timeout
Maximum wait time after sending final packet (seconds)
size
Size of request packets (0..65468 bytes)
count
Number of ping requests to send (1..2000000000 packets)
vrf
VRF (routing instance) for ping attempt
.. versionadded:: 2016.11.4
CLI Example:
.. code-block:: bash
salt '*' net.ping 8.8.8.8
salt '*' net.ping 8.8.8.8 ttl=3 size=65468
salt '*' net.ping 8.8.8.8 source=127.0.0.1 timeout=1 count=100
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'ping',
**{
'destination': destination,
'source': source,
'ttl': ttl,
'timeout': timeout,
'size': size,
'count': count,
'vrf': vrf
}
)
@salt.utils.napalm.proxy_napalm_wrap
def arp(interface='', ipaddr='', macaddr='', **kwargs): # pylint: disable=unused-argument
'''
NAPALM returns a list of dictionaries with details of the ARP entries.
:param interface: interface name to filter on
:param ipaddr: IP address to filter on
:param macaddr: MAC address to filter on
:return: List of the entries in the ARP table
CLI Example:
.. code-block:: bash
salt '*' net.arp
salt '*' net.arp macaddr='5c:5e:ab:da:3c:f0'
Example output:
.. code-block:: python
[
{
'interface' : 'MgmtEth0/RSP0/CPU0/0',
'mac' : '5c:5e:ab:da:3c:f0',
'ip' : '172.17.17.1',
'age' : 1454496274.84
},
{
'interface': 'MgmtEth0/RSP0/CPU0/0',
'mac' : '66:0e:94:96:e0:ff',
'ip' : '172.17.17.2',
'age' : 1435641582.49
}
]
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_arp_table',
**{
}
)
if not proxy_output.get('result'):
return proxy_output
arp_table = proxy_output.get('out')
if interface:
arp_table = _filter_list(arp_table, 'interface', interface)
if ipaddr:
arp_table = _filter_list(arp_table, 'ip', ipaddr)
if macaddr:
arp_table = _filter_list(arp_table, 'mac', macaddr)
proxy_output.update({
'out': arp_table
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def ipaddrs(**kwargs): # pylint: disable=unused-argument
'''
Returns IP addresses configured on the device.
:return: A dictionary with the IPv4 and IPv6 addresses of the interfaces.
Returns all configured IP addresses on all interfaces as a dictionary
of dictionaries. Keys of the main dictionary represent the name of the
interface. Values of the main dictionary represent are dictionaries
that may consist of two keys 'ipv4' and 'ipv6' (one, both or none)
which are themselvs dictionaries with the IP addresses as keys.
CLI Example:
.. code-block:: bash
salt '*' net.ipaddrs
Example output:
.. code-block:: python
{
'FastEthernet8': {
'ipv4': {
'10.66.43.169': {
'prefix_length': 22
}
}
},
'Loopback555': {
'ipv4': {
'192.168.1.1': {
'prefix_length': 24
}
},
'ipv6': {
'1::1': {
'prefix_length': 64
},
'2001:DB8:1::1': {
'prefix_length': 64
},
'FE80::3': {
'prefix_length': 'N/A'
}
}
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_interfaces_ip',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def interfaces(**kwargs): # pylint: disable=unused-argument
'''
Returns details of the interfaces on the device.
:return: Returns a dictionary of dictionaries. The keys for the first
dictionary will be the interfaces in the devices.
CLI Example:
.. code-block:: bash
salt '*' net.interfaces
Example output:
.. code-block:: python
{
'Management1': {
'is_up': False,
'is_enabled': False,
'description': '',
'last_flapped': -1,
'speed': 1000,
'mac_address': 'dead:beef:dead',
},
'Ethernet1':{
'is_up': True,
'is_enabled': True,
'description': 'foo',
'last_flapped': 1429978575.1554043,
'speed': 1000,
'mac_address': 'beef:dead:beef',
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_interfaces',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def lldp(interface='', **kwargs): # pylint: disable=unused-argument
'''
Returns a detailed view of the LLDP neighbors.
:param interface: interface name to filter on
:return: A dictionary with the LLDL neighbors. The keys are the
interfaces with LLDP activated on.
CLI Example:
.. code-block:: bash
salt '*' net.lldp
salt '*' net.lldp interface='TenGigE0/0/0/8'
Example output:
.. code-block:: python
{
'TenGigE0/0/0/8': [
{
'parent_interface': 'Bundle-Ether8',
'interface_description': 'TenGigE0/0/0/8',
'remote_chassis_id': '8c60.4f69.e96c',
'remote_system_name': 'switch',
'remote_port': 'Eth2/2/1',
'remote_port_description': 'Ethernet2/2/1',
'remote_system_description': 'Cisco Nexus Operating System (NX-OS) Software 7.1(0)N1(1a)
TAC support: http://www.cisco.com/tac
Copyright (c) 2002-2015, Cisco Systems, Inc. All rights reserved.',
'remote_system_capab': 'B, R',
'remote_system_enable_capab': 'B'
}
]
}
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_lldp_neighbors_detail',
**{
}
)
if not proxy_output.get('result'):
return proxy_output
lldp_neighbors = proxy_output.get('out')
if interface:
lldp_neighbors = {interface: lldp_neighbors.get(interface)}
proxy_output.update({
'out': lldp_neighbors
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def mac(address='', interface='', vlan=0, **kwargs): # pylint: disable=unused-argument
'''
Returns the MAC Address Table on the device.
:param address: MAC address to filter on
:param interface: Interface name to filter on
:param vlan: VLAN identifier
:return: A list of dictionaries representing the entries in the MAC Address Table
CLI Example:
.. code-block:: bash
salt '*' net.mac
salt '*' net.mac vlan=10
Example output:
.. code-block:: python
[
{
'mac' : '00:1c:58:29:4a:71',
'interface' : 'xe-3/0/2',
'static' : False,
'active' : True,
'moves' : 1,
'vlan' : 10,
'last_move' : 1454417742.58
},
{
'mac' : '8c:60:4f:58:e1:c1',
'interface' : 'xe-1/0/1',
'static' : False,
'active' : True,
'moves' : 2,
'vlan' : 42,
'last_move' : 1453191948.11
}
]
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_mac_address_table',
**{
}
)
if not proxy_output.get('result'):
# if negative, leave the output unchanged
return proxy_output
mac_address_table = proxy_output.get('out')
if vlan and isinstance(vlan, int):
mac_address_table = _filter_list(mac_address_table, 'vlan', vlan)
if address:
mac_address_table = _filter_list(mac_address_table, 'mac', address)
if interface:
mac_address_table = _filter_list(mac_address_table, 'interface', interface)
proxy_output.update({
'out': mac_address_table
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def config(source=None, **kwargs): # pylint: disable=unused-argument
'''
.. versionadded:: 2017.7.0
Return the whole configuration of the network device. By default, it will
return all possible configuration sources supported by the network device.
At most, there will be:
- running config
- startup config
- candidate config
To return only one of the configurations, you can use the ``source``
argument.
source
Which configuration type you want to display, default is all of them.
Options:
- running
- candidate
- startup
:return:
The object returned is a dictionary with the following keys:
- running (string): Representation of the native running configuration.
- candidate (string): Representation of the native candidate configuration.
If the device doesn't differentiate between running and startup
configuration this will an empty string.
- startup (string): Representation of the native startup configuration.
If the device doesn't differentiate between running and startup
configuration this will an empty string.
CLI Example:
.. code-block:: bash
salt '*' net.config
salt '*' net.config source=candidate
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_config',
**{
'retrieve': source
}
)
@salt.utils.napalm.proxy_napalm_wrap
def optics(**kwargs): # pylint: disable=unused-argument
'''
.. versionadded:: 2017.7.0
Fetches the power usage on the various transceivers installed
on the network device (in dBm), and returns a view that conforms with the
OpenConfig model openconfig-platform-transceiver.yang.
:return:
Returns a dictionary where the keys are as listed below:
* intf_name (unicode)
* physical_channels
* channels (list of dicts)
* index (int)
* state
* input_power
* instant (float)
* avg (float)
* min (float)
* max (float)
* output_power
* instant (float)
* avg (float)
* min (float)
* max (float)
* laser_bias_current
* instant (float)
* avg (float)
* min (float)
* max (float)
CLI Example:
.. code-block:: bash
salt '*' net.optics
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_optics',
**{
}
)
# <---- Call NAPALM getters --------------------------------------------------------------------------------------------
# ----- Configuration specific functions ------------------------------------------------------------------------------>
@salt.utils.napalm.proxy_napalm_wrap
def load_config(filename=None,
text=None,
test=False,
commit=True,
debug=False,
replace=False,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
commit_jid=None,
inherit_napalm_device=None,
saltenv='base',
**kwargs): # pylint: disable=unused-argument
'''
Applies configuration changes on the device. It can be loaded from a file or from inline string.
If you send both a filename and a string containing the configuration, the file has higher precedence.
By default this function will commit the changes. If there are no changes, it does not commit and
the flag ``already_configured`` will be set as ``True`` to point this out.
To avoid committing the configuration, set the argument ``test`` to ``True`` and will discard (dry run).
To keep the changes but not commit, set ``commit`` to ``False``.
To replace the config, set ``replace`` to ``True``.
filename
Path to the file containing the desired configuration.
This can be specified using the absolute path to the file,
or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
.. versionchanged:: 2018.3.0
text
String containing the desired configuration.
This argument is ignored when ``filename`` is specified.
test: False
Dry run? If set as ``True``, will apply the config, discard and return the changes. Default: ``False``
and will commit the changes on the device.
commit: True
Commit? Default: ``True``.
debug: False
Debug mode. Will insert a new key under the output dictionary, as ``loaded_config`` containing the raw
configuration loaded on the device.
.. versionadded:: 2016.11.2
replace: False
Load and replace the configuration. Default: ``False``.
.. versionadded:: 2016.11.2
commit_in: ``None``
Commit the changes in a specific number of minutes / hours. Example of
accepted formats: ``5`` (commit in 5 minutes), ``2m`` (commit in 2
minutes), ``1h`` (commit the changes in 1 hour)`, ``5h30m`` (commit
the changes in 5 hours and 30 minutes).
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
commit_at: ``None``
Commit the changes at a specific time. Example of accepted formats:
``1am`` (will commit the changes at the next 1AM), ``13:20`` (will
commit at 13:20), ``1:20am``, etc.
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
revert_in: ``None``
Commit and revert the changes in a specific number of minutes / hours.
Example of accepted formats: ``5`` (revert in 5 minutes), ``2m`` (revert
in 2 minutes), ``1h`` (revert the changes in 1 hour)`, ``5h30m`` (revert
the changes in 5 hours and 30 minutes).
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
revert_at: ``None``
Commit and revert the changes at a specific time. Example of accepted
formats: ``1am`` (will commit and revert the changes at the next 1AM),
``13:20`` (will commit and revert at 13:20), ``1:20am``, etc.
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
saltenv: ``base``
Specifies the Salt environment name.
.. versionadded:: 2018.3.0
:return: a dictionary having the following keys:
* result (bool): if the config was applied successfully. It is ``False`` only in case of failure. In case \
there are no changes to be applied and successfully performs all operations it is still ``True`` and so will be \
the ``already_configured`` flag (example below)
* comment (str): a message for the user
* already_configured (bool): flag to check if there were no changes applied
* loaded_config (str): the configuration loaded on the device. Requires ``debug`` to be set as ``True``
* diff (str): returns the config changes applied
CLI Example:
.. code-block:: bash
salt '*' net.load_config text='ntp peer 192.168.0.1'
salt '*' net.load_config filename='/absolute/path/to/your/file'
salt '*' net.load_config filename='/absolute/path/to/your/file' test=True
salt '*' net.load_config filename='/absolute/path/to/your/file' commit=False
Example output:
.. code-block:: python
{
'comment': 'Configuration discarded.',
'already_configured': False,
'result': True,
'diff': '[edit interfaces xe-0/0/5]+ description "Adding a description";'
}
'''
fun = 'load_merge_candidate'
if replace:
fun = 'load_replace_candidate'
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
if filename:
text = __salt__['cp.get_file_str'](filename, saltenv=saltenv)
if text is False:
# When using salt:// or https://, if the resource is not available,
# it will either raise an exception, or return False.
ret = {
'result': False,
'out': None
}
ret['comment'] = 'Unable to read from {}. Please specify a valid file or text.'.format(filename)
log.error(ret['comment'])
return ret
if commit_jid:
# When the commit_jid argument is passed, it probably is a scheduled
# commit to be executed, and filename is a temporary file which
# can be removed after reading it.
salt.utils.files.safe_rm(filename)
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
fun,
**{
'config': text
}
)
return _config_logic(napalm_device, # pylint: disable=undefined-variable
_loaded,
test=test,
debug=debug,
replace=replace,
commit_config=commit,
loaded_config=text,
commit_at=commit_at,
commit_in=commit_in,
revert_in=revert_in,
revert_at=revert_at,
commit_jid=commit_jid,
**kwargs)
@salt.utils.napalm.proxy_napalm_wrap
def load_template(template_name=None,
template_source=None,
context=None,
defaults=None,
template_engine='jinja',
saltenv='base',
template_hash=None,
template_hash_name=None,
skip_verify=False,
test=False,
commit=True,
debug=False,
replace=False,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
inherit_napalm_device=None, # pylint: disable=unused-argument
**template_vars):
'''
Renders a configuration template (default: Jinja) and loads the result on the device.
By default this function will commit the changes. If there are no changes,
it does not commit, discards he config and the flag ``already_configured``
will be set as ``True`` to point this out.
To avoid committing the configuration, set the argument ``test`` to ``True``
and will discard (dry run).
To preserve the changes, set ``commit`` to ``False``.
However, this is recommended to be used only in exceptional cases
when there are applied few consecutive states
and/or configuration changes.
Otherwise the user might forget that the config DB is locked
and the candidate config buffer is not cleared/merged in the running config.
To replace the config, set ``replace`` to ``True``.
template_name
Identifies path to the template source.
The template can be either stored on the local machine, either remotely.
The recommended location is under the ``file_roots``
as specified in the master config file.
For example, let's suppose the ``file_roots`` is configured as:
.. code-block:: yaml
file_roots:
base:
- /etc/salt/states
Placing the template under ``/etc/salt/states/templates/example.jinja``,
it can be used as ``salt://templates/example.jinja``.
Alternatively, for local files, the user can specify the absolute path.
If remotely, the source can be retrieved via ``http``, ``https`` or ``ftp``.
Examples:
- ``salt://my_template.jinja``
- ``/absolute/path/to/my_template.jinja``
- ``http://example.com/template.cheetah``
- ``https:/example.com/template.mako``
- ``ftp://example.com/template.py``
.. versionchanged:: 2019.2.0
This argument can now support a list of templates to be rendered.
The resulting configuration text is loaded at once, as a single
configuration chunk.
template_source: None
Inline config template to be rendered and loaded on the device.
template_hash: None
Hash of the template file. Format: ``{hash_type: 'md5', 'hsum': <md5sum>}``
.. versionadded:: 2016.11.2
context: None
Overrides default context variables passed to the template.
.. versionadded:: 2019.2.0
template_hash_name: None
When ``template_hash`` refers to a remote file,
this specifies the filename to look for in that file.
.. versionadded:: 2016.11.2
saltenv: ``base``
Specifies the template environment.
This will influence the relative imports inside the templates.
.. versionadded:: 2016.11.2
template_engine: jinja
The following templates engines are supported:
- :mod:`cheetah<salt.renderers.cheetah>`
- :mod:`genshi<salt.renderers.genshi>`
- :mod:`jinja<salt.renderers.jinja>`
- :mod:`mako<salt.renderers.mako>`
- :mod:`py<salt.renderers.py>`
- :mod:`wempy<salt.renderers.wempy>`
.. versionadded:: 2016.11.2
skip_verify: True
If ``True``, hash verification of remote file sources
(``http://``, ``https://``, ``ftp://``) will be skipped,
and the ``source_hash`` argument will be ignored.
.. versionadded:: 2016.11.2
test: False
Dry run? If set to ``True``, will apply the config,
discard and return the changes.
Default: ``False`` and will commit the changes on the device.
commit: True
Commit? (default: ``True``)
debug: False
Debug mode. Will insert a new key under the output dictionary,
as ``loaded_config`` containing the raw result after the template was rendered.
.. versionadded:: 2016.11.2
replace: False
Load and replace the configuration.
.. versionadded:: 2016.11.2
commit_in: ``None``
Commit the changes in a specific number of minutes / hours. Example of
accepted formats: ``5`` (commit in 5 minutes), ``2m`` (commit in 2
minutes), ``1h`` (commit the changes in 1 hour)`, ``5h30m`` (commit
the changes in 5 hours and 30 minutes).
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
commit_at: ``None``
Commit the changes at a specific time. Example of accepted formats:
``1am`` (will commit the changes at the next 1AM), ``13:20`` (will
commit at 13:20), ``1:20am``, etc.
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
revert_in: ``None``
Commit and revert the changes in a specific number of minutes / hours.
Example of accepted formats: ``5`` (revert in 5 minutes), ``2m`` (revert
in 2 minutes), ``1h`` (revert the changes in 1 hour)`, ``5h30m`` (revert
the changes in 5 hours and 30 minutes).
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
revert_at: ``None``
Commit and revert the changes at a specific time. Example of accepted
formats: ``1am`` (will commit and revert the changes at the next 1AM),
``13:20`` (will commit and revert at 13:20), ``1:20am``, etc.
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
defaults: None
Default variables/context passed to the template.
.. versionadded:: 2016.11.2
template_vars
Dictionary with the arguments/context to be used when the template is rendered.
.. note::
Do not explicitly specify this argument. This represents any other
variable that will be sent to the template rendering system.
Please see the examples below!
.. note::
It is more recommended to use the ``context`` argument to avoid
conflicts between CLI arguments and template variables.
:return: a dictionary having the following keys:
- result (bool): if the config was applied successfully. It is ``False``
only in case of failure. In case there are no changes to be applied and
successfully performs all operations it is still ``True`` and so will be
the ``already_configured`` flag (example below)
- comment (str): a message for the user
- already_configured (bool): flag to check if there were no changes applied
- loaded_config (str): the configuration loaded on the device, after
rendering the template. Requires ``debug`` to be set as ``True``
- diff (str): returns the config changes applied
The template can use variables from the ``grains``, ``pillar`` or ``opts``, for example:
.. code-block:: jinja
{% set router_model = grains.get('model') -%}
{% set router_vendor = grains.get('vendor') -%}
{% set os_version = grains.get('version') -%}
{% set hostname = pillar.get('proxy', {}).get('host') -%}
{% if router_vendor|lower == 'juniper' %}
system {
host-name {{hostname}};
}
{% elif router_vendor|lower == 'cisco' %}
hostname {{hostname}}
{% endif %}
CLI Examples:
.. code-block:: bash
salt '*' net.load_template set_ntp_peers peers=[192.168.0.1] # uses NAPALM default templates
# inline template:
salt -G 'os:junos' net.load_template template_source='system { host-name {{host_name}}; }' \
host_name='MX480.lab'
# inline template using grains info:
salt -G 'os:junos' net.load_template \
template_source='system { host-name {{grains.model}}.lab; }'
# if the device is a MX480, the command above will set the hostname as: MX480.lab
# inline template using pillar data:
salt -G 'os:junos' net.load_template template_source='system { host-name {{pillar.proxy.host}}; }'
salt '*' net.load_template https://bit.ly/2OhSgqP hostname=example # will commit
salt '*' net.load_template https://bit.ly/2OhSgqP hostname=example test=True # dry run
salt '*' net.load_template salt://templates/example.jinja debug=True # Using the salt:// URI
# render a mako template:
salt '*' net.load_template salt://templates/example.mako template_engine=mako debug=True
# render remote template
salt -G 'os:junos' net.load_template http://bit.ly/2fReJg7 test=True debug=True peers=['192.168.0.1']
salt -G 'os:ios' net.load_template http://bit.ly/2gKOj20 test=True debug=True peers=['192.168.0.1']
# render multiple templates at once
salt '*' net.load_template "['https://bit.ly/2OhSgqP', 'salt://templates/example.jinja']" context="{'hostname': 'example'}"
Example output:
.. code-block:: python
{
'comment': '',
'already_configured': False,
'result': True,
'diff': '[edit system]+ host-name edge01.bjm01',
'loaded_config': 'system { host-name edge01.bjm01; }''
}
'''
_rendered = ''
_loaded = {
'result': True,
'comment': '',
'out': None
}
loaded_config = None
# prechecks
deprecated_args = ('template_user', 'template_attrs', 'template_group', 'template_mode')
for deprecated_arg in deprecated_args:
if template_vars.get(deprecated_arg):
del template_vars[deprecated_arg]
salt.utils.versions.warn_until(
'Sodium',
('The \'{arg}\' argument to \'net.load_template\' is deprecated '
'and has been ignored').format(arg=deprecated_arg)
)
if template_engine not in salt.utils.templates.TEMPLATE_REGISTRY:
_loaded.update({
'result': False,
'comment': 'Invalid templating engine! Choose between: {tpl_eng_opts}'.format(
tpl_eng_opts=', '.join(list(salt.utils.templates.TEMPLATE_REGISTRY.keys()))
)
})
return _loaded # exit
# to check if will be rendered by salt or NAPALM
salt_render_prefixes = ('salt://', 'http://', 'https://', 'ftp://')
salt_render = False
file_exists = False
if not isinstance(template_name, (tuple, list)):
for salt_render_prefix in salt_render_prefixes:
if not salt_render:
salt_render = salt_render or template_name.startswith(salt_render_prefix)
file_exists = __salt__['file.file_exists'](template_name)
if template_source or file_exists or salt_render or isinstance(template_name, (tuple, list)):
# either inline template
# either template in a custom path
# either abs path send
# either starts with salt:// and
# then use Salt render system
if context is None:
context = {}
context.update(template_vars)
# if needed to render the template send as inline arg
if template_source:
# render the content
_rendered = __salt__['file.apply_template_on_contents'](
contents=template_source,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv
)
if not isinstance(_rendered, six.string_types):
if 'result' in _rendered:
_loaded['result'] = _rendered['result']
else:
_loaded['result'] = False
if 'comment' in _rendered:
_loaded['comment'] = _rendered['comment']
else:
_loaded['comment'] = 'Error while rendering the template.'
return _loaded
else:
# render the file - either local, either remote
if not isinstance(template_name, (list, tuple)):
template_name = [template_name]
if template_hash_name and not isinstance(template_hash_name, (list, tuple)):
template_hash_name = [template_hash_name]
elif not template_hash_name:
template_hash_name = [None] * len(template_name)
if template_hash and isinstance(template_hash, six.string_types) and not\
(template_hash.startswith('salt://') or template_hash.startswith('file://')):
# If the template hash is passed as string, and it's not a file
# (starts with the salt:// or file:// URI), then make it a list
# of 1 element (for the iteration below)
template_hash = [template_hash]
elif template_hash and isinstance(template_hash, six.string_types) and\
(template_hash.startswith('salt://') or template_hash.startswith('file://')):
# If the template hash is a file URI, then provide the same value
# for each of the templates in the list, as probably they all
# share the same hash file, otherwise the user should provide
# this as a list
template_hash = [template_hash] * len(template_name)
elif not template_hash:
template_hash = [None] * len(template_name)
for tpl_index, tpl_name in enumerate(template_name):
tpl_hash = template_hash[tpl_index]
tpl_hash_name = template_hash_name[tpl_index]
_rand_filename = __salt__['random.hash'](tpl_name, 'md5')
_temp_file = __salt__['file.join']('/tmp', _rand_filename)
_managed = __salt__['file.get_managed'](name=_temp_file,
source=tpl_name,
source_hash=tpl_hash,
source_hash_name=tpl_hash_name,
user=None,
group=None,
mode=None,
attrs=None,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv,
skip_verify=skip_verify)
if not isinstance(_managed, (list, tuple)) and isinstance(_managed, six.string_types):
_loaded['comment'] += _managed
_loaded['result'] = False
elif isinstance(_managed, (list, tuple)) and not _managed:
_loaded['result'] = False
_loaded['comment'] += 'Error while rendering the template.'
elif isinstance(_managed, (list, tuple)) and not _managed[0]:
_loaded['result'] = False
_loaded['comment'] += _managed[-1] # contains the error message
if _loaded['result']: # all good
_temp_tpl_file = _managed[0]
_temp_tpl_file_exists = __salt__['file.file_exists'](_temp_tpl_file)
if not _temp_tpl_file_exists:
_loaded['result'] = False
_loaded['comment'] += 'Error while rendering the template.'
return _loaded
_rendered += __salt__['file.read'](_temp_tpl_file)
__salt__['file.remove'](_temp_tpl_file)
else:
return _loaded # exit
loaded_config = _rendered
if _loaded['result']: # all good
fun = 'load_merge_candidate'
if replace: # replace requested
fun = 'load_replace_candidate'
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
fun,
**{
'config': _rendered
}
)
else:
salt.utils.versions.warn_until(
'Sodium',
'Native NAPALM templates support will be removed in the Sodium '
'release. Please consider using the Salt rendering pipeline instead.'
'If you are using the \'netntp\', \'netsnmp\', or \'netusers\' Salt '
'State modules, you can ignore this message'
)
# otherwise, use NAPALM render system, injecting pillar/grains/opts vars
load_templates_params = defaults if defaults else {}
load_templates_params.update(template_vars)
load_templates_params.update(
{
'template_name': template_name,
'template_source': template_source, # inline template
'pillar': __pillar__, # inject pillar content
'grains': __grains__, # inject grains content
'opts': __opts__ # inject opts content
}
)
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
# so we'll set the CLOSE global explicitly as False
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'load_template',
**load_templates_params
)
return _config_logic(napalm_device, # pylint: disable=undefined-variable
_loaded,
test=test,
debug=debug,
replace=replace,
commit_config=commit,
loaded_config=loaded_config,
commit_at=commit_at,
commit_in=commit_in,
revert_in=revert_in,
revert_at=revert_at,
**template_vars)
@salt.utils.napalm.proxy_napalm_wrap
def commit(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Commits the configuration changes made on the network device.
CLI Example:
.. code-block:: bash
salt '*' net.commit
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'commit_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def discard_config(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
"""
Discards the changes applied.
CLI Example:
.. code-block:: bash
salt '*' net.discard_config
"""
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'discard_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def compare_config(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Returns the difference between the running config and the candidate config.
CLI Example:
.. code-block:: bash
salt '*' net.compare_config
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'compare_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def rollback(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Rollbacks the configuration.
CLI Example:
.. code-block:: bash
salt '*' net.rollback
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'rollback',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def config_changed(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Will prompt if the configuration has been changed.
:return: A tuple with a boolean that specifies if the config was changed on the device.\
And a string that provides more details of the reason why the configuration was not changed.
CLI Example:
.. code-block:: bash
salt '*' net.config_changed
'''
is_config_changed = False
reason = ''
try_compare = compare_config(inherit_napalm_device=napalm_device) # pylint: disable=undefined-variable
if try_compare.get('result'):
if try_compare.get('out'):
is_config_changed = True
else:
reason = 'Configuration was not changed on the device.'
else:
reason = try_compare.get('comment')
return is_config_changed, reason
@salt.utils.napalm.proxy_napalm_wrap
def config_control(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Will check if the configuration was changed.
If differences found, will try to commit.
In case commit unsuccessful, will try to rollback.
:return: A tuple with a boolean that specifies if the config was changed/committed/rollbacked on the device.\
And a string that provides more details of the reason why the configuration was not committed properly.
CLI Example:
.. code-block:: bash
salt '*' net.config_control
'''
result = True
comment = ''
changed, not_changed_rsn = config_changed(inherit_napalm_device=napalm_device) # pylint: disable=undefined-variable
if not changed:
return (changed, not_changed_rsn)
# config changed, thus let's try to commit
try_commit = commit()
if not try_commit.get('result'):
result = False
comment = 'Unable to commit the changes: {reason}.\n\
Will try to rollback now!'.format(
reason=try_commit.get('comment')
)
try_rollback = rollback()
if not try_rollback.get('result'):
comment += '\nCannot rollback! {reason}'.format(
reason=try_rollback.get('comment')
)
return result, comment
def cancel_commit(jid):
'''
.. versionadded:: 2019.2.0
Cancel a commit scheduled to be executed via the ``commit_in`` and
``commit_at`` arguments from the
:py:func:`net.load_template <salt.modules.napalm_network.load_template>` or
:py:func:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit ID is displayed when the commit is scheduled
via the functions named above.
CLI Example:
.. code-block:: bash
salt '*' net.cancel_commit 20180726083540640360
'''
job_name = '__napalm_commit_{}'.format(jid)
removed = __salt__['schedule.delete'](job_name)
if removed['result']:
saved = __salt__['schedule.save']()
removed['comment'] = 'Commit #{jid} cancelled.'.format(jid=jid)
else:
removed['comment'] = 'Unable to find commit #{jid}.'.format(jid=jid)
return removed
def confirm_commit(jid):
'''
.. versionadded:: 2019.2.0
Confirm a commit scheduled to be reverted via the ``revert_in`` and
``revert_at`` arguments from the
:mod:`net.load_template <salt.modules.napalm_network.load_template>` or
:mod:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit ID is displayed when the commit confirmed
is scheduled via the functions named above.
CLI Example:
.. code-block:: bash
salt '*' net.confirm_commit 20180726083540640360
'''
if __grains__['os'] == 'junos':
# Confirm the commit, by committing (i.e., invoking the RPC call)
confirmed = __salt__['napalm.junos_commit']()
confirmed['result'] = confirmed.pop('out')
confirmed['comment'] = confirmed.pop('message')
else:
confirmed = cancel_commit(jid)
if confirmed['result']:
confirmed['comment'] = 'Commit #{jid} confirmed.'.format(jid=jid)
return confirmed
def save_config(source=None,
path=None):
'''
.. versionadded:: 2019.2.0
Save the configuration to a file on the local file system.
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``,
``startup``. Default: ``running``.
path
Absolute path to file where to save the configuration.
To push the files to the Master, use
:mod:`cp.push <salt.modules.cp.push>` Execution function.
CLI Example:
.. code-block:: bash
salt '*' net.save_config source=running
'''
if not source:
source = 'running'
if not path:
path = salt.utils.files.mkstemp()
running_config = __salt__['net.config'](source=source)
if not running_config or not running_config['result']:
log.error('Unable to retrieve the config')
return running_config
with salt.utils.files.fopen(path, 'w') as fh_:
fh_.write(running_config['out'][source])
return {
'result': True,
'out': path,
'comment': '{source} config saved to {path}'.format(source=source, path=path)
}
def replace_pattern(pattern,
repl,
count=0,
flags=8,
bufsize=1,
append_if_not_found=False,
prepend_if_not_found=False,
not_found_content=None,
search_only=False,
show_changes=True,
backslash_literal=False,
source=None,
path=None,
test=False,
replace=True,
debug=False,
commit=True):
'''
.. versionadded:: 2019.2.0
Replace occurrences of a pattern in the configuration source. If
``show_changes`` is ``True``, then a diff of what changed will be returned,
otherwise a ``True`` will be returned when changes are made, and ``False``
when no changes are made.
This is a pure Python implementation that wraps Python's :py:func:`~re.sub`.
pattern
A regular expression, to be matched using Python's
:py:func:`~re.search`.
repl
The replacement text.
count: ``0``
Maximum number of pattern occurrences to be replaced. If count is a
positive integer ``n``, only ``n`` occurrences will be replaced,
otherwise all occurrences will be replaced.
flags (list or int): ``8``
A list of flags defined in the ``re`` module documentation from the
Python standard library. Each list item should be a string that will
correlate to the human-friendly flag name. E.g., ``['IGNORECASE',
'MULTILINE']``. Optionally, ``flags`` may be an int, with a value
corresponding to the XOR (``|``) of all the desired flags. Defaults to
8 (which supports 'MULTILINE').
bufsize (int or str): ``1``
How much of the configuration to buffer into memory at once. The
default value ``1`` processes one line at a time. The special value
``file`` may be specified which will read the entire file into memory
before processing.
append_if_not_found: ``False``
If set to ``True``, and pattern is not found, then the content will be
appended to the file.
prepend_if_not_found: ``False``
If set to ``True`` and pattern is not found, then the content will be
prepended to the file.
not_found_content
Content to use for append/prepend if not found. If None (default), uses
``repl``. Useful when ``repl`` uses references to group in pattern.
search_only: ``False``
If set to true, this no changes will be performed on the file, and this
function will simply return ``True`` if the pattern was matched, and
``False`` if not.
show_changes: ``True``
If ``True``, return a diff of changes made. Otherwise, return ``True``
if changes were made, and ``False`` if not.
backslash_literal: ``False``
Interpret backslashes as literal backslashes for the repl and not
escape characters. This will help when using append/prepend so that
the backslashes are not interpreted for the repl on the second run of
the state.
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path
Save the temporary configuration to a specific path, then read from
there.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' net.replace_pattern "bind-address\\s*=" "bind-address:"
CLI Example:
.. code-block:: bash
salt '*' net.replace_pattern PREFIX-LIST_NAME new-prefix-list-name
salt '*' net.replace_pattern bgp-group-name new-bgp-group-name count=1
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
replace_pattern = __salt__['file.replace'](path,
pattern,
repl,
count=count,
flags=flags,
bufsize=bufsize,
append_if_not_found=append_if_not_found,
prepend_if_not_found=prepend_if_not_found,
not_found_content=not_found_content,
search_only=search_only,
show_changes=show_changes,
backslash_literal=backslash_literal)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
def blockreplace(marker_start,
marker_end,
content='',
append_if_not_found=False,
prepend_if_not_found=False,
show_changes=True,
append_newline=False,
source='running',
path=None,
test=False,
commit=True,
debug=False,
replace=True):
'''
.. versionadded:: 2019.2.0
Replace content of the configuration source, delimited by the line markers.
A block of content delimited by comments can help you manage several lines
without worrying about old entries removal.
marker_start
The line content identifying a line as the start of the content block.
Note that the whole line containing this marker will be considered,
so whitespace or extra content before or after the marker is included
in final output.
marker_end
The line content identifying a line as the end of the content block.
Note that the whole line containing this marker will be considered,
so whitespace or extra content before or after the marker is included
in final output.
content
The content to be used between the two lines identified by
``marker_start`` and ``marker_stop``.
append_if_not_found: ``False``
If markers are not found and set to True then, the markers and content
will be appended to the file.
prepend_if_not_found: ``False``
If markers are not found and set to True then, the markers and content
will be prepended to the file.
append_newline: ``False``
Controls whether or not a newline is appended to the content block.
If the value of this argument is ``True`` then a newline will be added
to the content block. If it is ``False``, then a newline will not be
added to the content block. If it is ``None`` then a newline will only
be added to the content block if it does not already end in a newline.
show_changes: ``True``
Controls how changes are presented. If ``True``, this function will
return the of the changes made.
If ``False``, then it will return a boolean (``True`` if any changes
were made, otherwise False).
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path: ``None``
Save the temporary configuration to a specific path, then read from
there. This argument is optional, can be used when you prefers a
particular location of the temporary file.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
CLI Example:
.. code-block:: bash
salt '*' net.blockreplace 'ntp' 'interface' ''
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
replace_pattern = __salt__['file.blockreplace'](path,
marker_start=marker_start,
marker_end=marker_end,
content=content,
append_if_not_found=append_if_not_found,
prepend_if_not_found=prepend_if_not_found,
show_changes=show_changes,
append_newline=append_newline)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
def patch(patchfile,
options='',
saltenv='base',
source_hash=None,
show_changes=True,
source='running',
path=None,
test=False,
commit=True,
debug=False,
replace=True):
'''
.. versionadded:: 2019.2.0
Apply a patch to the configuration source, and load the result into the
running config of the device.
patchfile
A patch file to apply to the configuration source.
options
Options to pass to patch.
source_hash
If the patch file (specified via the ``patchfile`` argument) is an
HTTP(S) or FTP URL and the file exists in the minion's file cache, this
option can be passed to keep the minion from re-downloading the file if
the cached copy matches the specified hash.
show_changes: ``True``
Controls how changes are presented. If ``True``, this function will
return the of the changes made.
If ``False``, then it will return a boolean (``True`` if any changes
were made, otherwise False).
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path: ``None``
Save the temporary configuration to a specific path, then read from
there. This argument is optional, can the user prefers a particular
location of the temporary file.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
CLI Example:
.. code-block:: bash
salt '*' net.patch https://example.com/running_config.patch
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
patchfile_cache = __salt__['cp.cache_file'](patchfile)
if patchfile_cache is False:
return {
'out': None,
'result': False,
'comment': 'The file "{}" does not exist.'.format(patchfile)
}
replace_pattern = __salt__['file.patch'](path,
patchfile_cache,
options=options)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
# <---- Configuration specific functions -------------------------------------------------------------------------------
|
saltstack/salt
|
salt/modules/napalm_network.py
|
ping
|
python
|
def ping(destination, source=None, ttl=None, timeout=None, size=None, count=None, vrf=None, **kwargs): # pylint: disable=unused-argument
'''
Executes a ping on the network device and returns a dictionary as a result.
destination
Hostname or IP address of remote host
source
Source address of echo request
ttl
IP time-to-live value (IPv6 hop-limit value) (1..255 hops)
timeout
Maximum wait time after sending final packet (seconds)
size
Size of request packets (0..65468 bytes)
count
Number of ping requests to send (1..2000000000 packets)
vrf
VRF (routing instance) for ping attempt
.. versionadded:: 2016.11.4
CLI Example:
.. code-block:: bash
salt '*' net.ping 8.8.8.8
salt '*' net.ping 8.8.8.8 ttl=3 size=65468
salt '*' net.ping 8.8.8.8 source=127.0.0.1 timeout=1 count=100
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'ping',
**{
'destination': destination,
'source': source,
'ttl': ttl,
'timeout': timeout,
'size': size,
'count': count,
'vrf': vrf
}
)
|
Executes a ping on the network device and returns a dictionary as a result.
destination
Hostname or IP address of remote host
source
Source address of echo request
ttl
IP time-to-live value (IPv6 hop-limit value) (1..255 hops)
timeout
Maximum wait time after sending final packet (seconds)
size
Size of request packets (0..65468 bytes)
count
Number of ping requests to send (1..2000000000 packets)
vrf
VRF (routing instance) for ping attempt
.. versionadded:: 2016.11.4
CLI Example:
.. code-block:: bash
salt '*' net.ping 8.8.8.8
salt '*' net.ping 8.8.8.8 ttl=3 size=65468
salt '*' net.ping 8.8.8.8 source=127.0.0.1 timeout=1 count=100
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_network.py#L832-L881
|
[
"def call(napalm_device, method, *args, **kwargs):\n '''\n Calls arbitrary methods from the network driver instance.\n Please check the readthedocs_ page for the updated list of getters.\n\n .. _readthedocs: http://napalm.readthedocs.org/en/latest/support/index.html#getters-support-matrix\n\n method\n Specifies the name of the method to be called.\n\n *args\n Arguments.\n\n **kwargs\n More arguments.\n\n :return: A dictionary with three keys:\n\n * result (True/False): if the operation succeeded\n * out (object): returns the object as-is from the call\n * comment (string): provides more details in case the call failed\n * traceback (string): complete traceback in case of exception. \\\n Please submit an issue including this traceback \\\n on the `correct driver repo`_ and make sure to read the FAQ_\n\n .. _`correct driver repo`: https://github.com/napalm-automation/napalm/issues/new\n .. FAQ_: https://github.com/napalm-automation/napalm#faq\n\n Example:\n\n .. code-block:: python\n\n salt.utils.napalm.call(\n napalm_object,\n 'cli',\n [\n 'show version',\n 'show chassis fan'\n ]\n )\n '''\n result = False\n out = None\n opts = napalm_device.get('__opts__', {})\n retry = kwargs.pop('__retry', True) # retry executing the task?\n force_reconnect = kwargs.get('force_reconnect', False)\n if force_reconnect:\n log.debug('Forced reconnection initiated')\n log.debug('The current opts (under the proxy key):')\n log.debug(opts['proxy'])\n opts['proxy'].update(**kwargs)\n log.debug('Updated to:')\n log.debug(opts['proxy'])\n napalm_device = get_device(opts)\n try:\n if not napalm_device.get('UP', False):\n raise Exception('not connected')\n # if connected will try to execute desired command\n kwargs_copy = {}\n kwargs_copy.update(kwargs)\n for karg, warg in six.iteritems(kwargs_copy):\n # lets clear None arguments\n # to not be sent to NAPALM methods\n if warg is None:\n kwargs.pop(karg)\n out = getattr(napalm_device.get('DRIVER'), method)(*args, **kwargs)\n # calls the method with the specified parameters\n result = True\n except Exception as error:\n # either not connected\n # either unable to execute the command\n hostname = napalm_device.get('HOSTNAME', '[unspecified hostname]')\n err_tb = traceback.format_exc() # let's get the full traceback and display for debugging reasons.\n if isinstance(error, NotImplementedError):\n comment = '{method} is not implemented for the NAPALM {driver} driver!'.format(\n method=method,\n driver=napalm_device.get('DRIVER_NAME')\n )\n elif retry and HAS_CONN_CLOSED_EXC_CLASS and isinstance(error, ConnectionClosedException):\n # Received disconection whilst executing the operation.\n # Instructed to retry (default behaviour)\n # thus trying to re-establish the connection\n # and re-execute the command\n # if any of the operations (close, open, call) will rise again ConnectionClosedException\n # it will fail loudly.\n kwargs['__retry'] = False # do not attempt re-executing\n comment = 'Disconnected from {device}. Trying to reconnect.'.format(device=hostname)\n log.error(err_tb)\n log.error(comment)\n log.debug('Clearing the connection with %s', hostname)\n call(napalm_device, 'close', __retry=False) # safely close the connection\n # Make sure we don't leave any TCP connection open behind\n # if we fail to close properly, we might not be able to access the\n log.debug('Re-opening the connection with %s', hostname)\n call(napalm_device, 'open', __retry=False)\n log.debug('Connection re-opened with %s', hostname)\n log.debug('Re-executing %s', method)\n return call(napalm_device, method, *args, **kwargs)\n # If still not able to reconnect and execute the task,\n # the proxy keepalive feature (if enabled) will attempt\n # to reconnect.\n # If the device is using a SSH-based connection, the failure\n # will also notify the paramiko transport and the `is_alive` flag\n # is going to be set correctly.\n # More background: the network device may decide to disconnect,\n # although the SSH session itself is alive and usable, the reason\n # being the lack of activity on the CLI.\n # Paramiko's keepalive doesn't help in this case, as the ServerAliveInterval\n # are targeting the transport layer, whilst the device takes the decision\n # when there isn't any activity on the CLI, thus at the application layer.\n # Moreover, the disconnect is silent and paramiko's is_alive flag will\n # continue to return True, although the connection is already unusable.\n # For more info, see https://github.com/paramiko/paramiko/issues/813.\n # But after a command fails, the `is_alive` flag becomes aware of these\n # changes and will return False from there on. And this is how the\n # Salt proxy keepalive helps: immediately after the first failure, it\n # will know the state of the connection and will try reconnecting.\n else:\n comment = 'Cannot execute \"{method}\" on {device}{port} as {user}. Reason: {error}!'.format(\n device=napalm_device.get('HOSTNAME', '[unspecified hostname]'),\n port=(':{port}'.format(port=napalm_device.get('OPTIONAL_ARGS', {}).get('port'))\n if napalm_device.get('OPTIONAL_ARGS', {}).get('port') else ''),\n user=napalm_device.get('USERNAME', ''),\n method=method,\n error=error\n )\n log.error(comment)\n log.error(err_tb)\n return {\n 'out': {},\n 'result': False,\n 'comment': comment,\n 'traceback': err_tb\n }\n finally:\n if opts and not_always_alive(opts) and napalm_device.get('CLOSE', True):\n # either running in a not-always-alive proxy\n # either running in a regular minion\n # close the connection when the call is over\n # unless the CLOSE is explicitly set as False\n napalm_device['DRIVER'].close()\n return {\n 'out': out,\n 'result': result,\n 'comment': ''\n }\n"
] |
# -*- coding: utf-8 -*-
'''
NAPALM Network
==============
Basic methods for interaction with the network device through the virtual proxy 'napalm'.
:codeauthor: Mircea Ulinic <mircea@cloudflare.com> & Jerome Fleury <jf@cloudflare.com>
:maturity: new
:depends: napalm
:platform: unix
Dependencies
------------
- :mod:`napalm proxy minion <salt.proxy.napalm>`
.. versionadded:: 2016.11.0
.. versionchanged:: 2017.7.0
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import time
import logging
import datetime
log = logging.getLogger(__name__)
# Import Salt libs
from salt.ext import six
import salt.utils.files
import salt.utils.napalm
import salt.utils.versions
import salt.utils.templates
# Import 3rd-party libs
try:
import jxmlease # pylint: disable=unused-import
HAS_JXMLEASE = True
except ImportError:
HAS_JXMLEASE = False
# ----------------------------------------------------------------------------------------------------------------------
# module properties
# ----------------------------------------------------------------------------------------------------------------------
__virtualname__ = 'net'
__proxyenabled__ = ['*']
__virtual_aliases__ = ('napalm_net',)
# uses NAPALM-based proxy to interact with network devices
# ----------------------------------------------------------------------------------------------------------------------
# property functions
# ----------------------------------------------------------------------------------------------------------------------
def __virtual__():
'''
NAPALM library must be installed for this module to work and run in a (proxy) minion.
'''
return salt.utils.napalm.virtual(__opts__, __virtualname__, __file__)
# ----------------------------------------------------------------------------------------------------------------------
# helper functions -- will not be exported
# ----------------------------------------------------------------------------------------------------------------------
def _filter_list(input_list, search_key, search_value):
'''
Filters a list of dictionary by a set of key-value pair.
:param input_list: is a list of dictionaries
:param search_key: is the key we are looking for
:param search_value: is the value we are looking for the key specified in search_key
:return: filered list of dictionaries
'''
output_list = list()
for dictionary in input_list:
if dictionary.get(search_key) == search_value:
output_list.append(dictionary)
return output_list
def _filter_dict(input_dict, search_key, search_value):
'''
Filters a dictionary of dictionaries by a key-value pair.
:param input_dict: is a dictionary whose values are lists of dictionaries
:param search_key: is the key in the leaf dictionaries
:param search_values: is the value in the leaf dictionaries
:return: filtered dictionary
'''
output_dict = dict()
for key, key_list in six.iteritems(input_dict):
key_list_filtered = _filter_list(key_list, search_key, search_value)
if key_list_filtered:
output_dict[key] = key_list_filtered
return output_dict
def _safe_commit_config(loaded_result, napalm_device):
_commit = commit(inherit_napalm_device=napalm_device) # calls the function commit, defined below
if not _commit.get('result', False):
# if unable to commit
loaded_result['comment'] += _commit['comment'] if _commit.get('comment') else 'Unable to commit.'
loaded_result['result'] = False
# unable to commit, something went wrong
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
return _commit
def _safe_dicard_config(loaded_result, napalm_device):
'''
'''
log.debug('Discarding the config')
log.debug(loaded_result)
_discarded = discard_config(inherit_napalm_device=napalm_device)
if not _discarded.get('result', False):
loaded_result['comment'] += _discarded['comment'] if _discarded.get('comment') \
else 'Unable to discard config.'
loaded_result['result'] = False
# make sure it notifies
# that something went wrong
_explicit_close(napalm_device)
__context__['retcode'] = 1
return loaded_result
return _discarded
def _explicit_close(napalm_device):
'''
Will explicily close the config session with the network device,
when running in a now-always-alive proxy minion or regular minion.
This helper must be used in configuration-related functions,
as the session is preserved and not closed before making any changes.
'''
if salt.utils.napalm.not_always_alive(__opts__):
# force closing the configuration session
# when running in a non-always-alive proxy
# or regular minion
try:
napalm_device['DRIVER'].close()
except Exception as err:
log.error('Unable to close the temp connection with the device:')
log.error(err)
log.error('Please report.')
def _config_logic(napalm_device,
loaded_result,
test=False,
debug=False,
replace=False,
commit_config=True,
loaded_config=None,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
commit_jid=None,
**kwargs):
'''
Builds the config logic for `load_config` and `load_template` functions.
'''
# As the Salt logic is built around independent events
# when it comes to configuration changes in the
# candidate DB on the network devices, we need to
# make sure we're using the same session.
# Hence, we need to pass the same object around.
# the napalm_device object is inherited from
# the load_config or load_template functions
# and forwarded to compare, discard, commit etc.
# then the decorator will make sure that
# if not proxy (when the connection is always alive)
# and the `inherit_napalm_device` is set,
# `napalm_device` will be overridden.
# See `salt.utils.napalm.proxy_napalm_wrap` decorator.
current_jid = kwargs.get('__pub_jid')
if not current_jid:
current_jid = '{0:%Y%m%d%H%M%S%f}'.format(datetime.datetime.now())
loaded_result['already_configured'] = False
loaded_result['loaded_config'] = ''
if debug:
loaded_result['loaded_config'] = loaded_config
_compare = compare_config(inherit_napalm_device=napalm_device)
if _compare.get('result', False):
loaded_result['diff'] = _compare.get('out')
loaded_result.pop('out', '') # not needed
else:
loaded_result['diff'] = None
loaded_result['result'] = False
loaded_result['comment'] = _compare.get('comment')
__context__['retcode'] = 1
return loaded_result
_loaded_res = loaded_result.get('result', False)
if not _loaded_res or test:
# if unable to load the config (errors / warnings)
# or in testing mode,
# will discard the config
if loaded_result['comment']:
loaded_result['comment'] += '\n'
if not loaded_result.get('diff', ''):
loaded_result['already_configured'] = True
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
loaded_result['comment'] += 'Configuration discarded.'
# loaded_result['result'] = False not necessary
# as the result can be true when test=True
_explicit_close(napalm_device)
if not loaded_result['result']:
__context__['retcode'] = 1
return loaded_result
if not test and commit_config:
# if not in testing mode and trying to commit
if commit_jid:
log.info('Committing the JID: %s', str(commit_jid))
removed = cancel_commit(commit_jid)
log.debug('Cleaned up the commit from the schedule')
log.debug(removed['comment'])
if loaded_result.get('diff', ''):
# if not testing mode
# and also the user wants to commit (default)
# and there are changes to commit
if commit_in or commit_at:
commit_time = __utils__['timeutil.get_time_at'](time_in=commit_in,
time_at=commit_in)
# schedule job
scheduled_job_name = '__napalm_commit_{}'.format(current_jid)
temp_file = salt.utils.files.mkstemp()
with salt.utils.files.fopen(temp_file, 'w') as fp_:
fp_.write(loaded_config)
scheduled = __salt__['schedule.add'](scheduled_job_name,
function='net.load_config',
job_kwargs={
'filename': temp_file,
'commit_jid': current_jid,
'replace': replace
},
once=commit_time)
log.debug('Scheduling job')
log.debug(scheduled)
saved = __salt__['schedule.save']() # ensure the schedule is
# persistent cross Minion restart
discarded = _safe_dicard_config(loaded_result, napalm_device)
# discard the changes
if not discarded['result']:
discarded['comment'] += ('Scheduled the job to be executed at {schedule_ts}, '
'but was unable to discard the config: \n').format(schedule_ts=commit_time)
return discarded
loaded_result['comment'] = ('Changes discarded for now, and scheduled commit at: {schedule_ts}.\n'
'The commit ID is: {current_jid}.\n'
'To discard this commit, you can execute: \n\n'
'salt {min_id} net.cancel_commit {current_jid}').format(schedule_ts=commit_time,
min_id=__opts__['id'],
current_jid=current_jid)
loaded_result['commit_id'] = current_jid
return loaded_result
log.debug('About to commit:')
log.debug(loaded_result['diff'])
if revert_in or revert_at:
revert_time = __utils__['timeutil.get_time_at'](time_in=revert_in,
time_at=revert_at)
if __grains__['os'] == 'junos':
if not HAS_JXMLEASE:
loaded_result['comment'] = ('This feature requires the library jxmlease to be installed.\n'
'To install, please execute: ``pip install jxmlease``.')
loaded_result['result'] = False
return loaded_result
timestamp_at = __utils__['timeutil.get_timestamp_at'](time_in=revert_in,
time_at=revert_at)
minutes = int((timestamp_at - time.time())/60)
_comm = __salt__['napalm.junos_commit'](confirm=minutes)
if not _comm['out']:
# If unable to commit confirm, should try to bail out
loaded_result['comment'] = 'Unable to commit confirm: {}'.format(_comm['message'])
loaded_result['result'] = False
# But before exiting, we must gracefully discard the config
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
else:
temp_file = salt.utils.files.mkstemp()
running_config = __salt__['net.config'](source='running')['out']['running']
with salt.utils.files.fopen(temp_file, 'w') as fp_:
fp_.write(running_config)
committed = _safe_commit_config(loaded_result, napalm_device)
if not committed['result']:
# If unable to commit, dicard the config (which is
# already done by the _safe_commit_config function), and
# return with the command and other details.
return loaded_result
scheduled_job_name = '__napalm_commit_{}'.format(current_jid)
scheduled = __salt__['schedule.add'](scheduled_job_name,
function='net.load_config',
job_kwargs={
'filename': temp_file,
'commit_jid': current_jid,
'replace': True
},
once=revert_time)
log.debug('Scheduling commit confirmed')
log.debug(scheduled)
saved = __salt__['schedule.save']()
loaded_result['comment'] = ('The commit ID is: {current_jid}.\n'
'This commit will be reverted at: {schedule_ts}, unless confirmed.\n'
'To confirm the commit and avoid reverting, you can execute:\n\n'
'salt {min_id} net.confirm_commit {current_jid}').format(schedule_ts=revert_time,
min_id=__opts__['id'],
current_jid=current_jid)
loaded_result['commit_id'] = current_jid
return loaded_result
committed = _safe_commit_config(loaded_result, napalm_device)
if not committed['result']:
return loaded_result
else:
# would like to commit, but there's no change
# need to call discard_config() to release the config DB
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
loaded_result['already_configured'] = True
loaded_result['comment'] = 'Already configured.'
_explicit_close(napalm_device)
if not loaded_result['result']:
__context__['retcode'] = 1
return loaded_result
# ----------------------------------------------------------------------------------------------------------------------
# callable functions
# ----------------------------------------------------------------------------------------------------------------------
@salt.utils.napalm.proxy_napalm_wrap
def connected(**kwargs): # pylint: disable=unused-argument
'''
Specifies if the connection to the device succeeded.
CLI Example:
.. code-block:: bash
salt '*' net.connected
'''
return {
'out': napalm_device.get('UP', False) # pylint: disable=undefined-variable
}
@salt.utils.napalm.proxy_napalm_wrap
def facts(**kwargs): # pylint: disable=unused-argument
'''
Returns characteristics of the network device.
:return: a dictionary with the following keys:
* uptime - Uptime of the device in seconds.
* vendor - Manufacturer of the device.
* model - Device model.
* hostname - Hostname of the device
* fqdn - Fqdn of the device
* os_version - String with the OS version running on the device.
* serial_number - Serial number of the device
* interface_list - List of the interfaces of the device
CLI Example:
.. code-block:: bash
salt '*' net.facts
Example output:
.. code-block:: python
{
'os_version': '13.3R6.5',
'uptime': 10117140,
'interface_list': [
'lc-0/0/0',
'pfe-0/0/0',
'pfh-0/0/0',
'xe-0/0/0',
'xe-0/0/1',
'xe-0/0/2',
'xe-0/0/3',
'gr-0/0/10',
'ip-0/0/10'
],
'vendor': 'Juniper',
'serial_number': 'JN131356FBFA',
'model': 'MX480',
'hostname': 're0.edge05.syd01',
'fqdn': 're0.edge05.syd01'
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_facts',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def environment(**kwargs): # pylint: disable=unused-argument
'''
Returns the environment of the device.
CLI Example:
.. code-block:: bash
salt '*' net.environment
Example output:
.. code-block:: python
{
'fans': {
'Bottom Rear Fan': {
'status': True
},
'Bottom Middle Fan': {
'status': True
},
'Top Middle Fan': {
'status': True
},
'Bottom Front Fan': {
'status': True
},
'Top Front Fan': {
'status': True
},
'Top Rear Fan': {
'status': True
}
},
'memory': {
'available_ram': 16349,
'used_ram': 4934
},
'temperature': {
'FPC 0 Exhaust A': {
'is_alert': False,
'temperature': 35.0,
'is_critical': False
}
},
'cpu': {
'1': {
'%usage': 19.0
},
'0': {
'%usage': 35.0
}
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_environment',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def cli(*commands, **kwargs): # pylint: disable=unused-argument
'''
Returns a dictionary with the raw output of all commands passed as arguments.
commands
List of commands to be executed on the device.
textfsm_parse: ``False``
Try parsing the outputs using the TextFSM templates.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``napalm_cli_textfsm_parse``.
textfsm_path
The path where the TextFSM templates can be found. This option implies
the usage of the TextFSM index file.
``textfsm_path`` can be either absolute path on the server,
either specified using the following URL mschemes: ``file://``,
``salt://``, ``http://``, ``https://``, ``ftp://``,
``s3://``, ``swift://``.
.. versionadded:: 2018.3.0
.. note::
This needs to be a directory with a flat structure, having an
index file (whose name can be specified using the ``index_file`` option)
and a number of TextFSM templates.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_path``.
textfsm_template
The path to a certain the TextFSM template.
This can be specified using the absolute path
to the file, or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
.. versionadded:: 2018.3.0
textfsm_template_dict
A dictionary with the mapping between a command
and the corresponding TextFSM path to use to extract the data.
The TextFSM paths can be specified as in ``textfsm_template``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``napalm_cli_textfsm_template_dict``.
platform_grain_name: ``os``
The name of the grain used to identify the platform name
in the TextFSM index file. Default: ``os``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_grain``.
platform_column_name: ``Platform``
The column name used to identify the platform,
exactly as specified in the TextFSM index file.
Default: ``Platform``.
.. versionadded:: 2018.3.0
.. note::
This is field is case sensitive, make sure
to assign the correct value to this option,
exactly as defined in the index file.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_column_name``.
index_file: ``index``
The name of the TextFSM index file, under the ``textfsm_path``. Default: ``index``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_index_file``.
saltenv: ``base``
Salt fileserver envrionment from which to retrieve the file.
Ignored if ``textfsm_path`` is not a ``salt://`` URL.
.. versionadded:: 2018.3.0
include_empty: ``False``
Include empty files under the ``textfsm_path``.
.. versionadded:: 2018.3.0
include_pat
Glob or regex to narrow down the files cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. versionadded:: 2018.3.0
exclude_pat
Glob or regex to exclude certain files from being cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. versionadded:: 2018.3.0
.. note::
If used with ``include_pat``, files matching this pattern will be
excluded from the subset of files defined by ``include_pat``.
CLI Example:
.. code-block:: bash
salt '*' net.cli "show version" "show chassis fan"
CLI Example with TextFSM template:
.. code-block:: bash
salt '*' net.cli textfsm_parse=True textfsm_path=salt://textfsm/
Example output:
.. code-block:: python
{
'show version and haiku': 'Hostname: re0.edge01.arn01
Model: mx480
Junos: 13.3R6.5
Help me, Obi-Wan
I just saw Episode Two
You're my only hope
',
'show chassis fan' : 'Item Status RPM Measurement
Top Rear Fan OK 3840 Spinning at intermediate-speed
Bottom Rear Fan OK 3840 Spinning at intermediate-speed
Top Middle Fan OK 3900 Spinning at intermediate-speed
Bottom Middle Fan OK 3840 Spinning at intermediate-speed
Top Front Fan OK 3810 Spinning at intermediate-speed
Bottom Front Fan OK 3840 Spinning at intermediate-speed
'
}
Example output with TextFSM parsing:
.. code-block:: json
{
"comment": "",
"result": true,
"out": {
"sh ver": [
{
"kernel": "9.1S3.5",
"documentation": "9.1S3.5",
"boot": "9.1S3.5",
"crypto": "9.1S3.5",
"chassis": "",
"routing": "9.1S3.5",
"base": "9.1S3.5",
"model": "mx960"
}
]
}
}
'''
raw_cli_outputs = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'cli',
**{
'commands': list(commands)
}
)
# thus we can display the output as is
# in case of errors, they'll be catched in the proxy
if not raw_cli_outputs['result']:
# Error -> dispaly the output as-is.
return raw_cli_outputs
textfsm_parse = kwargs.get('textfsm_parse') or __opts__.get('napalm_cli_textfsm_parse') or\
__pillar__.get('napalm_cli_textfsm_parse', False)
if not textfsm_parse:
# No TextFSM parsing required, return raw commands.
log.debug('No TextFSM parsing requested.')
return raw_cli_outputs
if 'textfsm.extract' not in __salt__ or 'textfsm.index' not in __salt__:
raw_cli_outputs['comment'] += 'Unable to process: is TextFSM installed?'
log.error(raw_cli_outputs['comment'])
return raw_cli_outputs
textfsm_template = kwargs.get('textfsm_template')
log.debug('textfsm_template: %s', textfsm_template)
textfsm_path = kwargs.get('textfsm_path') or __opts__.get('textfsm_path') or\
__pillar__.get('textfsm_path')
log.debug('textfsm_path: %s', textfsm_path)
textfsm_template_dict = kwargs.get('textfsm_template_dict') or __opts__.get('napalm_cli_textfsm_template_dict') or\
__pillar__.get('napalm_cli_textfsm_template_dict', {})
log.debug('TextFSM command-template mapping: %s', textfsm_template_dict)
index_file = kwargs.get('index_file') or __opts__.get('textfsm_index_file') or\
__pillar__.get('textfsm_index_file')
log.debug('index_file: %s', index_file)
platform_grain_name = kwargs.get('platform_grain_name') or __opts__.get('textfsm_platform_grain') or\
__pillar__.get('textfsm_platform_grain', 'os')
log.debug('platform_grain_name: %s', platform_grain_name)
platform_column_name = kwargs.get('platform_column_name') or __opts__.get('textfsm_platform_column_name') or\
__pillar__.get('textfsm_platform_column_name', 'Platform')
log.debug('platform_column_name: %s', platform_column_name)
saltenv = kwargs.get('saltenv', 'base')
include_empty = kwargs.get('include_empty', False)
include_pat = kwargs.get('include_pat')
exclude_pat = kwargs.get('exclude_pat')
processed_cli_outputs = {
'comment': raw_cli_outputs.get('comment', ''),
'result': raw_cli_outputs['result'],
'out': {}
}
log.debug('Starting to analyse the raw outputs')
for command in list(commands):
command_output = raw_cli_outputs['out'][command]
log.debug('Output from command: %s', command)
log.debug(command_output)
processed_command_output = None
if textfsm_path:
log.debug('Using the templates under %s', textfsm_path)
processed_cli_output = __salt__['textfsm.index'](command,
platform_grain_name=platform_grain_name,
platform_column_name=platform_column_name,
output=command_output.strip(),
textfsm_path=textfsm_path,
saltenv=saltenv,
include_empty=include_empty,
include_pat=include_pat,
exclude_pat=exclude_pat)
log.debug('Processed CLI output:')
log.debug(processed_cli_output)
if not processed_cli_output['result']:
log.debug('Apparently this didnt work, returnin the raw output')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {0}: {1}.'.format(command,
processed_cli_output['comment'])
log.error(processed_cli_outputs['comment'])
elif processed_cli_output['out']:
log.debug('All good, %s has a nice output!', command)
processed_command_output = processed_cli_output['out']
else:
comment = '''\nProcessing "{}" didn't fail, but didn't return anything either. Dumping raw.'''.format(
command)
processed_cli_outputs['comment'] += comment
log.error(comment)
processed_command_output = command_output
elif textfsm_template or command in textfsm_template_dict:
if command in textfsm_template_dict:
textfsm_template = textfsm_template_dict[command]
log.debug('Using %s to process the command: %s', textfsm_template, command)
processed_cli_output = __salt__['textfsm.extract'](textfsm_template,
raw_text=command_output,
saltenv=saltenv)
log.debug('Processed CLI output:')
log.debug(processed_cli_output)
if not processed_cli_output['result']:
log.debug('Apparently this didnt work, returning '
'the raw output')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {0}: {1}'.format(command,
processed_cli_output['comment'])
log.error(processed_cli_outputs['comment'])
elif processed_cli_output['out']:
log.debug('All good, %s has a nice output!', command)
processed_command_output = processed_cli_output['out']
else:
log.debug('Processing %s didnt fail, but didnt return'
' anything either. Dumping raw.', command)
processed_command_output = command_output
else:
log.error('No TextFSM template specified, or no TextFSM path defined')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {}.'.format(command)
processed_cli_outputs['out'][command] = processed_command_output
processed_cli_outputs['comment'] = processed_cli_outputs['comment'].strip()
return processed_cli_outputs
@salt.utils.napalm.proxy_napalm_wrap
def traceroute(destination, source=None, ttl=None, timeout=None, vrf=None, **kwargs): # pylint: disable=unused-argument
'''
Calls the method traceroute from the NAPALM driver object and returns a dictionary with the result of the traceroute
command executed on the device.
destination
Hostname or address of remote host
source
Source address to use in outgoing traceroute packets
ttl
IP maximum time-to-live value (or IPv6 maximum hop-limit value)
timeout
Number of seconds to wait for response (seconds)
vrf
VRF (routing instance) for traceroute attempt
.. versionadded:: 2016.11.4
CLI Example:
.. code-block:: bash
salt '*' net.traceroute 8.8.8.8
salt '*' net.traceroute 8.8.8.8 source=127.0.0.1 ttl=5 timeout=1
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'traceroute',
**{
'destination': destination,
'source': source,
'ttl': ttl,
'timeout': timeout,
'vrf': vrf
}
)
@salt.utils.napalm.proxy_napalm_wrap
@salt.utils.napalm.proxy_napalm_wrap
def arp(interface='', ipaddr='', macaddr='', **kwargs): # pylint: disable=unused-argument
'''
NAPALM returns a list of dictionaries with details of the ARP entries.
:param interface: interface name to filter on
:param ipaddr: IP address to filter on
:param macaddr: MAC address to filter on
:return: List of the entries in the ARP table
CLI Example:
.. code-block:: bash
salt '*' net.arp
salt '*' net.arp macaddr='5c:5e:ab:da:3c:f0'
Example output:
.. code-block:: python
[
{
'interface' : 'MgmtEth0/RSP0/CPU0/0',
'mac' : '5c:5e:ab:da:3c:f0',
'ip' : '172.17.17.1',
'age' : 1454496274.84
},
{
'interface': 'MgmtEth0/RSP0/CPU0/0',
'mac' : '66:0e:94:96:e0:ff',
'ip' : '172.17.17.2',
'age' : 1435641582.49
}
]
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_arp_table',
**{
}
)
if not proxy_output.get('result'):
return proxy_output
arp_table = proxy_output.get('out')
if interface:
arp_table = _filter_list(arp_table, 'interface', interface)
if ipaddr:
arp_table = _filter_list(arp_table, 'ip', ipaddr)
if macaddr:
arp_table = _filter_list(arp_table, 'mac', macaddr)
proxy_output.update({
'out': arp_table
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def ipaddrs(**kwargs): # pylint: disable=unused-argument
'''
Returns IP addresses configured on the device.
:return: A dictionary with the IPv4 and IPv6 addresses of the interfaces.
Returns all configured IP addresses on all interfaces as a dictionary
of dictionaries. Keys of the main dictionary represent the name of the
interface. Values of the main dictionary represent are dictionaries
that may consist of two keys 'ipv4' and 'ipv6' (one, both or none)
which are themselvs dictionaries with the IP addresses as keys.
CLI Example:
.. code-block:: bash
salt '*' net.ipaddrs
Example output:
.. code-block:: python
{
'FastEthernet8': {
'ipv4': {
'10.66.43.169': {
'prefix_length': 22
}
}
},
'Loopback555': {
'ipv4': {
'192.168.1.1': {
'prefix_length': 24
}
},
'ipv6': {
'1::1': {
'prefix_length': 64
},
'2001:DB8:1::1': {
'prefix_length': 64
},
'FE80::3': {
'prefix_length': 'N/A'
}
}
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_interfaces_ip',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def interfaces(**kwargs): # pylint: disable=unused-argument
'''
Returns details of the interfaces on the device.
:return: Returns a dictionary of dictionaries. The keys for the first
dictionary will be the interfaces in the devices.
CLI Example:
.. code-block:: bash
salt '*' net.interfaces
Example output:
.. code-block:: python
{
'Management1': {
'is_up': False,
'is_enabled': False,
'description': '',
'last_flapped': -1,
'speed': 1000,
'mac_address': 'dead:beef:dead',
},
'Ethernet1':{
'is_up': True,
'is_enabled': True,
'description': 'foo',
'last_flapped': 1429978575.1554043,
'speed': 1000,
'mac_address': 'beef:dead:beef',
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_interfaces',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def lldp(interface='', **kwargs): # pylint: disable=unused-argument
'''
Returns a detailed view of the LLDP neighbors.
:param interface: interface name to filter on
:return: A dictionary with the LLDL neighbors. The keys are the
interfaces with LLDP activated on.
CLI Example:
.. code-block:: bash
salt '*' net.lldp
salt '*' net.lldp interface='TenGigE0/0/0/8'
Example output:
.. code-block:: python
{
'TenGigE0/0/0/8': [
{
'parent_interface': 'Bundle-Ether8',
'interface_description': 'TenGigE0/0/0/8',
'remote_chassis_id': '8c60.4f69.e96c',
'remote_system_name': 'switch',
'remote_port': 'Eth2/2/1',
'remote_port_description': 'Ethernet2/2/1',
'remote_system_description': 'Cisco Nexus Operating System (NX-OS) Software 7.1(0)N1(1a)
TAC support: http://www.cisco.com/tac
Copyright (c) 2002-2015, Cisco Systems, Inc. All rights reserved.',
'remote_system_capab': 'B, R',
'remote_system_enable_capab': 'B'
}
]
}
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_lldp_neighbors_detail',
**{
}
)
if not proxy_output.get('result'):
return proxy_output
lldp_neighbors = proxy_output.get('out')
if interface:
lldp_neighbors = {interface: lldp_neighbors.get(interface)}
proxy_output.update({
'out': lldp_neighbors
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def mac(address='', interface='', vlan=0, **kwargs): # pylint: disable=unused-argument
'''
Returns the MAC Address Table on the device.
:param address: MAC address to filter on
:param interface: Interface name to filter on
:param vlan: VLAN identifier
:return: A list of dictionaries representing the entries in the MAC Address Table
CLI Example:
.. code-block:: bash
salt '*' net.mac
salt '*' net.mac vlan=10
Example output:
.. code-block:: python
[
{
'mac' : '00:1c:58:29:4a:71',
'interface' : 'xe-3/0/2',
'static' : False,
'active' : True,
'moves' : 1,
'vlan' : 10,
'last_move' : 1454417742.58
},
{
'mac' : '8c:60:4f:58:e1:c1',
'interface' : 'xe-1/0/1',
'static' : False,
'active' : True,
'moves' : 2,
'vlan' : 42,
'last_move' : 1453191948.11
}
]
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_mac_address_table',
**{
}
)
if not proxy_output.get('result'):
# if negative, leave the output unchanged
return proxy_output
mac_address_table = proxy_output.get('out')
if vlan and isinstance(vlan, int):
mac_address_table = _filter_list(mac_address_table, 'vlan', vlan)
if address:
mac_address_table = _filter_list(mac_address_table, 'mac', address)
if interface:
mac_address_table = _filter_list(mac_address_table, 'interface', interface)
proxy_output.update({
'out': mac_address_table
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def config(source=None, **kwargs): # pylint: disable=unused-argument
'''
.. versionadded:: 2017.7.0
Return the whole configuration of the network device. By default, it will
return all possible configuration sources supported by the network device.
At most, there will be:
- running config
- startup config
- candidate config
To return only one of the configurations, you can use the ``source``
argument.
source
Which configuration type you want to display, default is all of them.
Options:
- running
- candidate
- startup
:return:
The object returned is a dictionary with the following keys:
- running (string): Representation of the native running configuration.
- candidate (string): Representation of the native candidate configuration.
If the device doesn't differentiate between running and startup
configuration this will an empty string.
- startup (string): Representation of the native startup configuration.
If the device doesn't differentiate between running and startup
configuration this will an empty string.
CLI Example:
.. code-block:: bash
salt '*' net.config
salt '*' net.config source=candidate
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_config',
**{
'retrieve': source
}
)
@salt.utils.napalm.proxy_napalm_wrap
def optics(**kwargs): # pylint: disable=unused-argument
'''
.. versionadded:: 2017.7.0
Fetches the power usage on the various transceivers installed
on the network device (in dBm), and returns a view that conforms with the
OpenConfig model openconfig-platform-transceiver.yang.
:return:
Returns a dictionary where the keys are as listed below:
* intf_name (unicode)
* physical_channels
* channels (list of dicts)
* index (int)
* state
* input_power
* instant (float)
* avg (float)
* min (float)
* max (float)
* output_power
* instant (float)
* avg (float)
* min (float)
* max (float)
* laser_bias_current
* instant (float)
* avg (float)
* min (float)
* max (float)
CLI Example:
.. code-block:: bash
salt '*' net.optics
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_optics',
**{
}
)
# <---- Call NAPALM getters --------------------------------------------------------------------------------------------
# ----- Configuration specific functions ------------------------------------------------------------------------------>
@salt.utils.napalm.proxy_napalm_wrap
def load_config(filename=None,
text=None,
test=False,
commit=True,
debug=False,
replace=False,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
commit_jid=None,
inherit_napalm_device=None,
saltenv='base',
**kwargs): # pylint: disable=unused-argument
'''
Applies configuration changes on the device. It can be loaded from a file or from inline string.
If you send both a filename and a string containing the configuration, the file has higher precedence.
By default this function will commit the changes. If there are no changes, it does not commit and
the flag ``already_configured`` will be set as ``True`` to point this out.
To avoid committing the configuration, set the argument ``test`` to ``True`` and will discard (dry run).
To keep the changes but not commit, set ``commit`` to ``False``.
To replace the config, set ``replace`` to ``True``.
filename
Path to the file containing the desired configuration.
This can be specified using the absolute path to the file,
or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
.. versionchanged:: 2018.3.0
text
String containing the desired configuration.
This argument is ignored when ``filename`` is specified.
test: False
Dry run? If set as ``True``, will apply the config, discard and return the changes. Default: ``False``
and will commit the changes on the device.
commit: True
Commit? Default: ``True``.
debug: False
Debug mode. Will insert a new key under the output dictionary, as ``loaded_config`` containing the raw
configuration loaded on the device.
.. versionadded:: 2016.11.2
replace: False
Load and replace the configuration. Default: ``False``.
.. versionadded:: 2016.11.2
commit_in: ``None``
Commit the changes in a specific number of minutes / hours. Example of
accepted formats: ``5`` (commit in 5 minutes), ``2m`` (commit in 2
minutes), ``1h`` (commit the changes in 1 hour)`, ``5h30m`` (commit
the changes in 5 hours and 30 minutes).
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
commit_at: ``None``
Commit the changes at a specific time. Example of accepted formats:
``1am`` (will commit the changes at the next 1AM), ``13:20`` (will
commit at 13:20), ``1:20am``, etc.
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
revert_in: ``None``
Commit and revert the changes in a specific number of minutes / hours.
Example of accepted formats: ``5`` (revert in 5 minutes), ``2m`` (revert
in 2 minutes), ``1h`` (revert the changes in 1 hour)`, ``5h30m`` (revert
the changes in 5 hours and 30 minutes).
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
revert_at: ``None``
Commit and revert the changes at a specific time. Example of accepted
formats: ``1am`` (will commit and revert the changes at the next 1AM),
``13:20`` (will commit and revert at 13:20), ``1:20am``, etc.
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
saltenv: ``base``
Specifies the Salt environment name.
.. versionadded:: 2018.3.0
:return: a dictionary having the following keys:
* result (bool): if the config was applied successfully. It is ``False`` only in case of failure. In case \
there are no changes to be applied and successfully performs all operations it is still ``True`` and so will be \
the ``already_configured`` flag (example below)
* comment (str): a message for the user
* already_configured (bool): flag to check if there were no changes applied
* loaded_config (str): the configuration loaded on the device. Requires ``debug`` to be set as ``True``
* diff (str): returns the config changes applied
CLI Example:
.. code-block:: bash
salt '*' net.load_config text='ntp peer 192.168.0.1'
salt '*' net.load_config filename='/absolute/path/to/your/file'
salt '*' net.load_config filename='/absolute/path/to/your/file' test=True
salt '*' net.load_config filename='/absolute/path/to/your/file' commit=False
Example output:
.. code-block:: python
{
'comment': 'Configuration discarded.',
'already_configured': False,
'result': True,
'diff': '[edit interfaces xe-0/0/5]+ description "Adding a description";'
}
'''
fun = 'load_merge_candidate'
if replace:
fun = 'load_replace_candidate'
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
if filename:
text = __salt__['cp.get_file_str'](filename, saltenv=saltenv)
if text is False:
# When using salt:// or https://, if the resource is not available,
# it will either raise an exception, or return False.
ret = {
'result': False,
'out': None
}
ret['comment'] = 'Unable to read from {}. Please specify a valid file or text.'.format(filename)
log.error(ret['comment'])
return ret
if commit_jid:
# When the commit_jid argument is passed, it probably is a scheduled
# commit to be executed, and filename is a temporary file which
# can be removed after reading it.
salt.utils.files.safe_rm(filename)
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
fun,
**{
'config': text
}
)
return _config_logic(napalm_device, # pylint: disable=undefined-variable
_loaded,
test=test,
debug=debug,
replace=replace,
commit_config=commit,
loaded_config=text,
commit_at=commit_at,
commit_in=commit_in,
revert_in=revert_in,
revert_at=revert_at,
commit_jid=commit_jid,
**kwargs)
@salt.utils.napalm.proxy_napalm_wrap
def load_template(template_name=None,
template_source=None,
context=None,
defaults=None,
template_engine='jinja',
saltenv='base',
template_hash=None,
template_hash_name=None,
skip_verify=False,
test=False,
commit=True,
debug=False,
replace=False,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
inherit_napalm_device=None, # pylint: disable=unused-argument
**template_vars):
'''
Renders a configuration template (default: Jinja) and loads the result on the device.
By default this function will commit the changes. If there are no changes,
it does not commit, discards he config and the flag ``already_configured``
will be set as ``True`` to point this out.
To avoid committing the configuration, set the argument ``test`` to ``True``
and will discard (dry run).
To preserve the changes, set ``commit`` to ``False``.
However, this is recommended to be used only in exceptional cases
when there are applied few consecutive states
and/or configuration changes.
Otherwise the user might forget that the config DB is locked
and the candidate config buffer is not cleared/merged in the running config.
To replace the config, set ``replace`` to ``True``.
template_name
Identifies path to the template source.
The template can be either stored on the local machine, either remotely.
The recommended location is under the ``file_roots``
as specified in the master config file.
For example, let's suppose the ``file_roots`` is configured as:
.. code-block:: yaml
file_roots:
base:
- /etc/salt/states
Placing the template under ``/etc/salt/states/templates/example.jinja``,
it can be used as ``salt://templates/example.jinja``.
Alternatively, for local files, the user can specify the absolute path.
If remotely, the source can be retrieved via ``http``, ``https`` or ``ftp``.
Examples:
- ``salt://my_template.jinja``
- ``/absolute/path/to/my_template.jinja``
- ``http://example.com/template.cheetah``
- ``https:/example.com/template.mako``
- ``ftp://example.com/template.py``
.. versionchanged:: 2019.2.0
This argument can now support a list of templates to be rendered.
The resulting configuration text is loaded at once, as a single
configuration chunk.
template_source: None
Inline config template to be rendered and loaded on the device.
template_hash: None
Hash of the template file. Format: ``{hash_type: 'md5', 'hsum': <md5sum>}``
.. versionadded:: 2016.11.2
context: None
Overrides default context variables passed to the template.
.. versionadded:: 2019.2.0
template_hash_name: None
When ``template_hash`` refers to a remote file,
this specifies the filename to look for in that file.
.. versionadded:: 2016.11.2
saltenv: ``base``
Specifies the template environment.
This will influence the relative imports inside the templates.
.. versionadded:: 2016.11.2
template_engine: jinja
The following templates engines are supported:
- :mod:`cheetah<salt.renderers.cheetah>`
- :mod:`genshi<salt.renderers.genshi>`
- :mod:`jinja<salt.renderers.jinja>`
- :mod:`mako<salt.renderers.mako>`
- :mod:`py<salt.renderers.py>`
- :mod:`wempy<salt.renderers.wempy>`
.. versionadded:: 2016.11.2
skip_verify: True
If ``True``, hash verification of remote file sources
(``http://``, ``https://``, ``ftp://``) will be skipped,
and the ``source_hash`` argument will be ignored.
.. versionadded:: 2016.11.2
test: False
Dry run? If set to ``True``, will apply the config,
discard and return the changes.
Default: ``False`` and will commit the changes on the device.
commit: True
Commit? (default: ``True``)
debug: False
Debug mode. Will insert a new key under the output dictionary,
as ``loaded_config`` containing the raw result after the template was rendered.
.. versionadded:: 2016.11.2
replace: False
Load and replace the configuration.
.. versionadded:: 2016.11.2
commit_in: ``None``
Commit the changes in a specific number of minutes / hours. Example of
accepted formats: ``5`` (commit in 5 minutes), ``2m`` (commit in 2
minutes), ``1h`` (commit the changes in 1 hour)`, ``5h30m`` (commit
the changes in 5 hours and 30 minutes).
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
commit_at: ``None``
Commit the changes at a specific time. Example of accepted formats:
``1am`` (will commit the changes at the next 1AM), ``13:20`` (will
commit at 13:20), ``1:20am``, etc.
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
revert_in: ``None``
Commit and revert the changes in a specific number of minutes / hours.
Example of accepted formats: ``5`` (revert in 5 minutes), ``2m`` (revert
in 2 minutes), ``1h`` (revert the changes in 1 hour)`, ``5h30m`` (revert
the changes in 5 hours and 30 minutes).
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
revert_at: ``None``
Commit and revert the changes at a specific time. Example of accepted
formats: ``1am`` (will commit and revert the changes at the next 1AM),
``13:20`` (will commit and revert at 13:20), ``1:20am``, etc.
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
defaults: None
Default variables/context passed to the template.
.. versionadded:: 2016.11.2
template_vars
Dictionary with the arguments/context to be used when the template is rendered.
.. note::
Do not explicitly specify this argument. This represents any other
variable that will be sent to the template rendering system.
Please see the examples below!
.. note::
It is more recommended to use the ``context`` argument to avoid
conflicts between CLI arguments and template variables.
:return: a dictionary having the following keys:
- result (bool): if the config was applied successfully. It is ``False``
only in case of failure. In case there are no changes to be applied and
successfully performs all operations it is still ``True`` and so will be
the ``already_configured`` flag (example below)
- comment (str): a message for the user
- already_configured (bool): flag to check if there were no changes applied
- loaded_config (str): the configuration loaded on the device, after
rendering the template. Requires ``debug`` to be set as ``True``
- diff (str): returns the config changes applied
The template can use variables from the ``grains``, ``pillar`` or ``opts``, for example:
.. code-block:: jinja
{% set router_model = grains.get('model') -%}
{% set router_vendor = grains.get('vendor') -%}
{% set os_version = grains.get('version') -%}
{% set hostname = pillar.get('proxy', {}).get('host') -%}
{% if router_vendor|lower == 'juniper' %}
system {
host-name {{hostname}};
}
{% elif router_vendor|lower == 'cisco' %}
hostname {{hostname}}
{% endif %}
CLI Examples:
.. code-block:: bash
salt '*' net.load_template set_ntp_peers peers=[192.168.0.1] # uses NAPALM default templates
# inline template:
salt -G 'os:junos' net.load_template template_source='system { host-name {{host_name}}; }' \
host_name='MX480.lab'
# inline template using grains info:
salt -G 'os:junos' net.load_template \
template_source='system { host-name {{grains.model}}.lab; }'
# if the device is a MX480, the command above will set the hostname as: MX480.lab
# inline template using pillar data:
salt -G 'os:junos' net.load_template template_source='system { host-name {{pillar.proxy.host}}; }'
salt '*' net.load_template https://bit.ly/2OhSgqP hostname=example # will commit
salt '*' net.load_template https://bit.ly/2OhSgqP hostname=example test=True # dry run
salt '*' net.load_template salt://templates/example.jinja debug=True # Using the salt:// URI
# render a mako template:
salt '*' net.load_template salt://templates/example.mako template_engine=mako debug=True
# render remote template
salt -G 'os:junos' net.load_template http://bit.ly/2fReJg7 test=True debug=True peers=['192.168.0.1']
salt -G 'os:ios' net.load_template http://bit.ly/2gKOj20 test=True debug=True peers=['192.168.0.1']
# render multiple templates at once
salt '*' net.load_template "['https://bit.ly/2OhSgqP', 'salt://templates/example.jinja']" context="{'hostname': 'example'}"
Example output:
.. code-block:: python
{
'comment': '',
'already_configured': False,
'result': True,
'diff': '[edit system]+ host-name edge01.bjm01',
'loaded_config': 'system { host-name edge01.bjm01; }''
}
'''
_rendered = ''
_loaded = {
'result': True,
'comment': '',
'out': None
}
loaded_config = None
# prechecks
deprecated_args = ('template_user', 'template_attrs', 'template_group', 'template_mode')
for deprecated_arg in deprecated_args:
if template_vars.get(deprecated_arg):
del template_vars[deprecated_arg]
salt.utils.versions.warn_until(
'Sodium',
('The \'{arg}\' argument to \'net.load_template\' is deprecated '
'and has been ignored').format(arg=deprecated_arg)
)
if template_engine not in salt.utils.templates.TEMPLATE_REGISTRY:
_loaded.update({
'result': False,
'comment': 'Invalid templating engine! Choose between: {tpl_eng_opts}'.format(
tpl_eng_opts=', '.join(list(salt.utils.templates.TEMPLATE_REGISTRY.keys()))
)
})
return _loaded # exit
# to check if will be rendered by salt or NAPALM
salt_render_prefixes = ('salt://', 'http://', 'https://', 'ftp://')
salt_render = False
file_exists = False
if not isinstance(template_name, (tuple, list)):
for salt_render_prefix in salt_render_prefixes:
if not salt_render:
salt_render = salt_render or template_name.startswith(salt_render_prefix)
file_exists = __salt__['file.file_exists'](template_name)
if template_source or file_exists or salt_render or isinstance(template_name, (tuple, list)):
# either inline template
# either template in a custom path
# either abs path send
# either starts with salt:// and
# then use Salt render system
if context is None:
context = {}
context.update(template_vars)
# if needed to render the template send as inline arg
if template_source:
# render the content
_rendered = __salt__['file.apply_template_on_contents'](
contents=template_source,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv
)
if not isinstance(_rendered, six.string_types):
if 'result' in _rendered:
_loaded['result'] = _rendered['result']
else:
_loaded['result'] = False
if 'comment' in _rendered:
_loaded['comment'] = _rendered['comment']
else:
_loaded['comment'] = 'Error while rendering the template.'
return _loaded
else:
# render the file - either local, either remote
if not isinstance(template_name, (list, tuple)):
template_name = [template_name]
if template_hash_name and not isinstance(template_hash_name, (list, tuple)):
template_hash_name = [template_hash_name]
elif not template_hash_name:
template_hash_name = [None] * len(template_name)
if template_hash and isinstance(template_hash, six.string_types) and not\
(template_hash.startswith('salt://') or template_hash.startswith('file://')):
# If the template hash is passed as string, and it's not a file
# (starts with the salt:// or file:// URI), then make it a list
# of 1 element (for the iteration below)
template_hash = [template_hash]
elif template_hash and isinstance(template_hash, six.string_types) and\
(template_hash.startswith('salt://') or template_hash.startswith('file://')):
# If the template hash is a file URI, then provide the same value
# for each of the templates in the list, as probably they all
# share the same hash file, otherwise the user should provide
# this as a list
template_hash = [template_hash] * len(template_name)
elif not template_hash:
template_hash = [None] * len(template_name)
for tpl_index, tpl_name in enumerate(template_name):
tpl_hash = template_hash[tpl_index]
tpl_hash_name = template_hash_name[tpl_index]
_rand_filename = __salt__['random.hash'](tpl_name, 'md5')
_temp_file = __salt__['file.join']('/tmp', _rand_filename)
_managed = __salt__['file.get_managed'](name=_temp_file,
source=tpl_name,
source_hash=tpl_hash,
source_hash_name=tpl_hash_name,
user=None,
group=None,
mode=None,
attrs=None,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv,
skip_verify=skip_verify)
if not isinstance(_managed, (list, tuple)) and isinstance(_managed, six.string_types):
_loaded['comment'] += _managed
_loaded['result'] = False
elif isinstance(_managed, (list, tuple)) and not _managed:
_loaded['result'] = False
_loaded['comment'] += 'Error while rendering the template.'
elif isinstance(_managed, (list, tuple)) and not _managed[0]:
_loaded['result'] = False
_loaded['comment'] += _managed[-1] # contains the error message
if _loaded['result']: # all good
_temp_tpl_file = _managed[0]
_temp_tpl_file_exists = __salt__['file.file_exists'](_temp_tpl_file)
if not _temp_tpl_file_exists:
_loaded['result'] = False
_loaded['comment'] += 'Error while rendering the template.'
return _loaded
_rendered += __salt__['file.read'](_temp_tpl_file)
__salt__['file.remove'](_temp_tpl_file)
else:
return _loaded # exit
loaded_config = _rendered
if _loaded['result']: # all good
fun = 'load_merge_candidate'
if replace: # replace requested
fun = 'load_replace_candidate'
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
fun,
**{
'config': _rendered
}
)
else:
salt.utils.versions.warn_until(
'Sodium',
'Native NAPALM templates support will be removed in the Sodium '
'release. Please consider using the Salt rendering pipeline instead.'
'If you are using the \'netntp\', \'netsnmp\', or \'netusers\' Salt '
'State modules, you can ignore this message'
)
# otherwise, use NAPALM render system, injecting pillar/grains/opts vars
load_templates_params = defaults if defaults else {}
load_templates_params.update(template_vars)
load_templates_params.update(
{
'template_name': template_name,
'template_source': template_source, # inline template
'pillar': __pillar__, # inject pillar content
'grains': __grains__, # inject grains content
'opts': __opts__ # inject opts content
}
)
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
# so we'll set the CLOSE global explicitly as False
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'load_template',
**load_templates_params
)
return _config_logic(napalm_device, # pylint: disable=undefined-variable
_loaded,
test=test,
debug=debug,
replace=replace,
commit_config=commit,
loaded_config=loaded_config,
commit_at=commit_at,
commit_in=commit_in,
revert_in=revert_in,
revert_at=revert_at,
**template_vars)
@salt.utils.napalm.proxy_napalm_wrap
def commit(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Commits the configuration changes made on the network device.
CLI Example:
.. code-block:: bash
salt '*' net.commit
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'commit_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def discard_config(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
"""
Discards the changes applied.
CLI Example:
.. code-block:: bash
salt '*' net.discard_config
"""
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'discard_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def compare_config(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Returns the difference between the running config and the candidate config.
CLI Example:
.. code-block:: bash
salt '*' net.compare_config
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'compare_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def rollback(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Rollbacks the configuration.
CLI Example:
.. code-block:: bash
salt '*' net.rollback
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'rollback',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def config_changed(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Will prompt if the configuration has been changed.
:return: A tuple with a boolean that specifies if the config was changed on the device.\
And a string that provides more details of the reason why the configuration was not changed.
CLI Example:
.. code-block:: bash
salt '*' net.config_changed
'''
is_config_changed = False
reason = ''
try_compare = compare_config(inherit_napalm_device=napalm_device) # pylint: disable=undefined-variable
if try_compare.get('result'):
if try_compare.get('out'):
is_config_changed = True
else:
reason = 'Configuration was not changed on the device.'
else:
reason = try_compare.get('comment')
return is_config_changed, reason
@salt.utils.napalm.proxy_napalm_wrap
def config_control(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Will check if the configuration was changed.
If differences found, will try to commit.
In case commit unsuccessful, will try to rollback.
:return: A tuple with a boolean that specifies if the config was changed/committed/rollbacked on the device.\
And a string that provides more details of the reason why the configuration was not committed properly.
CLI Example:
.. code-block:: bash
salt '*' net.config_control
'''
result = True
comment = ''
changed, not_changed_rsn = config_changed(inherit_napalm_device=napalm_device) # pylint: disable=undefined-variable
if not changed:
return (changed, not_changed_rsn)
# config changed, thus let's try to commit
try_commit = commit()
if not try_commit.get('result'):
result = False
comment = 'Unable to commit the changes: {reason}.\n\
Will try to rollback now!'.format(
reason=try_commit.get('comment')
)
try_rollback = rollback()
if not try_rollback.get('result'):
comment += '\nCannot rollback! {reason}'.format(
reason=try_rollback.get('comment')
)
return result, comment
def cancel_commit(jid):
'''
.. versionadded:: 2019.2.0
Cancel a commit scheduled to be executed via the ``commit_in`` and
``commit_at`` arguments from the
:py:func:`net.load_template <salt.modules.napalm_network.load_template>` or
:py:func:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit ID is displayed when the commit is scheduled
via the functions named above.
CLI Example:
.. code-block:: bash
salt '*' net.cancel_commit 20180726083540640360
'''
job_name = '__napalm_commit_{}'.format(jid)
removed = __salt__['schedule.delete'](job_name)
if removed['result']:
saved = __salt__['schedule.save']()
removed['comment'] = 'Commit #{jid} cancelled.'.format(jid=jid)
else:
removed['comment'] = 'Unable to find commit #{jid}.'.format(jid=jid)
return removed
def confirm_commit(jid):
'''
.. versionadded:: 2019.2.0
Confirm a commit scheduled to be reverted via the ``revert_in`` and
``revert_at`` arguments from the
:mod:`net.load_template <salt.modules.napalm_network.load_template>` or
:mod:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit ID is displayed when the commit confirmed
is scheduled via the functions named above.
CLI Example:
.. code-block:: bash
salt '*' net.confirm_commit 20180726083540640360
'''
if __grains__['os'] == 'junos':
# Confirm the commit, by committing (i.e., invoking the RPC call)
confirmed = __salt__['napalm.junos_commit']()
confirmed['result'] = confirmed.pop('out')
confirmed['comment'] = confirmed.pop('message')
else:
confirmed = cancel_commit(jid)
if confirmed['result']:
confirmed['comment'] = 'Commit #{jid} confirmed.'.format(jid=jid)
return confirmed
def save_config(source=None,
path=None):
'''
.. versionadded:: 2019.2.0
Save the configuration to a file on the local file system.
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``,
``startup``. Default: ``running``.
path
Absolute path to file where to save the configuration.
To push the files to the Master, use
:mod:`cp.push <salt.modules.cp.push>` Execution function.
CLI Example:
.. code-block:: bash
salt '*' net.save_config source=running
'''
if not source:
source = 'running'
if not path:
path = salt.utils.files.mkstemp()
running_config = __salt__['net.config'](source=source)
if not running_config or not running_config['result']:
log.error('Unable to retrieve the config')
return running_config
with salt.utils.files.fopen(path, 'w') as fh_:
fh_.write(running_config['out'][source])
return {
'result': True,
'out': path,
'comment': '{source} config saved to {path}'.format(source=source, path=path)
}
def replace_pattern(pattern,
repl,
count=0,
flags=8,
bufsize=1,
append_if_not_found=False,
prepend_if_not_found=False,
not_found_content=None,
search_only=False,
show_changes=True,
backslash_literal=False,
source=None,
path=None,
test=False,
replace=True,
debug=False,
commit=True):
'''
.. versionadded:: 2019.2.0
Replace occurrences of a pattern in the configuration source. If
``show_changes`` is ``True``, then a diff of what changed will be returned,
otherwise a ``True`` will be returned when changes are made, and ``False``
when no changes are made.
This is a pure Python implementation that wraps Python's :py:func:`~re.sub`.
pattern
A regular expression, to be matched using Python's
:py:func:`~re.search`.
repl
The replacement text.
count: ``0``
Maximum number of pattern occurrences to be replaced. If count is a
positive integer ``n``, only ``n`` occurrences will be replaced,
otherwise all occurrences will be replaced.
flags (list or int): ``8``
A list of flags defined in the ``re`` module documentation from the
Python standard library. Each list item should be a string that will
correlate to the human-friendly flag name. E.g., ``['IGNORECASE',
'MULTILINE']``. Optionally, ``flags`` may be an int, with a value
corresponding to the XOR (``|``) of all the desired flags. Defaults to
8 (which supports 'MULTILINE').
bufsize (int or str): ``1``
How much of the configuration to buffer into memory at once. The
default value ``1`` processes one line at a time. The special value
``file`` may be specified which will read the entire file into memory
before processing.
append_if_not_found: ``False``
If set to ``True``, and pattern is not found, then the content will be
appended to the file.
prepend_if_not_found: ``False``
If set to ``True`` and pattern is not found, then the content will be
prepended to the file.
not_found_content
Content to use for append/prepend if not found. If None (default), uses
``repl``. Useful when ``repl`` uses references to group in pattern.
search_only: ``False``
If set to true, this no changes will be performed on the file, and this
function will simply return ``True`` if the pattern was matched, and
``False`` if not.
show_changes: ``True``
If ``True``, return a diff of changes made. Otherwise, return ``True``
if changes were made, and ``False`` if not.
backslash_literal: ``False``
Interpret backslashes as literal backslashes for the repl and not
escape characters. This will help when using append/prepend so that
the backslashes are not interpreted for the repl on the second run of
the state.
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path
Save the temporary configuration to a specific path, then read from
there.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' net.replace_pattern "bind-address\\s*=" "bind-address:"
CLI Example:
.. code-block:: bash
salt '*' net.replace_pattern PREFIX-LIST_NAME new-prefix-list-name
salt '*' net.replace_pattern bgp-group-name new-bgp-group-name count=1
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
replace_pattern = __salt__['file.replace'](path,
pattern,
repl,
count=count,
flags=flags,
bufsize=bufsize,
append_if_not_found=append_if_not_found,
prepend_if_not_found=prepend_if_not_found,
not_found_content=not_found_content,
search_only=search_only,
show_changes=show_changes,
backslash_literal=backslash_literal)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
def blockreplace(marker_start,
marker_end,
content='',
append_if_not_found=False,
prepend_if_not_found=False,
show_changes=True,
append_newline=False,
source='running',
path=None,
test=False,
commit=True,
debug=False,
replace=True):
'''
.. versionadded:: 2019.2.0
Replace content of the configuration source, delimited by the line markers.
A block of content delimited by comments can help you manage several lines
without worrying about old entries removal.
marker_start
The line content identifying a line as the start of the content block.
Note that the whole line containing this marker will be considered,
so whitespace or extra content before or after the marker is included
in final output.
marker_end
The line content identifying a line as the end of the content block.
Note that the whole line containing this marker will be considered,
so whitespace or extra content before or after the marker is included
in final output.
content
The content to be used between the two lines identified by
``marker_start`` and ``marker_stop``.
append_if_not_found: ``False``
If markers are not found and set to True then, the markers and content
will be appended to the file.
prepend_if_not_found: ``False``
If markers are not found and set to True then, the markers and content
will be prepended to the file.
append_newline: ``False``
Controls whether or not a newline is appended to the content block.
If the value of this argument is ``True`` then a newline will be added
to the content block. If it is ``False``, then a newline will not be
added to the content block. If it is ``None`` then a newline will only
be added to the content block if it does not already end in a newline.
show_changes: ``True``
Controls how changes are presented. If ``True``, this function will
return the of the changes made.
If ``False``, then it will return a boolean (``True`` if any changes
were made, otherwise False).
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path: ``None``
Save the temporary configuration to a specific path, then read from
there. This argument is optional, can be used when you prefers a
particular location of the temporary file.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
CLI Example:
.. code-block:: bash
salt '*' net.blockreplace 'ntp' 'interface' ''
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
replace_pattern = __salt__['file.blockreplace'](path,
marker_start=marker_start,
marker_end=marker_end,
content=content,
append_if_not_found=append_if_not_found,
prepend_if_not_found=prepend_if_not_found,
show_changes=show_changes,
append_newline=append_newline)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
def patch(patchfile,
options='',
saltenv='base',
source_hash=None,
show_changes=True,
source='running',
path=None,
test=False,
commit=True,
debug=False,
replace=True):
'''
.. versionadded:: 2019.2.0
Apply a patch to the configuration source, and load the result into the
running config of the device.
patchfile
A patch file to apply to the configuration source.
options
Options to pass to patch.
source_hash
If the patch file (specified via the ``patchfile`` argument) is an
HTTP(S) or FTP URL and the file exists in the minion's file cache, this
option can be passed to keep the minion from re-downloading the file if
the cached copy matches the specified hash.
show_changes: ``True``
Controls how changes are presented. If ``True``, this function will
return the of the changes made.
If ``False``, then it will return a boolean (``True`` if any changes
were made, otherwise False).
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path: ``None``
Save the temporary configuration to a specific path, then read from
there. This argument is optional, can the user prefers a particular
location of the temporary file.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
CLI Example:
.. code-block:: bash
salt '*' net.patch https://example.com/running_config.patch
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
patchfile_cache = __salt__['cp.cache_file'](patchfile)
if patchfile_cache is False:
return {
'out': None,
'result': False,
'comment': 'The file "{}" does not exist.'.format(patchfile)
}
replace_pattern = __salt__['file.patch'](path,
patchfile_cache,
options=options)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
# <---- Configuration specific functions -------------------------------------------------------------------------------
|
saltstack/salt
|
salt/modules/napalm_network.py
|
arp
|
python
|
def arp(interface='', ipaddr='', macaddr='', **kwargs): # pylint: disable=unused-argument
'''
NAPALM returns a list of dictionaries with details of the ARP entries.
:param interface: interface name to filter on
:param ipaddr: IP address to filter on
:param macaddr: MAC address to filter on
:return: List of the entries in the ARP table
CLI Example:
.. code-block:: bash
salt '*' net.arp
salt '*' net.arp macaddr='5c:5e:ab:da:3c:f0'
Example output:
.. code-block:: python
[
{
'interface' : 'MgmtEth0/RSP0/CPU0/0',
'mac' : '5c:5e:ab:da:3c:f0',
'ip' : '172.17.17.1',
'age' : 1454496274.84
},
{
'interface': 'MgmtEth0/RSP0/CPU0/0',
'mac' : '66:0e:94:96:e0:ff',
'ip' : '172.17.17.2',
'age' : 1435641582.49
}
]
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_arp_table',
**{
}
)
if not proxy_output.get('result'):
return proxy_output
arp_table = proxy_output.get('out')
if interface:
arp_table = _filter_list(arp_table, 'interface', interface)
if ipaddr:
arp_table = _filter_list(arp_table, 'ip', ipaddr)
if macaddr:
arp_table = _filter_list(arp_table, 'mac', macaddr)
proxy_output.update({
'out': arp_table
})
return proxy_output
|
NAPALM returns a list of dictionaries with details of the ARP entries.
:param interface: interface name to filter on
:param ipaddr: IP address to filter on
:param macaddr: MAC address to filter on
:return: List of the entries in the ARP table
CLI Example:
.. code-block:: bash
salt '*' net.arp
salt '*' net.arp macaddr='5c:5e:ab:da:3c:f0'
Example output:
.. code-block:: python
[
{
'interface' : 'MgmtEth0/RSP0/CPU0/0',
'mac' : '5c:5e:ab:da:3c:f0',
'ip' : '172.17.17.1',
'age' : 1454496274.84
},
{
'interface': 'MgmtEth0/RSP0/CPU0/0',
'mac' : '66:0e:94:96:e0:ff',
'ip' : '172.17.17.2',
'age' : 1435641582.49
}
]
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_network.py#L885-L947
|
[
"def call(napalm_device, method, *args, **kwargs):\n '''\n Calls arbitrary methods from the network driver instance.\n Please check the readthedocs_ page for the updated list of getters.\n\n .. _readthedocs: http://napalm.readthedocs.org/en/latest/support/index.html#getters-support-matrix\n\n method\n Specifies the name of the method to be called.\n\n *args\n Arguments.\n\n **kwargs\n More arguments.\n\n :return: A dictionary with three keys:\n\n * result (True/False): if the operation succeeded\n * out (object): returns the object as-is from the call\n * comment (string): provides more details in case the call failed\n * traceback (string): complete traceback in case of exception. \\\n Please submit an issue including this traceback \\\n on the `correct driver repo`_ and make sure to read the FAQ_\n\n .. _`correct driver repo`: https://github.com/napalm-automation/napalm/issues/new\n .. FAQ_: https://github.com/napalm-automation/napalm#faq\n\n Example:\n\n .. code-block:: python\n\n salt.utils.napalm.call(\n napalm_object,\n 'cli',\n [\n 'show version',\n 'show chassis fan'\n ]\n )\n '''\n result = False\n out = None\n opts = napalm_device.get('__opts__', {})\n retry = kwargs.pop('__retry', True) # retry executing the task?\n force_reconnect = kwargs.get('force_reconnect', False)\n if force_reconnect:\n log.debug('Forced reconnection initiated')\n log.debug('The current opts (under the proxy key):')\n log.debug(opts['proxy'])\n opts['proxy'].update(**kwargs)\n log.debug('Updated to:')\n log.debug(opts['proxy'])\n napalm_device = get_device(opts)\n try:\n if not napalm_device.get('UP', False):\n raise Exception('not connected')\n # if connected will try to execute desired command\n kwargs_copy = {}\n kwargs_copy.update(kwargs)\n for karg, warg in six.iteritems(kwargs_copy):\n # lets clear None arguments\n # to not be sent to NAPALM methods\n if warg is None:\n kwargs.pop(karg)\n out = getattr(napalm_device.get('DRIVER'), method)(*args, **kwargs)\n # calls the method with the specified parameters\n result = True\n except Exception as error:\n # either not connected\n # either unable to execute the command\n hostname = napalm_device.get('HOSTNAME', '[unspecified hostname]')\n err_tb = traceback.format_exc() # let's get the full traceback and display for debugging reasons.\n if isinstance(error, NotImplementedError):\n comment = '{method} is not implemented for the NAPALM {driver} driver!'.format(\n method=method,\n driver=napalm_device.get('DRIVER_NAME')\n )\n elif retry and HAS_CONN_CLOSED_EXC_CLASS and isinstance(error, ConnectionClosedException):\n # Received disconection whilst executing the operation.\n # Instructed to retry (default behaviour)\n # thus trying to re-establish the connection\n # and re-execute the command\n # if any of the operations (close, open, call) will rise again ConnectionClosedException\n # it will fail loudly.\n kwargs['__retry'] = False # do not attempt re-executing\n comment = 'Disconnected from {device}. Trying to reconnect.'.format(device=hostname)\n log.error(err_tb)\n log.error(comment)\n log.debug('Clearing the connection with %s', hostname)\n call(napalm_device, 'close', __retry=False) # safely close the connection\n # Make sure we don't leave any TCP connection open behind\n # if we fail to close properly, we might not be able to access the\n log.debug('Re-opening the connection with %s', hostname)\n call(napalm_device, 'open', __retry=False)\n log.debug('Connection re-opened with %s', hostname)\n log.debug('Re-executing %s', method)\n return call(napalm_device, method, *args, **kwargs)\n # If still not able to reconnect and execute the task,\n # the proxy keepalive feature (if enabled) will attempt\n # to reconnect.\n # If the device is using a SSH-based connection, the failure\n # will also notify the paramiko transport and the `is_alive` flag\n # is going to be set correctly.\n # More background: the network device may decide to disconnect,\n # although the SSH session itself is alive and usable, the reason\n # being the lack of activity on the CLI.\n # Paramiko's keepalive doesn't help in this case, as the ServerAliveInterval\n # are targeting the transport layer, whilst the device takes the decision\n # when there isn't any activity on the CLI, thus at the application layer.\n # Moreover, the disconnect is silent and paramiko's is_alive flag will\n # continue to return True, although the connection is already unusable.\n # For more info, see https://github.com/paramiko/paramiko/issues/813.\n # But after a command fails, the `is_alive` flag becomes aware of these\n # changes and will return False from there on. And this is how the\n # Salt proxy keepalive helps: immediately after the first failure, it\n # will know the state of the connection and will try reconnecting.\n else:\n comment = 'Cannot execute \"{method}\" on {device}{port} as {user}. Reason: {error}!'.format(\n device=napalm_device.get('HOSTNAME', '[unspecified hostname]'),\n port=(':{port}'.format(port=napalm_device.get('OPTIONAL_ARGS', {}).get('port'))\n if napalm_device.get('OPTIONAL_ARGS', {}).get('port') else ''),\n user=napalm_device.get('USERNAME', ''),\n method=method,\n error=error\n )\n log.error(comment)\n log.error(err_tb)\n return {\n 'out': {},\n 'result': False,\n 'comment': comment,\n 'traceback': err_tb\n }\n finally:\n if opts and not_always_alive(opts) and napalm_device.get('CLOSE', True):\n # either running in a not-always-alive proxy\n # either running in a regular minion\n # close the connection when the call is over\n # unless the CLOSE is explicitly set as False\n napalm_device['DRIVER'].close()\n return {\n 'out': out,\n 'result': result,\n 'comment': ''\n }\n"
] |
# -*- coding: utf-8 -*-
'''
NAPALM Network
==============
Basic methods for interaction with the network device through the virtual proxy 'napalm'.
:codeauthor: Mircea Ulinic <mircea@cloudflare.com> & Jerome Fleury <jf@cloudflare.com>
:maturity: new
:depends: napalm
:platform: unix
Dependencies
------------
- :mod:`napalm proxy minion <salt.proxy.napalm>`
.. versionadded:: 2016.11.0
.. versionchanged:: 2017.7.0
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import time
import logging
import datetime
log = logging.getLogger(__name__)
# Import Salt libs
from salt.ext import six
import salt.utils.files
import salt.utils.napalm
import salt.utils.versions
import salt.utils.templates
# Import 3rd-party libs
try:
import jxmlease # pylint: disable=unused-import
HAS_JXMLEASE = True
except ImportError:
HAS_JXMLEASE = False
# ----------------------------------------------------------------------------------------------------------------------
# module properties
# ----------------------------------------------------------------------------------------------------------------------
__virtualname__ = 'net'
__proxyenabled__ = ['*']
__virtual_aliases__ = ('napalm_net',)
# uses NAPALM-based proxy to interact with network devices
# ----------------------------------------------------------------------------------------------------------------------
# property functions
# ----------------------------------------------------------------------------------------------------------------------
def __virtual__():
'''
NAPALM library must be installed for this module to work and run in a (proxy) minion.
'''
return salt.utils.napalm.virtual(__opts__, __virtualname__, __file__)
# ----------------------------------------------------------------------------------------------------------------------
# helper functions -- will not be exported
# ----------------------------------------------------------------------------------------------------------------------
def _filter_list(input_list, search_key, search_value):
'''
Filters a list of dictionary by a set of key-value pair.
:param input_list: is a list of dictionaries
:param search_key: is the key we are looking for
:param search_value: is the value we are looking for the key specified in search_key
:return: filered list of dictionaries
'''
output_list = list()
for dictionary in input_list:
if dictionary.get(search_key) == search_value:
output_list.append(dictionary)
return output_list
def _filter_dict(input_dict, search_key, search_value):
'''
Filters a dictionary of dictionaries by a key-value pair.
:param input_dict: is a dictionary whose values are lists of dictionaries
:param search_key: is the key in the leaf dictionaries
:param search_values: is the value in the leaf dictionaries
:return: filtered dictionary
'''
output_dict = dict()
for key, key_list in six.iteritems(input_dict):
key_list_filtered = _filter_list(key_list, search_key, search_value)
if key_list_filtered:
output_dict[key] = key_list_filtered
return output_dict
def _safe_commit_config(loaded_result, napalm_device):
_commit = commit(inherit_napalm_device=napalm_device) # calls the function commit, defined below
if not _commit.get('result', False):
# if unable to commit
loaded_result['comment'] += _commit['comment'] if _commit.get('comment') else 'Unable to commit.'
loaded_result['result'] = False
# unable to commit, something went wrong
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
return _commit
def _safe_dicard_config(loaded_result, napalm_device):
'''
'''
log.debug('Discarding the config')
log.debug(loaded_result)
_discarded = discard_config(inherit_napalm_device=napalm_device)
if not _discarded.get('result', False):
loaded_result['comment'] += _discarded['comment'] if _discarded.get('comment') \
else 'Unable to discard config.'
loaded_result['result'] = False
# make sure it notifies
# that something went wrong
_explicit_close(napalm_device)
__context__['retcode'] = 1
return loaded_result
return _discarded
def _explicit_close(napalm_device):
'''
Will explicily close the config session with the network device,
when running in a now-always-alive proxy minion or regular minion.
This helper must be used in configuration-related functions,
as the session is preserved and not closed before making any changes.
'''
if salt.utils.napalm.not_always_alive(__opts__):
# force closing the configuration session
# when running in a non-always-alive proxy
# or regular minion
try:
napalm_device['DRIVER'].close()
except Exception as err:
log.error('Unable to close the temp connection with the device:')
log.error(err)
log.error('Please report.')
def _config_logic(napalm_device,
loaded_result,
test=False,
debug=False,
replace=False,
commit_config=True,
loaded_config=None,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
commit_jid=None,
**kwargs):
'''
Builds the config logic for `load_config` and `load_template` functions.
'''
# As the Salt logic is built around independent events
# when it comes to configuration changes in the
# candidate DB on the network devices, we need to
# make sure we're using the same session.
# Hence, we need to pass the same object around.
# the napalm_device object is inherited from
# the load_config or load_template functions
# and forwarded to compare, discard, commit etc.
# then the decorator will make sure that
# if not proxy (when the connection is always alive)
# and the `inherit_napalm_device` is set,
# `napalm_device` will be overridden.
# See `salt.utils.napalm.proxy_napalm_wrap` decorator.
current_jid = kwargs.get('__pub_jid')
if not current_jid:
current_jid = '{0:%Y%m%d%H%M%S%f}'.format(datetime.datetime.now())
loaded_result['already_configured'] = False
loaded_result['loaded_config'] = ''
if debug:
loaded_result['loaded_config'] = loaded_config
_compare = compare_config(inherit_napalm_device=napalm_device)
if _compare.get('result', False):
loaded_result['diff'] = _compare.get('out')
loaded_result.pop('out', '') # not needed
else:
loaded_result['diff'] = None
loaded_result['result'] = False
loaded_result['comment'] = _compare.get('comment')
__context__['retcode'] = 1
return loaded_result
_loaded_res = loaded_result.get('result', False)
if not _loaded_res or test:
# if unable to load the config (errors / warnings)
# or in testing mode,
# will discard the config
if loaded_result['comment']:
loaded_result['comment'] += '\n'
if not loaded_result.get('diff', ''):
loaded_result['already_configured'] = True
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
loaded_result['comment'] += 'Configuration discarded.'
# loaded_result['result'] = False not necessary
# as the result can be true when test=True
_explicit_close(napalm_device)
if not loaded_result['result']:
__context__['retcode'] = 1
return loaded_result
if not test and commit_config:
# if not in testing mode and trying to commit
if commit_jid:
log.info('Committing the JID: %s', str(commit_jid))
removed = cancel_commit(commit_jid)
log.debug('Cleaned up the commit from the schedule')
log.debug(removed['comment'])
if loaded_result.get('diff', ''):
# if not testing mode
# and also the user wants to commit (default)
# and there are changes to commit
if commit_in or commit_at:
commit_time = __utils__['timeutil.get_time_at'](time_in=commit_in,
time_at=commit_in)
# schedule job
scheduled_job_name = '__napalm_commit_{}'.format(current_jid)
temp_file = salt.utils.files.mkstemp()
with salt.utils.files.fopen(temp_file, 'w') as fp_:
fp_.write(loaded_config)
scheduled = __salt__['schedule.add'](scheduled_job_name,
function='net.load_config',
job_kwargs={
'filename': temp_file,
'commit_jid': current_jid,
'replace': replace
},
once=commit_time)
log.debug('Scheduling job')
log.debug(scheduled)
saved = __salt__['schedule.save']() # ensure the schedule is
# persistent cross Minion restart
discarded = _safe_dicard_config(loaded_result, napalm_device)
# discard the changes
if not discarded['result']:
discarded['comment'] += ('Scheduled the job to be executed at {schedule_ts}, '
'but was unable to discard the config: \n').format(schedule_ts=commit_time)
return discarded
loaded_result['comment'] = ('Changes discarded for now, and scheduled commit at: {schedule_ts}.\n'
'The commit ID is: {current_jid}.\n'
'To discard this commit, you can execute: \n\n'
'salt {min_id} net.cancel_commit {current_jid}').format(schedule_ts=commit_time,
min_id=__opts__['id'],
current_jid=current_jid)
loaded_result['commit_id'] = current_jid
return loaded_result
log.debug('About to commit:')
log.debug(loaded_result['diff'])
if revert_in or revert_at:
revert_time = __utils__['timeutil.get_time_at'](time_in=revert_in,
time_at=revert_at)
if __grains__['os'] == 'junos':
if not HAS_JXMLEASE:
loaded_result['comment'] = ('This feature requires the library jxmlease to be installed.\n'
'To install, please execute: ``pip install jxmlease``.')
loaded_result['result'] = False
return loaded_result
timestamp_at = __utils__['timeutil.get_timestamp_at'](time_in=revert_in,
time_at=revert_at)
minutes = int((timestamp_at - time.time())/60)
_comm = __salt__['napalm.junos_commit'](confirm=minutes)
if not _comm['out']:
# If unable to commit confirm, should try to bail out
loaded_result['comment'] = 'Unable to commit confirm: {}'.format(_comm['message'])
loaded_result['result'] = False
# But before exiting, we must gracefully discard the config
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
else:
temp_file = salt.utils.files.mkstemp()
running_config = __salt__['net.config'](source='running')['out']['running']
with salt.utils.files.fopen(temp_file, 'w') as fp_:
fp_.write(running_config)
committed = _safe_commit_config(loaded_result, napalm_device)
if not committed['result']:
# If unable to commit, dicard the config (which is
# already done by the _safe_commit_config function), and
# return with the command and other details.
return loaded_result
scheduled_job_name = '__napalm_commit_{}'.format(current_jid)
scheduled = __salt__['schedule.add'](scheduled_job_name,
function='net.load_config',
job_kwargs={
'filename': temp_file,
'commit_jid': current_jid,
'replace': True
},
once=revert_time)
log.debug('Scheduling commit confirmed')
log.debug(scheduled)
saved = __salt__['schedule.save']()
loaded_result['comment'] = ('The commit ID is: {current_jid}.\n'
'This commit will be reverted at: {schedule_ts}, unless confirmed.\n'
'To confirm the commit and avoid reverting, you can execute:\n\n'
'salt {min_id} net.confirm_commit {current_jid}').format(schedule_ts=revert_time,
min_id=__opts__['id'],
current_jid=current_jid)
loaded_result['commit_id'] = current_jid
return loaded_result
committed = _safe_commit_config(loaded_result, napalm_device)
if not committed['result']:
return loaded_result
else:
# would like to commit, but there's no change
# need to call discard_config() to release the config DB
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
loaded_result['already_configured'] = True
loaded_result['comment'] = 'Already configured.'
_explicit_close(napalm_device)
if not loaded_result['result']:
__context__['retcode'] = 1
return loaded_result
# ----------------------------------------------------------------------------------------------------------------------
# callable functions
# ----------------------------------------------------------------------------------------------------------------------
@salt.utils.napalm.proxy_napalm_wrap
def connected(**kwargs): # pylint: disable=unused-argument
'''
Specifies if the connection to the device succeeded.
CLI Example:
.. code-block:: bash
salt '*' net.connected
'''
return {
'out': napalm_device.get('UP', False) # pylint: disable=undefined-variable
}
@salt.utils.napalm.proxy_napalm_wrap
def facts(**kwargs): # pylint: disable=unused-argument
'''
Returns characteristics of the network device.
:return: a dictionary with the following keys:
* uptime - Uptime of the device in seconds.
* vendor - Manufacturer of the device.
* model - Device model.
* hostname - Hostname of the device
* fqdn - Fqdn of the device
* os_version - String with the OS version running on the device.
* serial_number - Serial number of the device
* interface_list - List of the interfaces of the device
CLI Example:
.. code-block:: bash
salt '*' net.facts
Example output:
.. code-block:: python
{
'os_version': '13.3R6.5',
'uptime': 10117140,
'interface_list': [
'lc-0/0/0',
'pfe-0/0/0',
'pfh-0/0/0',
'xe-0/0/0',
'xe-0/0/1',
'xe-0/0/2',
'xe-0/0/3',
'gr-0/0/10',
'ip-0/0/10'
],
'vendor': 'Juniper',
'serial_number': 'JN131356FBFA',
'model': 'MX480',
'hostname': 're0.edge05.syd01',
'fqdn': 're0.edge05.syd01'
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_facts',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def environment(**kwargs): # pylint: disable=unused-argument
'''
Returns the environment of the device.
CLI Example:
.. code-block:: bash
salt '*' net.environment
Example output:
.. code-block:: python
{
'fans': {
'Bottom Rear Fan': {
'status': True
},
'Bottom Middle Fan': {
'status': True
},
'Top Middle Fan': {
'status': True
},
'Bottom Front Fan': {
'status': True
},
'Top Front Fan': {
'status': True
},
'Top Rear Fan': {
'status': True
}
},
'memory': {
'available_ram': 16349,
'used_ram': 4934
},
'temperature': {
'FPC 0 Exhaust A': {
'is_alert': False,
'temperature': 35.0,
'is_critical': False
}
},
'cpu': {
'1': {
'%usage': 19.0
},
'0': {
'%usage': 35.0
}
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_environment',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def cli(*commands, **kwargs): # pylint: disable=unused-argument
'''
Returns a dictionary with the raw output of all commands passed as arguments.
commands
List of commands to be executed on the device.
textfsm_parse: ``False``
Try parsing the outputs using the TextFSM templates.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``napalm_cli_textfsm_parse``.
textfsm_path
The path where the TextFSM templates can be found. This option implies
the usage of the TextFSM index file.
``textfsm_path`` can be either absolute path on the server,
either specified using the following URL mschemes: ``file://``,
``salt://``, ``http://``, ``https://``, ``ftp://``,
``s3://``, ``swift://``.
.. versionadded:: 2018.3.0
.. note::
This needs to be a directory with a flat structure, having an
index file (whose name can be specified using the ``index_file`` option)
and a number of TextFSM templates.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_path``.
textfsm_template
The path to a certain the TextFSM template.
This can be specified using the absolute path
to the file, or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
.. versionadded:: 2018.3.0
textfsm_template_dict
A dictionary with the mapping between a command
and the corresponding TextFSM path to use to extract the data.
The TextFSM paths can be specified as in ``textfsm_template``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``napalm_cli_textfsm_template_dict``.
platform_grain_name: ``os``
The name of the grain used to identify the platform name
in the TextFSM index file. Default: ``os``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_grain``.
platform_column_name: ``Platform``
The column name used to identify the platform,
exactly as specified in the TextFSM index file.
Default: ``Platform``.
.. versionadded:: 2018.3.0
.. note::
This is field is case sensitive, make sure
to assign the correct value to this option,
exactly as defined in the index file.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_column_name``.
index_file: ``index``
The name of the TextFSM index file, under the ``textfsm_path``. Default: ``index``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_index_file``.
saltenv: ``base``
Salt fileserver envrionment from which to retrieve the file.
Ignored if ``textfsm_path`` is not a ``salt://`` URL.
.. versionadded:: 2018.3.0
include_empty: ``False``
Include empty files under the ``textfsm_path``.
.. versionadded:: 2018.3.0
include_pat
Glob or regex to narrow down the files cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. versionadded:: 2018.3.0
exclude_pat
Glob or regex to exclude certain files from being cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. versionadded:: 2018.3.0
.. note::
If used with ``include_pat``, files matching this pattern will be
excluded from the subset of files defined by ``include_pat``.
CLI Example:
.. code-block:: bash
salt '*' net.cli "show version" "show chassis fan"
CLI Example with TextFSM template:
.. code-block:: bash
salt '*' net.cli textfsm_parse=True textfsm_path=salt://textfsm/
Example output:
.. code-block:: python
{
'show version and haiku': 'Hostname: re0.edge01.arn01
Model: mx480
Junos: 13.3R6.5
Help me, Obi-Wan
I just saw Episode Two
You're my only hope
',
'show chassis fan' : 'Item Status RPM Measurement
Top Rear Fan OK 3840 Spinning at intermediate-speed
Bottom Rear Fan OK 3840 Spinning at intermediate-speed
Top Middle Fan OK 3900 Spinning at intermediate-speed
Bottom Middle Fan OK 3840 Spinning at intermediate-speed
Top Front Fan OK 3810 Spinning at intermediate-speed
Bottom Front Fan OK 3840 Spinning at intermediate-speed
'
}
Example output with TextFSM parsing:
.. code-block:: json
{
"comment": "",
"result": true,
"out": {
"sh ver": [
{
"kernel": "9.1S3.5",
"documentation": "9.1S3.5",
"boot": "9.1S3.5",
"crypto": "9.1S3.5",
"chassis": "",
"routing": "9.1S3.5",
"base": "9.1S3.5",
"model": "mx960"
}
]
}
}
'''
raw_cli_outputs = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'cli',
**{
'commands': list(commands)
}
)
# thus we can display the output as is
# in case of errors, they'll be catched in the proxy
if not raw_cli_outputs['result']:
# Error -> dispaly the output as-is.
return raw_cli_outputs
textfsm_parse = kwargs.get('textfsm_parse') or __opts__.get('napalm_cli_textfsm_parse') or\
__pillar__.get('napalm_cli_textfsm_parse', False)
if not textfsm_parse:
# No TextFSM parsing required, return raw commands.
log.debug('No TextFSM parsing requested.')
return raw_cli_outputs
if 'textfsm.extract' not in __salt__ or 'textfsm.index' not in __salt__:
raw_cli_outputs['comment'] += 'Unable to process: is TextFSM installed?'
log.error(raw_cli_outputs['comment'])
return raw_cli_outputs
textfsm_template = kwargs.get('textfsm_template')
log.debug('textfsm_template: %s', textfsm_template)
textfsm_path = kwargs.get('textfsm_path') or __opts__.get('textfsm_path') or\
__pillar__.get('textfsm_path')
log.debug('textfsm_path: %s', textfsm_path)
textfsm_template_dict = kwargs.get('textfsm_template_dict') or __opts__.get('napalm_cli_textfsm_template_dict') or\
__pillar__.get('napalm_cli_textfsm_template_dict', {})
log.debug('TextFSM command-template mapping: %s', textfsm_template_dict)
index_file = kwargs.get('index_file') or __opts__.get('textfsm_index_file') or\
__pillar__.get('textfsm_index_file')
log.debug('index_file: %s', index_file)
platform_grain_name = kwargs.get('platform_grain_name') or __opts__.get('textfsm_platform_grain') or\
__pillar__.get('textfsm_platform_grain', 'os')
log.debug('platform_grain_name: %s', platform_grain_name)
platform_column_name = kwargs.get('platform_column_name') or __opts__.get('textfsm_platform_column_name') or\
__pillar__.get('textfsm_platform_column_name', 'Platform')
log.debug('platform_column_name: %s', platform_column_name)
saltenv = kwargs.get('saltenv', 'base')
include_empty = kwargs.get('include_empty', False)
include_pat = kwargs.get('include_pat')
exclude_pat = kwargs.get('exclude_pat')
processed_cli_outputs = {
'comment': raw_cli_outputs.get('comment', ''),
'result': raw_cli_outputs['result'],
'out': {}
}
log.debug('Starting to analyse the raw outputs')
for command in list(commands):
command_output = raw_cli_outputs['out'][command]
log.debug('Output from command: %s', command)
log.debug(command_output)
processed_command_output = None
if textfsm_path:
log.debug('Using the templates under %s', textfsm_path)
processed_cli_output = __salt__['textfsm.index'](command,
platform_grain_name=platform_grain_name,
platform_column_name=platform_column_name,
output=command_output.strip(),
textfsm_path=textfsm_path,
saltenv=saltenv,
include_empty=include_empty,
include_pat=include_pat,
exclude_pat=exclude_pat)
log.debug('Processed CLI output:')
log.debug(processed_cli_output)
if not processed_cli_output['result']:
log.debug('Apparently this didnt work, returnin the raw output')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {0}: {1}.'.format(command,
processed_cli_output['comment'])
log.error(processed_cli_outputs['comment'])
elif processed_cli_output['out']:
log.debug('All good, %s has a nice output!', command)
processed_command_output = processed_cli_output['out']
else:
comment = '''\nProcessing "{}" didn't fail, but didn't return anything either. Dumping raw.'''.format(
command)
processed_cli_outputs['comment'] += comment
log.error(comment)
processed_command_output = command_output
elif textfsm_template or command in textfsm_template_dict:
if command in textfsm_template_dict:
textfsm_template = textfsm_template_dict[command]
log.debug('Using %s to process the command: %s', textfsm_template, command)
processed_cli_output = __salt__['textfsm.extract'](textfsm_template,
raw_text=command_output,
saltenv=saltenv)
log.debug('Processed CLI output:')
log.debug(processed_cli_output)
if not processed_cli_output['result']:
log.debug('Apparently this didnt work, returning '
'the raw output')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {0}: {1}'.format(command,
processed_cli_output['comment'])
log.error(processed_cli_outputs['comment'])
elif processed_cli_output['out']:
log.debug('All good, %s has a nice output!', command)
processed_command_output = processed_cli_output['out']
else:
log.debug('Processing %s didnt fail, but didnt return'
' anything either. Dumping raw.', command)
processed_command_output = command_output
else:
log.error('No TextFSM template specified, or no TextFSM path defined')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {}.'.format(command)
processed_cli_outputs['out'][command] = processed_command_output
processed_cli_outputs['comment'] = processed_cli_outputs['comment'].strip()
return processed_cli_outputs
@salt.utils.napalm.proxy_napalm_wrap
def traceroute(destination, source=None, ttl=None, timeout=None, vrf=None, **kwargs): # pylint: disable=unused-argument
'''
Calls the method traceroute from the NAPALM driver object and returns a dictionary with the result of the traceroute
command executed on the device.
destination
Hostname or address of remote host
source
Source address to use in outgoing traceroute packets
ttl
IP maximum time-to-live value (or IPv6 maximum hop-limit value)
timeout
Number of seconds to wait for response (seconds)
vrf
VRF (routing instance) for traceroute attempt
.. versionadded:: 2016.11.4
CLI Example:
.. code-block:: bash
salt '*' net.traceroute 8.8.8.8
salt '*' net.traceroute 8.8.8.8 source=127.0.0.1 ttl=5 timeout=1
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'traceroute',
**{
'destination': destination,
'source': source,
'ttl': ttl,
'timeout': timeout,
'vrf': vrf
}
)
@salt.utils.napalm.proxy_napalm_wrap
def ping(destination, source=None, ttl=None, timeout=None, size=None, count=None, vrf=None, **kwargs): # pylint: disable=unused-argument
'''
Executes a ping on the network device and returns a dictionary as a result.
destination
Hostname or IP address of remote host
source
Source address of echo request
ttl
IP time-to-live value (IPv6 hop-limit value) (1..255 hops)
timeout
Maximum wait time after sending final packet (seconds)
size
Size of request packets (0..65468 bytes)
count
Number of ping requests to send (1..2000000000 packets)
vrf
VRF (routing instance) for ping attempt
.. versionadded:: 2016.11.4
CLI Example:
.. code-block:: bash
salt '*' net.ping 8.8.8.8
salt '*' net.ping 8.8.8.8 ttl=3 size=65468
salt '*' net.ping 8.8.8.8 source=127.0.0.1 timeout=1 count=100
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'ping',
**{
'destination': destination,
'source': source,
'ttl': ttl,
'timeout': timeout,
'size': size,
'count': count,
'vrf': vrf
}
)
@salt.utils.napalm.proxy_napalm_wrap
@salt.utils.napalm.proxy_napalm_wrap
def ipaddrs(**kwargs): # pylint: disable=unused-argument
'''
Returns IP addresses configured on the device.
:return: A dictionary with the IPv4 and IPv6 addresses of the interfaces.
Returns all configured IP addresses on all interfaces as a dictionary
of dictionaries. Keys of the main dictionary represent the name of the
interface. Values of the main dictionary represent are dictionaries
that may consist of two keys 'ipv4' and 'ipv6' (one, both or none)
which are themselvs dictionaries with the IP addresses as keys.
CLI Example:
.. code-block:: bash
salt '*' net.ipaddrs
Example output:
.. code-block:: python
{
'FastEthernet8': {
'ipv4': {
'10.66.43.169': {
'prefix_length': 22
}
}
},
'Loopback555': {
'ipv4': {
'192.168.1.1': {
'prefix_length': 24
}
},
'ipv6': {
'1::1': {
'prefix_length': 64
},
'2001:DB8:1::1': {
'prefix_length': 64
},
'FE80::3': {
'prefix_length': 'N/A'
}
}
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_interfaces_ip',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def interfaces(**kwargs): # pylint: disable=unused-argument
'''
Returns details of the interfaces on the device.
:return: Returns a dictionary of dictionaries. The keys for the first
dictionary will be the interfaces in the devices.
CLI Example:
.. code-block:: bash
salt '*' net.interfaces
Example output:
.. code-block:: python
{
'Management1': {
'is_up': False,
'is_enabled': False,
'description': '',
'last_flapped': -1,
'speed': 1000,
'mac_address': 'dead:beef:dead',
},
'Ethernet1':{
'is_up': True,
'is_enabled': True,
'description': 'foo',
'last_flapped': 1429978575.1554043,
'speed': 1000,
'mac_address': 'beef:dead:beef',
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_interfaces',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def lldp(interface='', **kwargs): # pylint: disable=unused-argument
'''
Returns a detailed view of the LLDP neighbors.
:param interface: interface name to filter on
:return: A dictionary with the LLDL neighbors. The keys are the
interfaces with LLDP activated on.
CLI Example:
.. code-block:: bash
salt '*' net.lldp
salt '*' net.lldp interface='TenGigE0/0/0/8'
Example output:
.. code-block:: python
{
'TenGigE0/0/0/8': [
{
'parent_interface': 'Bundle-Ether8',
'interface_description': 'TenGigE0/0/0/8',
'remote_chassis_id': '8c60.4f69.e96c',
'remote_system_name': 'switch',
'remote_port': 'Eth2/2/1',
'remote_port_description': 'Ethernet2/2/1',
'remote_system_description': 'Cisco Nexus Operating System (NX-OS) Software 7.1(0)N1(1a)
TAC support: http://www.cisco.com/tac
Copyright (c) 2002-2015, Cisco Systems, Inc. All rights reserved.',
'remote_system_capab': 'B, R',
'remote_system_enable_capab': 'B'
}
]
}
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_lldp_neighbors_detail',
**{
}
)
if not proxy_output.get('result'):
return proxy_output
lldp_neighbors = proxy_output.get('out')
if interface:
lldp_neighbors = {interface: lldp_neighbors.get(interface)}
proxy_output.update({
'out': lldp_neighbors
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def mac(address='', interface='', vlan=0, **kwargs): # pylint: disable=unused-argument
'''
Returns the MAC Address Table on the device.
:param address: MAC address to filter on
:param interface: Interface name to filter on
:param vlan: VLAN identifier
:return: A list of dictionaries representing the entries in the MAC Address Table
CLI Example:
.. code-block:: bash
salt '*' net.mac
salt '*' net.mac vlan=10
Example output:
.. code-block:: python
[
{
'mac' : '00:1c:58:29:4a:71',
'interface' : 'xe-3/0/2',
'static' : False,
'active' : True,
'moves' : 1,
'vlan' : 10,
'last_move' : 1454417742.58
},
{
'mac' : '8c:60:4f:58:e1:c1',
'interface' : 'xe-1/0/1',
'static' : False,
'active' : True,
'moves' : 2,
'vlan' : 42,
'last_move' : 1453191948.11
}
]
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_mac_address_table',
**{
}
)
if not proxy_output.get('result'):
# if negative, leave the output unchanged
return proxy_output
mac_address_table = proxy_output.get('out')
if vlan and isinstance(vlan, int):
mac_address_table = _filter_list(mac_address_table, 'vlan', vlan)
if address:
mac_address_table = _filter_list(mac_address_table, 'mac', address)
if interface:
mac_address_table = _filter_list(mac_address_table, 'interface', interface)
proxy_output.update({
'out': mac_address_table
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def config(source=None, **kwargs): # pylint: disable=unused-argument
'''
.. versionadded:: 2017.7.0
Return the whole configuration of the network device. By default, it will
return all possible configuration sources supported by the network device.
At most, there will be:
- running config
- startup config
- candidate config
To return only one of the configurations, you can use the ``source``
argument.
source
Which configuration type you want to display, default is all of them.
Options:
- running
- candidate
- startup
:return:
The object returned is a dictionary with the following keys:
- running (string): Representation of the native running configuration.
- candidate (string): Representation of the native candidate configuration.
If the device doesn't differentiate between running and startup
configuration this will an empty string.
- startup (string): Representation of the native startup configuration.
If the device doesn't differentiate between running and startup
configuration this will an empty string.
CLI Example:
.. code-block:: bash
salt '*' net.config
salt '*' net.config source=candidate
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_config',
**{
'retrieve': source
}
)
@salt.utils.napalm.proxy_napalm_wrap
def optics(**kwargs): # pylint: disable=unused-argument
'''
.. versionadded:: 2017.7.0
Fetches the power usage on the various transceivers installed
on the network device (in dBm), and returns a view that conforms with the
OpenConfig model openconfig-platform-transceiver.yang.
:return:
Returns a dictionary where the keys are as listed below:
* intf_name (unicode)
* physical_channels
* channels (list of dicts)
* index (int)
* state
* input_power
* instant (float)
* avg (float)
* min (float)
* max (float)
* output_power
* instant (float)
* avg (float)
* min (float)
* max (float)
* laser_bias_current
* instant (float)
* avg (float)
* min (float)
* max (float)
CLI Example:
.. code-block:: bash
salt '*' net.optics
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_optics',
**{
}
)
# <---- Call NAPALM getters --------------------------------------------------------------------------------------------
# ----- Configuration specific functions ------------------------------------------------------------------------------>
@salt.utils.napalm.proxy_napalm_wrap
def load_config(filename=None,
text=None,
test=False,
commit=True,
debug=False,
replace=False,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
commit_jid=None,
inherit_napalm_device=None,
saltenv='base',
**kwargs): # pylint: disable=unused-argument
'''
Applies configuration changes on the device. It can be loaded from a file or from inline string.
If you send both a filename and a string containing the configuration, the file has higher precedence.
By default this function will commit the changes. If there are no changes, it does not commit and
the flag ``already_configured`` will be set as ``True`` to point this out.
To avoid committing the configuration, set the argument ``test`` to ``True`` and will discard (dry run).
To keep the changes but not commit, set ``commit`` to ``False``.
To replace the config, set ``replace`` to ``True``.
filename
Path to the file containing the desired configuration.
This can be specified using the absolute path to the file,
or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
.. versionchanged:: 2018.3.0
text
String containing the desired configuration.
This argument is ignored when ``filename`` is specified.
test: False
Dry run? If set as ``True``, will apply the config, discard and return the changes. Default: ``False``
and will commit the changes on the device.
commit: True
Commit? Default: ``True``.
debug: False
Debug mode. Will insert a new key under the output dictionary, as ``loaded_config`` containing the raw
configuration loaded on the device.
.. versionadded:: 2016.11.2
replace: False
Load and replace the configuration. Default: ``False``.
.. versionadded:: 2016.11.2
commit_in: ``None``
Commit the changes in a specific number of minutes / hours. Example of
accepted formats: ``5`` (commit in 5 minutes), ``2m`` (commit in 2
minutes), ``1h`` (commit the changes in 1 hour)`, ``5h30m`` (commit
the changes in 5 hours and 30 minutes).
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
commit_at: ``None``
Commit the changes at a specific time. Example of accepted formats:
``1am`` (will commit the changes at the next 1AM), ``13:20`` (will
commit at 13:20), ``1:20am``, etc.
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
revert_in: ``None``
Commit and revert the changes in a specific number of minutes / hours.
Example of accepted formats: ``5`` (revert in 5 minutes), ``2m`` (revert
in 2 minutes), ``1h`` (revert the changes in 1 hour)`, ``5h30m`` (revert
the changes in 5 hours and 30 minutes).
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
revert_at: ``None``
Commit and revert the changes at a specific time. Example of accepted
formats: ``1am`` (will commit and revert the changes at the next 1AM),
``13:20`` (will commit and revert at 13:20), ``1:20am``, etc.
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
saltenv: ``base``
Specifies the Salt environment name.
.. versionadded:: 2018.3.0
:return: a dictionary having the following keys:
* result (bool): if the config was applied successfully. It is ``False`` only in case of failure. In case \
there are no changes to be applied and successfully performs all operations it is still ``True`` and so will be \
the ``already_configured`` flag (example below)
* comment (str): a message for the user
* already_configured (bool): flag to check if there were no changes applied
* loaded_config (str): the configuration loaded on the device. Requires ``debug`` to be set as ``True``
* diff (str): returns the config changes applied
CLI Example:
.. code-block:: bash
salt '*' net.load_config text='ntp peer 192.168.0.1'
salt '*' net.load_config filename='/absolute/path/to/your/file'
salt '*' net.load_config filename='/absolute/path/to/your/file' test=True
salt '*' net.load_config filename='/absolute/path/to/your/file' commit=False
Example output:
.. code-block:: python
{
'comment': 'Configuration discarded.',
'already_configured': False,
'result': True,
'diff': '[edit interfaces xe-0/0/5]+ description "Adding a description";'
}
'''
fun = 'load_merge_candidate'
if replace:
fun = 'load_replace_candidate'
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
if filename:
text = __salt__['cp.get_file_str'](filename, saltenv=saltenv)
if text is False:
# When using salt:// or https://, if the resource is not available,
# it will either raise an exception, or return False.
ret = {
'result': False,
'out': None
}
ret['comment'] = 'Unable to read from {}. Please specify a valid file or text.'.format(filename)
log.error(ret['comment'])
return ret
if commit_jid:
# When the commit_jid argument is passed, it probably is a scheduled
# commit to be executed, and filename is a temporary file which
# can be removed after reading it.
salt.utils.files.safe_rm(filename)
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
fun,
**{
'config': text
}
)
return _config_logic(napalm_device, # pylint: disable=undefined-variable
_loaded,
test=test,
debug=debug,
replace=replace,
commit_config=commit,
loaded_config=text,
commit_at=commit_at,
commit_in=commit_in,
revert_in=revert_in,
revert_at=revert_at,
commit_jid=commit_jid,
**kwargs)
@salt.utils.napalm.proxy_napalm_wrap
def load_template(template_name=None,
template_source=None,
context=None,
defaults=None,
template_engine='jinja',
saltenv='base',
template_hash=None,
template_hash_name=None,
skip_verify=False,
test=False,
commit=True,
debug=False,
replace=False,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
inherit_napalm_device=None, # pylint: disable=unused-argument
**template_vars):
'''
Renders a configuration template (default: Jinja) and loads the result on the device.
By default this function will commit the changes. If there are no changes,
it does not commit, discards he config and the flag ``already_configured``
will be set as ``True`` to point this out.
To avoid committing the configuration, set the argument ``test`` to ``True``
and will discard (dry run).
To preserve the changes, set ``commit`` to ``False``.
However, this is recommended to be used only in exceptional cases
when there are applied few consecutive states
and/or configuration changes.
Otherwise the user might forget that the config DB is locked
and the candidate config buffer is not cleared/merged in the running config.
To replace the config, set ``replace`` to ``True``.
template_name
Identifies path to the template source.
The template can be either stored on the local machine, either remotely.
The recommended location is under the ``file_roots``
as specified in the master config file.
For example, let's suppose the ``file_roots`` is configured as:
.. code-block:: yaml
file_roots:
base:
- /etc/salt/states
Placing the template under ``/etc/salt/states/templates/example.jinja``,
it can be used as ``salt://templates/example.jinja``.
Alternatively, for local files, the user can specify the absolute path.
If remotely, the source can be retrieved via ``http``, ``https`` or ``ftp``.
Examples:
- ``salt://my_template.jinja``
- ``/absolute/path/to/my_template.jinja``
- ``http://example.com/template.cheetah``
- ``https:/example.com/template.mako``
- ``ftp://example.com/template.py``
.. versionchanged:: 2019.2.0
This argument can now support a list of templates to be rendered.
The resulting configuration text is loaded at once, as a single
configuration chunk.
template_source: None
Inline config template to be rendered and loaded on the device.
template_hash: None
Hash of the template file. Format: ``{hash_type: 'md5', 'hsum': <md5sum>}``
.. versionadded:: 2016.11.2
context: None
Overrides default context variables passed to the template.
.. versionadded:: 2019.2.0
template_hash_name: None
When ``template_hash`` refers to a remote file,
this specifies the filename to look for in that file.
.. versionadded:: 2016.11.2
saltenv: ``base``
Specifies the template environment.
This will influence the relative imports inside the templates.
.. versionadded:: 2016.11.2
template_engine: jinja
The following templates engines are supported:
- :mod:`cheetah<salt.renderers.cheetah>`
- :mod:`genshi<salt.renderers.genshi>`
- :mod:`jinja<salt.renderers.jinja>`
- :mod:`mako<salt.renderers.mako>`
- :mod:`py<salt.renderers.py>`
- :mod:`wempy<salt.renderers.wempy>`
.. versionadded:: 2016.11.2
skip_verify: True
If ``True``, hash verification of remote file sources
(``http://``, ``https://``, ``ftp://``) will be skipped,
and the ``source_hash`` argument will be ignored.
.. versionadded:: 2016.11.2
test: False
Dry run? If set to ``True``, will apply the config,
discard and return the changes.
Default: ``False`` and will commit the changes on the device.
commit: True
Commit? (default: ``True``)
debug: False
Debug mode. Will insert a new key under the output dictionary,
as ``loaded_config`` containing the raw result after the template was rendered.
.. versionadded:: 2016.11.2
replace: False
Load and replace the configuration.
.. versionadded:: 2016.11.2
commit_in: ``None``
Commit the changes in a specific number of minutes / hours. Example of
accepted formats: ``5`` (commit in 5 minutes), ``2m`` (commit in 2
minutes), ``1h`` (commit the changes in 1 hour)`, ``5h30m`` (commit
the changes in 5 hours and 30 minutes).
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
commit_at: ``None``
Commit the changes at a specific time. Example of accepted formats:
``1am`` (will commit the changes at the next 1AM), ``13:20`` (will
commit at 13:20), ``1:20am``, etc.
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
revert_in: ``None``
Commit and revert the changes in a specific number of minutes / hours.
Example of accepted formats: ``5`` (revert in 5 minutes), ``2m`` (revert
in 2 minutes), ``1h`` (revert the changes in 1 hour)`, ``5h30m`` (revert
the changes in 5 hours and 30 minutes).
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
revert_at: ``None``
Commit and revert the changes at a specific time. Example of accepted
formats: ``1am`` (will commit and revert the changes at the next 1AM),
``13:20`` (will commit and revert at 13:20), ``1:20am``, etc.
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
defaults: None
Default variables/context passed to the template.
.. versionadded:: 2016.11.2
template_vars
Dictionary with the arguments/context to be used when the template is rendered.
.. note::
Do not explicitly specify this argument. This represents any other
variable that will be sent to the template rendering system.
Please see the examples below!
.. note::
It is more recommended to use the ``context`` argument to avoid
conflicts between CLI arguments and template variables.
:return: a dictionary having the following keys:
- result (bool): if the config was applied successfully. It is ``False``
only in case of failure. In case there are no changes to be applied and
successfully performs all operations it is still ``True`` and so will be
the ``already_configured`` flag (example below)
- comment (str): a message for the user
- already_configured (bool): flag to check if there were no changes applied
- loaded_config (str): the configuration loaded on the device, after
rendering the template. Requires ``debug`` to be set as ``True``
- diff (str): returns the config changes applied
The template can use variables from the ``grains``, ``pillar`` or ``opts``, for example:
.. code-block:: jinja
{% set router_model = grains.get('model') -%}
{% set router_vendor = grains.get('vendor') -%}
{% set os_version = grains.get('version') -%}
{% set hostname = pillar.get('proxy', {}).get('host') -%}
{% if router_vendor|lower == 'juniper' %}
system {
host-name {{hostname}};
}
{% elif router_vendor|lower == 'cisco' %}
hostname {{hostname}}
{% endif %}
CLI Examples:
.. code-block:: bash
salt '*' net.load_template set_ntp_peers peers=[192.168.0.1] # uses NAPALM default templates
# inline template:
salt -G 'os:junos' net.load_template template_source='system { host-name {{host_name}}; }' \
host_name='MX480.lab'
# inline template using grains info:
salt -G 'os:junos' net.load_template \
template_source='system { host-name {{grains.model}}.lab; }'
# if the device is a MX480, the command above will set the hostname as: MX480.lab
# inline template using pillar data:
salt -G 'os:junos' net.load_template template_source='system { host-name {{pillar.proxy.host}}; }'
salt '*' net.load_template https://bit.ly/2OhSgqP hostname=example # will commit
salt '*' net.load_template https://bit.ly/2OhSgqP hostname=example test=True # dry run
salt '*' net.load_template salt://templates/example.jinja debug=True # Using the salt:// URI
# render a mako template:
salt '*' net.load_template salt://templates/example.mako template_engine=mako debug=True
# render remote template
salt -G 'os:junos' net.load_template http://bit.ly/2fReJg7 test=True debug=True peers=['192.168.0.1']
salt -G 'os:ios' net.load_template http://bit.ly/2gKOj20 test=True debug=True peers=['192.168.0.1']
# render multiple templates at once
salt '*' net.load_template "['https://bit.ly/2OhSgqP', 'salt://templates/example.jinja']" context="{'hostname': 'example'}"
Example output:
.. code-block:: python
{
'comment': '',
'already_configured': False,
'result': True,
'diff': '[edit system]+ host-name edge01.bjm01',
'loaded_config': 'system { host-name edge01.bjm01; }''
}
'''
_rendered = ''
_loaded = {
'result': True,
'comment': '',
'out': None
}
loaded_config = None
# prechecks
deprecated_args = ('template_user', 'template_attrs', 'template_group', 'template_mode')
for deprecated_arg in deprecated_args:
if template_vars.get(deprecated_arg):
del template_vars[deprecated_arg]
salt.utils.versions.warn_until(
'Sodium',
('The \'{arg}\' argument to \'net.load_template\' is deprecated '
'and has been ignored').format(arg=deprecated_arg)
)
if template_engine not in salt.utils.templates.TEMPLATE_REGISTRY:
_loaded.update({
'result': False,
'comment': 'Invalid templating engine! Choose between: {tpl_eng_opts}'.format(
tpl_eng_opts=', '.join(list(salt.utils.templates.TEMPLATE_REGISTRY.keys()))
)
})
return _loaded # exit
# to check if will be rendered by salt or NAPALM
salt_render_prefixes = ('salt://', 'http://', 'https://', 'ftp://')
salt_render = False
file_exists = False
if not isinstance(template_name, (tuple, list)):
for salt_render_prefix in salt_render_prefixes:
if not salt_render:
salt_render = salt_render or template_name.startswith(salt_render_prefix)
file_exists = __salt__['file.file_exists'](template_name)
if template_source or file_exists or salt_render or isinstance(template_name, (tuple, list)):
# either inline template
# either template in a custom path
# either abs path send
# either starts with salt:// and
# then use Salt render system
if context is None:
context = {}
context.update(template_vars)
# if needed to render the template send as inline arg
if template_source:
# render the content
_rendered = __salt__['file.apply_template_on_contents'](
contents=template_source,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv
)
if not isinstance(_rendered, six.string_types):
if 'result' in _rendered:
_loaded['result'] = _rendered['result']
else:
_loaded['result'] = False
if 'comment' in _rendered:
_loaded['comment'] = _rendered['comment']
else:
_loaded['comment'] = 'Error while rendering the template.'
return _loaded
else:
# render the file - either local, either remote
if not isinstance(template_name, (list, tuple)):
template_name = [template_name]
if template_hash_name and not isinstance(template_hash_name, (list, tuple)):
template_hash_name = [template_hash_name]
elif not template_hash_name:
template_hash_name = [None] * len(template_name)
if template_hash and isinstance(template_hash, six.string_types) and not\
(template_hash.startswith('salt://') or template_hash.startswith('file://')):
# If the template hash is passed as string, and it's not a file
# (starts with the salt:// or file:// URI), then make it a list
# of 1 element (for the iteration below)
template_hash = [template_hash]
elif template_hash and isinstance(template_hash, six.string_types) and\
(template_hash.startswith('salt://') or template_hash.startswith('file://')):
# If the template hash is a file URI, then provide the same value
# for each of the templates in the list, as probably they all
# share the same hash file, otherwise the user should provide
# this as a list
template_hash = [template_hash] * len(template_name)
elif not template_hash:
template_hash = [None] * len(template_name)
for tpl_index, tpl_name in enumerate(template_name):
tpl_hash = template_hash[tpl_index]
tpl_hash_name = template_hash_name[tpl_index]
_rand_filename = __salt__['random.hash'](tpl_name, 'md5')
_temp_file = __salt__['file.join']('/tmp', _rand_filename)
_managed = __salt__['file.get_managed'](name=_temp_file,
source=tpl_name,
source_hash=tpl_hash,
source_hash_name=tpl_hash_name,
user=None,
group=None,
mode=None,
attrs=None,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv,
skip_verify=skip_verify)
if not isinstance(_managed, (list, tuple)) and isinstance(_managed, six.string_types):
_loaded['comment'] += _managed
_loaded['result'] = False
elif isinstance(_managed, (list, tuple)) and not _managed:
_loaded['result'] = False
_loaded['comment'] += 'Error while rendering the template.'
elif isinstance(_managed, (list, tuple)) and not _managed[0]:
_loaded['result'] = False
_loaded['comment'] += _managed[-1] # contains the error message
if _loaded['result']: # all good
_temp_tpl_file = _managed[0]
_temp_tpl_file_exists = __salt__['file.file_exists'](_temp_tpl_file)
if not _temp_tpl_file_exists:
_loaded['result'] = False
_loaded['comment'] += 'Error while rendering the template.'
return _loaded
_rendered += __salt__['file.read'](_temp_tpl_file)
__salt__['file.remove'](_temp_tpl_file)
else:
return _loaded # exit
loaded_config = _rendered
if _loaded['result']: # all good
fun = 'load_merge_candidate'
if replace: # replace requested
fun = 'load_replace_candidate'
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
fun,
**{
'config': _rendered
}
)
else:
salt.utils.versions.warn_until(
'Sodium',
'Native NAPALM templates support will be removed in the Sodium '
'release. Please consider using the Salt rendering pipeline instead.'
'If you are using the \'netntp\', \'netsnmp\', or \'netusers\' Salt '
'State modules, you can ignore this message'
)
# otherwise, use NAPALM render system, injecting pillar/grains/opts vars
load_templates_params = defaults if defaults else {}
load_templates_params.update(template_vars)
load_templates_params.update(
{
'template_name': template_name,
'template_source': template_source, # inline template
'pillar': __pillar__, # inject pillar content
'grains': __grains__, # inject grains content
'opts': __opts__ # inject opts content
}
)
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
# so we'll set the CLOSE global explicitly as False
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'load_template',
**load_templates_params
)
return _config_logic(napalm_device, # pylint: disable=undefined-variable
_loaded,
test=test,
debug=debug,
replace=replace,
commit_config=commit,
loaded_config=loaded_config,
commit_at=commit_at,
commit_in=commit_in,
revert_in=revert_in,
revert_at=revert_at,
**template_vars)
@salt.utils.napalm.proxy_napalm_wrap
def commit(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Commits the configuration changes made on the network device.
CLI Example:
.. code-block:: bash
salt '*' net.commit
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'commit_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def discard_config(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
"""
Discards the changes applied.
CLI Example:
.. code-block:: bash
salt '*' net.discard_config
"""
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'discard_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def compare_config(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Returns the difference between the running config and the candidate config.
CLI Example:
.. code-block:: bash
salt '*' net.compare_config
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'compare_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def rollback(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Rollbacks the configuration.
CLI Example:
.. code-block:: bash
salt '*' net.rollback
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'rollback',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def config_changed(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Will prompt if the configuration has been changed.
:return: A tuple with a boolean that specifies if the config was changed on the device.\
And a string that provides more details of the reason why the configuration was not changed.
CLI Example:
.. code-block:: bash
salt '*' net.config_changed
'''
is_config_changed = False
reason = ''
try_compare = compare_config(inherit_napalm_device=napalm_device) # pylint: disable=undefined-variable
if try_compare.get('result'):
if try_compare.get('out'):
is_config_changed = True
else:
reason = 'Configuration was not changed on the device.'
else:
reason = try_compare.get('comment')
return is_config_changed, reason
@salt.utils.napalm.proxy_napalm_wrap
def config_control(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Will check if the configuration was changed.
If differences found, will try to commit.
In case commit unsuccessful, will try to rollback.
:return: A tuple with a boolean that specifies if the config was changed/committed/rollbacked on the device.\
And a string that provides more details of the reason why the configuration was not committed properly.
CLI Example:
.. code-block:: bash
salt '*' net.config_control
'''
result = True
comment = ''
changed, not_changed_rsn = config_changed(inherit_napalm_device=napalm_device) # pylint: disable=undefined-variable
if not changed:
return (changed, not_changed_rsn)
# config changed, thus let's try to commit
try_commit = commit()
if not try_commit.get('result'):
result = False
comment = 'Unable to commit the changes: {reason}.\n\
Will try to rollback now!'.format(
reason=try_commit.get('comment')
)
try_rollback = rollback()
if not try_rollback.get('result'):
comment += '\nCannot rollback! {reason}'.format(
reason=try_rollback.get('comment')
)
return result, comment
def cancel_commit(jid):
'''
.. versionadded:: 2019.2.0
Cancel a commit scheduled to be executed via the ``commit_in`` and
``commit_at`` arguments from the
:py:func:`net.load_template <salt.modules.napalm_network.load_template>` or
:py:func:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit ID is displayed when the commit is scheduled
via the functions named above.
CLI Example:
.. code-block:: bash
salt '*' net.cancel_commit 20180726083540640360
'''
job_name = '__napalm_commit_{}'.format(jid)
removed = __salt__['schedule.delete'](job_name)
if removed['result']:
saved = __salt__['schedule.save']()
removed['comment'] = 'Commit #{jid} cancelled.'.format(jid=jid)
else:
removed['comment'] = 'Unable to find commit #{jid}.'.format(jid=jid)
return removed
def confirm_commit(jid):
'''
.. versionadded:: 2019.2.0
Confirm a commit scheduled to be reverted via the ``revert_in`` and
``revert_at`` arguments from the
:mod:`net.load_template <salt.modules.napalm_network.load_template>` or
:mod:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit ID is displayed when the commit confirmed
is scheduled via the functions named above.
CLI Example:
.. code-block:: bash
salt '*' net.confirm_commit 20180726083540640360
'''
if __grains__['os'] == 'junos':
# Confirm the commit, by committing (i.e., invoking the RPC call)
confirmed = __salt__['napalm.junos_commit']()
confirmed['result'] = confirmed.pop('out')
confirmed['comment'] = confirmed.pop('message')
else:
confirmed = cancel_commit(jid)
if confirmed['result']:
confirmed['comment'] = 'Commit #{jid} confirmed.'.format(jid=jid)
return confirmed
def save_config(source=None,
path=None):
'''
.. versionadded:: 2019.2.0
Save the configuration to a file on the local file system.
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``,
``startup``. Default: ``running``.
path
Absolute path to file where to save the configuration.
To push the files to the Master, use
:mod:`cp.push <salt.modules.cp.push>` Execution function.
CLI Example:
.. code-block:: bash
salt '*' net.save_config source=running
'''
if not source:
source = 'running'
if not path:
path = salt.utils.files.mkstemp()
running_config = __salt__['net.config'](source=source)
if not running_config or not running_config['result']:
log.error('Unable to retrieve the config')
return running_config
with salt.utils.files.fopen(path, 'w') as fh_:
fh_.write(running_config['out'][source])
return {
'result': True,
'out': path,
'comment': '{source} config saved to {path}'.format(source=source, path=path)
}
def replace_pattern(pattern,
repl,
count=0,
flags=8,
bufsize=1,
append_if_not_found=False,
prepend_if_not_found=False,
not_found_content=None,
search_only=False,
show_changes=True,
backslash_literal=False,
source=None,
path=None,
test=False,
replace=True,
debug=False,
commit=True):
'''
.. versionadded:: 2019.2.0
Replace occurrences of a pattern in the configuration source. If
``show_changes`` is ``True``, then a diff of what changed will be returned,
otherwise a ``True`` will be returned when changes are made, and ``False``
when no changes are made.
This is a pure Python implementation that wraps Python's :py:func:`~re.sub`.
pattern
A regular expression, to be matched using Python's
:py:func:`~re.search`.
repl
The replacement text.
count: ``0``
Maximum number of pattern occurrences to be replaced. If count is a
positive integer ``n``, only ``n`` occurrences will be replaced,
otherwise all occurrences will be replaced.
flags (list or int): ``8``
A list of flags defined in the ``re`` module documentation from the
Python standard library. Each list item should be a string that will
correlate to the human-friendly flag name. E.g., ``['IGNORECASE',
'MULTILINE']``. Optionally, ``flags`` may be an int, with a value
corresponding to the XOR (``|``) of all the desired flags. Defaults to
8 (which supports 'MULTILINE').
bufsize (int or str): ``1``
How much of the configuration to buffer into memory at once. The
default value ``1`` processes one line at a time. The special value
``file`` may be specified which will read the entire file into memory
before processing.
append_if_not_found: ``False``
If set to ``True``, and pattern is not found, then the content will be
appended to the file.
prepend_if_not_found: ``False``
If set to ``True`` and pattern is not found, then the content will be
prepended to the file.
not_found_content
Content to use for append/prepend if not found. If None (default), uses
``repl``. Useful when ``repl`` uses references to group in pattern.
search_only: ``False``
If set to true, this no changes will be performed on the file, and this
function will simply return ``True`` if the pattern was matched, and
``False`` if not.
show_changes: ``True``
If ``True``, return a diff of changes made. Otherwise, return ``True``
if changes were made, and ``False`` if not.
backslash_literal: ``False``
Interpret backslashes as literal backslashes for the repl and not
escape characters. This will help when using append/prepend so that
the backslashes are not interpreted for the repl on the second run of
the state.
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path
Save the temporary configuration to a specific path, then read from
there.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' net.replace_pattern "bind-address\\s*=" "bind-address:"
CLI Example:
.. code-block:: bash
salt '*' net.replace_pattern PREFIX-LIST_NAME new-prefix-list-name
salt '*' net.replace_pattern bgp-group-name new-bgp-group-name count=1
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
replace_pattern = __salt__['file.replace'](path,
pattern,
repl,
count=count,
flags=flags,
bufsize=bufsize,
append_if_not_found=append_if_not_found,
prepend_if_not_found=prepend_if_not_found,
not_found_content=not_found_content,
search_only=search_only,
show_changes=show_changes,
backslash_literal=backslash_literal)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
def blockreplace(marker_start,
marker_end,
content='',
append_if_not_found=False,
prepend_if_not_found=False,
show_changes=True,
append_newline=False,
source='running',
path=None,
test=False,
commit=True,
debug=False,
replace=True):
'''
.. versionadded:: 2019.2.0
Replace content of the configuration source, delimited by the line markers.
A block of content delimited by comments can help you manage several lines
without worrying about old entries removal.
marker_start
The line content identifying a line as the start of the content block.
Note that the whole line containing this marker will be considered,
so whitespace or extra content before or after the marker is included
in final output.
marker_end
The line content identifying a line as the end of the content block.
Note that the whole line containing this marker will be considered,
so whitespace or extra content before or after the marker is included
in final output.
content
The content to be used between the two lines identified by
``marker_start`` and ``marker_stop``.
append_if_not_found: ``False``
If markers are not found and set to True then, the markers and content
will be appended to the file.
prepend_if_not_found: ``False``
If markers are not found and set to True then, the markers and content
will be prepended to the file.
append_newline: ``False``
Controls whether or not a newline is appended to the content block.
If the value of this argument is ``True`` then a newline will be added
to the content block. If it is ``False``, then a newline will not be
added to the content block. If it is ``None`` then a newline will only
be added to the content block if it does not already end in a newline.
show_changes: ``True``
Controls how changes are presented. If ``True``, this function will
return the of the changes made.
If ``False``, then it will return a boolean (``True`` if any changes
were made, otherwise False).
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path: ``None``
Save the temporary configuration to a specific path, then read from
there. This argument is optional, can be used when you prefers a
particular location of the temporary file.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
CLI Example:
.. code-block:: bash
salt '*' net.blockreplace 'ntp' 'interface' ''
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
replace_pattern = __salt__['file.blockreplace'](path,
marker_start=marker_start,
marker_end=marker_end,
content=content,
append_if_not_found=append_if_not_found,
prepend_if_not_found=prepend_if_not_found,
show_changes=show_changes,
append_newline=append_newline)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
def patch(patchfile,
options='',
saltenv='base',
source_hash=None,
show_changes=True,
source='running',
path=None,
test=False,
commit=True,
debug=False,
replace=True):
'''
.. versionadded:: 2019.2.0
Apply a patch to the configuration source, and load the result into the
running config of the device.
patchfile
A patch file to apply to the configuration source.
options
Options to pass to patch.
source_hash
If the patch file (specified via the ``patchfile`` argument) is an
HTTP(S) or FTP URL and the file exists in the minion's file cache, this
option can be passed to keep the minion from re-downloading the file if
the cached copy matches the specified hash.
show_changes: ``True``
Controls how changes are presented. If ``True``, this function will
return the of the changes made.
If ``False``, then it will return a boolean (``True`` if any changes
were made, otherwise False).
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path: ``None``
Save the temporary configuration to a specific path, then read from
there. This argument is optional, can the user prefers a particular
location of the temporary file.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
CLI Example:
.. code-block:: bash
salt '*' net.patch https://example.com/running_config.patch
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
patchfile_cache = __salt__['cp.cache_file'](patchfile)
if patchfile_cache is False:
return {
'out': None,
'result': False,
'comment': 'The file "{}" does not exist.'.format(patchfile)
}
replace_pattern = __salt__['file.patch'](path,
patchfile_cache,
options=options)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
# <---- Configuration specific functions -------------------------------------------------------------------------------
|
saltstack/salt
|
salt/modules/napalm_network.py
|
lldp
|
python
|
def lldp(interface='', **kwargs): # pylint: disable=unused-argument
'''
Returns a detailed view of the LLDP neighbors.
:param interface: interface name to filter on
:return: A dictionary with the LLDL neighbors. The keys are the
interfaces with LLDP activated on.
CLI Example:
.. code-block:: bash
salt '*' net.lldp
salt '*' net.lldp interface='TenGigE0/0/0/8'
Example output:
.. code-block:: python
{
'TenGigE0/0/0/8': [
{
'parent_interface': 'Bundle-Ether8',
'interface_description': 'TenGigE0/0/0/8',
'remote_chassis_id': '8c60.4f69.e96c',
'remote_system_name': 'switch',
'remote_port': 'Eth2/2/1',
'remote_port_description': 'Ethernet2/2/1',
'remote_system_description': 'Cisco Nexus Operating System (NX-OS) Software 7.1(0)N1(1a)
TAC support: http://www.cisco.com/tac
Copyright (c) 2002-2015, Cisco Systems, Inc. All rights reserved.',
'remote_system_capab': 'B, R',
'remote_system_enable_capab': 'B'
}
]
}
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_lldp_neighbors_detail',
**{
}
)
if not proxy_output.get('result'):
return proxy_output
lldp_neighbors = proxy_output.get('out')
if interface:
lldp_neighbors = {interface: lldp_neighbors.get(interface)}
proxy_output.update({
'out': lldp_neighbors
})
return proxy_output
|
Returns a detailed view of the LLDP neighbors.
:param interface: interface name to filter on
:return: A dictionary with the LLDL neighbors. The keys are the
interfaces with LLDP activated on.
CLI Example:
.. code-block:: bash
salt '*' net.lldp
salt '*' net.lldp interface='TenGigE0/0/0/8'
Example output:
.. code-block:: python
{
'TenGigE0/0/0/8': [
{
'parent_interface': 'Bundle-Ether8',
'interface_description': 'TenGigE0/0/0/8',
'remote_chassis_id': '8c60.4f69.e96c',
'remote_system_name': 'switch',
'remote_port': 'Eth2/2/1',
'remote_port_description': 'Ethernet2/2/1',
'remote_system_description': 'Cisco Nexus Operating System (NX-OS) Software 7.1(0)N1(1a)
TAC support: http://www.cisco.com/tac
Copyright (c) 2002-2015, Cisco Systems, Inc. All rights reserved.',
'remote_system_capab': 'B, R',
'remote_system_enable_capab': 'B'
}
]
}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_network.py#L1058-L1117
|
[
"def call(napalm_device, method, *args, **kwargs):\n '''\n Calls arbitrary methods from the network driver instance.\n Please check the readthedocs_ page for the updated list of getters.\n\n .. _readthedocs: http://napalm.readthedocs.org/en/latest/support/index.html#getters-support-matrix\n\n method\n Specifies the name of the method to be called.\n\n *args\n Arguments.\n\n **kwargs\n More arguments.\n\n :return: A dictionary with three keys:\n\n * result (True/False): if the operation succeeded\n * out (object): returns the object as-is from the call\n * comment (string): provides more details in case the call failed\n * traceback (string): complete traceback in case of exception. \\\n Please submit an issue including this traceback \\\n on the `correct driver repo`_ and make sure to read the FAQ_\n\n .. _`correct driver repo`: https://github.com/napalm-automation/napalm/issues/new\n .. FAQ_: https://github.com/napalm-automation/napalm#faq\n\n Example:\n\n .. code-block:: python\n\n salt.utils.napalm.call(\n napalm_object,\n 'cli',\n [\n 'show version',\n 'show chassis fan'\n ]\n )\n '''\n result = False\n out = None\n opts = napalm_device.get('__opts__', {})\n retry = kwargs.pop('__retry', True) # retry executing the task?\n force_reconnect = kwargs.get('force_reconnect', False)\n if force_reconnect:\n log.debug('Forced reconnection initiated')\n log.debug('The current opts (under the proxy key):')\n log.debug(opts['proxy'])\n opts['proxy'].update(**kwargs)\n log.debug('Updated to:')\n log.debug(opts['proxy'])\n napalm_device = get_device(opts)\n try:\n if not napalm_device.get('UP', False):\n raise Exception('not connected')\n # if connected will try to execute desired command\n kwargs_copy = {}\n kwargs_copy.update(kwargs)\n for karg, warg in six.iteritems(kwargs_copy):\n # lets clear None arguments\n # to not be sent to NAPALM methods\n if warg is None:\n kwargs.pop(karg)\n out = getattr(napalm_device.get('DRIVER'), method)(*args, **kwargs)\n # calls the method with the specified parameters\n result = True\n except Exception as error:\n # either not connected\n # either unable to execute the command\n hostname = napalm_device.get('HOSTNAME', '[unspecified hostname]')\n err_tb = traceback.format_exc() # let's get the full traceback and display for debugging reasons.\n if isinstance(error, NotImplementedError):\n comment = '{method} is not implemented for the NAPALM {driver} driver!'.format(\n method=method,\n driver=napalm_device.get('DRIVER_NAME')\n )\n elif retry and HAS_CONN_CLOSED_EXC_CLASS and isinstance(error, ConnectionClosedException):\n # Received disconection whilst executing the operation.\n # Instructed to retry (default behaviour)\n # thus trying to re-establish the connection\n # and re-execute the command\n # if any of the operations (close, open, call) will rise again ConnectionClosedException\n # it will fail loudly.\n kwargs['__retry'] = False # do not attempt re-executing\n comment = 'Disconnected from {device}. Trying to reconnect.'.format(device=hostname)\n log.error(err_tb)\n log.error(comment)\n log.debug('Clearing the connection with %s', hostname)\n call(napalm_device, 'close', __retry=False) # safely close the connection\n # Make sure we don't leave any TCP connection open behind\n # if we fail to close properly, we might not be able to access the\n log.debug('Re-opening the connection with %s', hostname)\n call(napalm_device, 'open', __retry=False)\n log.debug('Connection re-opened with %s', hostname)\n log.debug('Re-executing %s', method)\n return call(napalm_device, method, *args, **kwargs)\n # If still not able to reconnect and execute the task,\n # the proxy keepalive feature (if enabled) will attempt\n # to reconnect.\n # If the device is using a SSH-based connection, the failure\n # will also notify the paramiko transport and the `is_alive` flag\n # is going to be set correctly.\n # More background: the network device may decide to disconnect,\n # although the SSH session itself is alive and usable, the reason\n # being the lack of activity on the CLI.\n # Paramiko's keepalive doesn't help in this case, as the ServerAliveInterval\n # are targeting the transport layer, whilst the device takes the decision\n # when there isn't any activity on the CLI, thus at the application layer.\n # Moreover, the disconnect is silent and paramiko's is_alive flag will\n # continue to return True, although the connection is already unusable.\n # For more info, see https://github.com/paramiko/paramiko/issues/813.\n # But after a command fails, the `is_alive` flag becomes aware of these\n # changes and will return False from there on. And this is how the\n # Salt proxy keepalive helps: immediately after the first failure, it\n # will know the state of the connection and will try reconnecting.\n else:\n comment = 'Cannot execute \"{method}\" on {device}{port} as {user}. Reason: {error}!'.format(\n device=napalm_device.get('HOSTNAME', '[unspecified hostname]'),\n port=(':{port}'.format(port=napalm_device.get('OPTIONAL_ARGS', {}).get('port'))\n if napalm_device.get('OPTIONAL_ARGS', {}).get('port') else ''),\n user=napalm_device.get('USERNAME', ''),\n method=method,\n error=error\n )\n log.error(comment)\n log.error(err_tb)\n return {\n 'out': {},\n 'result': False,\n 'comment': comment,\n 'traceback': err_tb\n }\n finally:\n if opts and not_always_alive(opts) and napalm_device.get('CLOSE', True):\n # either running in a not-always-alive proxy\n # either running in a regular minion\n # close the connection when the call is over\n # unless the CLOSE is explicitly set as False\n napalm_device['DRIVER'].close()\n return {\n 'out': out,\n 'result': result,\n 'comment': ''\n }\n"
] |
# -*- coding: utf-8 -*-
'''
NAPALM Network
==============
Basic methods for interaction with the network device through the virtual proxy 'napalm'.
:codeauthor: Mircea Ulinic <mircea@cloudflare.com> & Jerome Fleury <jf@cloudflare.com>
:maturity: new
:depends: napalm
:platform: unix
Dependencies
------------
- :mod:`napalm proxy minion <salt.proxy.napalm>`
.. versionadded:: 2016.11.0
.. versionchanged:: 2017.7.0
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import time
import logging
import datetime
log = logging.getLogger(__name__)
# Import Salt libs
from salt.ext import six
import salt.utils.files
import salt.utils.napalm
import salt.utils.versions
import salt.utils.templates
# Import 3rd-party libs
try:
import jxmlease # pylint: disable=unused-import
HAS_JXMLEASE = True
except ImportError:
HAS_JXMLEASE = False
# ----------------------------------------------------------------------------------------------------------------------
# module properties
# ----------------------------------------------------------------------------------------------------------------------
__virtualname__ = 'net'
__proxyenabled__ = ['*']
__virtual_aliases__ = ('napalm_net',)
# uses NAPALM-based proxy to interact with network devices
# ----------------------------------------------------------------------------------------------------------------------
# property functions
# ----------------------------------------------------------------------------------------------------------------------
def __virtual__():
'''
NAPALM library must be installed for this module to work and run in a (proxy) minion.
'''
return salt.utils.napalm.virtual(__opts__, __virtualname__, __file__)
# ----------------------------------------------------------------------------------------------------------------------
# helper functions -- will not be exported
# ----------------------------------------------------------------------------------------------------------------------
def _filter_list(input_list, search_key, search_value):
'''
Filters a list of dictionary by a set of key-value pair.
:param input_list: is a list of dictionaries
:param search_key: is the key we are looking for
:param search_value: is the value we are looking for the key specified in search_key
:return: filered list of dictionaries
'''
output_list = list()
for dictionary in input_list:
if dictionary.get(search_key) == search_value:
output_list.append(dictionary)
return output_list
def _filter_dict(input_dict, search_key, search_value):
'''
Filters a dictionary of dictionaries by a key-value pair.
:param input_dict: is a dictionary whose values are lists of dictionaries
:param search_key: is the key in the leaf dictionaries
:param search_values: is the value in the leaf dictionaries
:return: filtered dictionary
'''
output_dict = dict()
for key, key_list in six.iteritems(input_dict):
key_list_filtered = _filter_list(key_list, search_key, search_value)
if key_list_filtered:
output_dict[key] = key_list_filtered
return output_dict
def _safe_commit_config(loaded_result, napalm_device):
_commit = commit(inherit_napalm_device=napalm_device) # calls the function commit, defined below
if not _commit.get('result', False):
# if unable to commit
loaded_result['comment'] += _commit['comment'] if _commit.get('comment') else 'Unable to commit.'
loaded_result['result'] = False
# unable to commit, something went wrong
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
return _commit
def _safe_dicard_config(loaded_result, napalm_device):
'''
'''
log.debug('Discarding the config')
log.debug(loaded_result)
_discarded = discard_config(inherit_napalm_device=napalm_device)
if not _discarded.get('result', False):
loaded_result['comment'] += _discarded['comment'] if _discarded.get('comment') \
else 'Unable to discard config.'
loaded_result['result'] = False
# make sure it notifies
# that something went wrong
_explicit_close(napalm_device)
__context__['retcode'] = 1
return loaded_result
return _discarded
def _explicit_close(napalm_device):
'''
Will explicily close the config session with the network device,
when running in a now-always-alive proxy minion or regular minion.
This helper must be used in configuration-related functions,
as the session is preserved and not closed before making any changes.
'''
if salt.utils.napalm.not_always_alive(__opts__):
# force closing the configuration session
# when running in a non-always-alive proxy
# or regular minion
try:
napalm_device['DRIVER'].close()
except Exception as err:
log.error('Unable to close the temp connection with the device:')
log.error(err)
log.error('Please report.')
def _config_logic(napalm_device,
loaded_result,
test=False,
debug=False,
replace=False,
commit_config=True,
loaded_config=None,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
commit_jid=None,
**kwargs):
'''
Builds the config logic for `load_config` and `load_template` functions.
'''
# As the Salt logic is built around independent events
# when it comes to configuration changes in the
# candidate DB on the network devices, we need to
# make sure we're using the same session.
# Hence, we need to pass the same object around.
# the napalm_device object is inherited from
# the load_config or load_template functions
# and forwarded to compare, discard, commit etc.
# then the decorator will make sure that
# if not proxy (when the connection is always alive)
# and the `inherit_napalm_device` is set,
# `napalm_device` will be overridden.
# See `salt.utils.napalm.proxy_napalm_wrap` decorator.
current_jid = kwargs.get('__pub_jid')
if not current_jid:
current_jid = '{0:%Y%m%d%H%M%S%f}'.format(datetime.datetime.now())
loaded_result['already_configured'] = False
loaded_result['loaded_config'] = ''
if debug:
loaded_result['loaded_config'] = loaded_config
_compare = compare_config(inherit_napalm_device=napalm_device)
if _compare.get('result', False):
loaded_result['diff'] = _compare.get('out')
loaded_result.pop('out', '') # not needed
else:
loaded_result['diff'] = None
loaded_result['result'] = False
loaded_result['comment'] = _compare.get('comment')
__context__['retcode'] = 1
return loaded_result
_loaded_res = loaded_result.get('result', False)
if not _loaded_res or test:
# if unable to load the config (errors / warnings)
# or in testing mode,
# will discard the config
if loaded_result['comment']:
loaded_result['comment'] += '\n'
if not loaded_result.get('diff', ''):
loaded_result['already_configured'] = True
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
loaded_result['comment'] += 'Configuration discarded.'
# loaded_result['result'] = False not necessary
# as the result can be true when test=True
_explicit_close(napalm_device)
if not loaded_result['result']:
__context__['retcode'] = 1
return loaded_result
if not test and commit_config:
# if not in testing mode and trying to commit
if commit_jid:
log.info('Committing the JID: %s', str(commit_jid))
removed = cancel_commit(commit_jid)
log.debug('Cleaned up the commit from the schedule')
log.debug(removed['comment'])
if loaded_result.get('diff', ''):
# if not testing mode
# and also the user wants to commit (default)
# and there are changes to commit
if commit_in or commit_at:
commit_time = __utils__['timeutil.get_time_at'](time_in=commit_in,
time_at=commit_in)
# schedule job
scheduled_job_name = '__napalm_commit_{}'.format(current_jid)
temp_file = salt.utils.files.mkstemp()
with salt.utils.files.fopen(temp_file, 'w') as fp_:
fp_.write(loaded_config)
scheduled = __salt__['schedule.add'](scheduled_job_name,
function='net.load_config',
job_kwargs={
'filename': temp_file,
'commit_jid': current_jid,
'replace': replace
},
once=commit_time)
log.debug('Scheduling job')
log.debug(scheduled)
saved = __salt__['schedule.save']() # ensure the schedule is
# persistent cross Minion restart
discarded = _safe_dicard_config(loaded_result, napalm_device)
# discard the changes
if not discarded['result']:
discarded['comment'] += ('Scheduled the job to be executed at {schedule_ts}, '
'but was unable to discard the config: \n').format(schedule_ts=commit_time)
return discarded
loaded_result['comment'] = ('Changes discarded for now, and scheduled commit at: {schedule_ts}.\n'
'The commit ID is: {current_jid}.\n'
'To discard this commit, you can execute: \n\n'
'salt {min_id} net.cancel_commit {current_jid}').format(schedule_ts=commit_time,
min_id=__opts__['id'],
current_jid=current_jid)
loaded_result['commit_id'] = current_jid
return loaded_result
log.debug('About to commit:')
log.debug(loaded_result['diff'])
if revert_in or revert_at:
revert_time = __utils__['timeutil.get_time_at'](time_in=revert_in,
time_at=revert_at)
if __grains__['os'] == 'junos':
if not HAS_JXMLEASE:
loaded_result['comment'] = ('This feature requires the library jxmlease to be installed.\n'
'To install, please execute: ``pip install jxmlease``.')
loaded_result['result'] = False
return loaded_result
timestamp_at = __utils__['timeutil.get_timestamp_at'](time_in=revert_in,
time_at=revert_at)
minutes = int((timestamp_at - time.time())/60)
_comm = __salt__['napalm.junos_commit'](confirm=minutes)
if not _comm['out']:
# If unable to commit confirm, should try to bail out
loaded_result['comment'] = 'Unable to commit confirm: {}'.format(_comm['message'])
loaded_result['result'] = False
# But before exiting, we must gracefully discard the config
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
else:
temp_file = salt.utils.files.mkstemp()
running_config = __salt__['net.config'](source='running')['out']['running']
with salt.utils.files.fopen(temp_file, 'w') as fp_:
fp_.write(running_config)
committed = _safe_commit_config(loaded_result, napalm_device)
if not committed['result']:
# If unable to commit, dicard the config (which is
# already done by the _safe_commit_config function), and
# return with the command and other details.
return loaded_result
scheduled_job_name = '__napalm_commit_{}'.format(current_jid)
scheduled = __salt__['schedule.add'](scheduled_job_name,
function='net.load_config',
job_kwargs={
'filename': temp_file,
'commit_jid': current_jid,
'replace': True
},
once=revert_time)
log.debug('Scheduling commit confirmed')
log.debug(scheduled)
saved = __salt__['schedule.save']()
loaded_result['comment'] = ('The commit ID is: {current_jid}.\n'
'This commit will be reverted at: {schedule_ts}, unless confirmed.\n'
'To confirm the commit and avoid reverting, you can execute:\n\n'
'salt {min_id} net.confirm_commit {current_jid}').format(schedule_ts=revert_time,
min_id=__opts__['id'],
current_jid=current_jid)
loaded_result['commit_id'] = current_jid
return loaded_result
committed = _safe_commit_config(loaded_result, napalm_device)
if not committed['result']:
return loaded_result
else:
# would like to commit, but there's no change
# need to call discard_config() to release the config DB
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
loaded_result['already_configured'] = True
loaded_result['comment'] = 'Already configured.'
_explicit_close(napalm_device)
if not loaded_result['result']:
__context__['retcode'] = 1
return loaded_result
# ----------------------------------------------------------------------------------------------------------------------
# callable functions
# ----------------------------------------------------------------------------------------------------------------------
@salt.utils.napalm.proxy_napalm_wrap
def connected(**kwargs): # pylint: disable=unused-argument
'''
Specifies if the connection to the device succeeded.
CLI Example:
.. code-block:: bash
salt '*' net.connected
'''
return {
'out': napalm_device.get('UP', False) # pylint: disable=undefined-variable
}
@salt.utils.napalm.proxy_napalm_wrap
def facts(**kwargs): # pylint: disable=unused-argument
'''
Returns characteristics of the network device.
:return: a dictionary with the following keys:
* uptime - Uptime of the device in seconds.
* vendor - Manufacturer of the device.
* model - Device model.
* hostname - Hostname of the device
* fqdn - Fqdn of the device
* os_version - String with the OS version running on the device.
* serial_number - Serial number of the device
* interface_list - List of the interfaces of the device
CLI Example:
.. code-block:: bash
salt '*' net.facts
Example output:
.. code-block:: python
{
'os_version': '13.3R6.5',
'uptime': 10117140,
'interface_list': [
'lc-0/0/0',
'pfe-0/0/0',
'pfh-0/0/0',
'xe-0/0/0',
'xe-0/0/1',
'xe-0/0/2',
'xe-0/0/3',
'gr-0/0/10',
'ip-0/0/10'
],
'vendor': 'Juniper',
'serial_number': 'JN131356FBFA',
'model': 'MX480',
'hostname': 're0.edge05.syd01',
'fqdn': 're0.edge05.syd01'
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_facts',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def environment(**kwargs): # pylint: disable=unused-argument
'''
Returns the environment of the device.
CLI Example:
.. code-block:: bash
salt '*' net.environment
Example output:
.. code-block:: python
{
'fans': {
'Bottom Rear Fan': {
'status': True
},
'Bottom Middle Fan': {
'status': True
},
'Top Middle Fan': {
'status': True
},
'Bottom Front Fan': {
'status': True
},
'Top Front Fan': {
'status': True
},
'Top Rear Fan': {
'status': True
}
},
'memory': {
'available_ram': 16349,
'used_ram': 4934
},
'temperature': {
'FPC 0 Exhaust A': {
'is_alert': False,
'temperature': 35.0,
'is_critical': False
}
},
'cpu': {
'1': {
'%usage': 19.0
},
'0': {
'%usage': 35.0
}
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_environment',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def cli(*commands, **kwargs): # pylint: disable=unused-argument
'''
Returns a dictionary with the raw output of all commands passed as arguments.
commands
List of commands to be executed on the device.
textfsm_parse: ``False``
Try parsing the outputs using the TextFSM templates.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``napalm_cli_textfsm_parse``.
textfsm_path
The path where the TextFSM templates can be found. This option implies
the usage of the TextFSM index file.
``textfsm_path`` can be either absolute path on the server,
either specified using the following URL mschemes: ``file://``,
``salt://``, ``http://``, ``https://``, ``ftp://``,
``s3://``, ``swift://``.
.. versionadded:: 2018.3.0
.. note::
This needs to be a directory with a flat structure, having an
index file (whose name can be specified using the ``index_file`` option)
and a number of TextFSM templates.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_path``.
textfsm_template
The path to a certain the TextFSM template.
This can be specified using the absolute path
to the file, or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
.. versionadded:: 2018.3.0
textfsm_template_dict
A dictionary with the mapping between a command
and the corresponding TextFSM path to use to extract the data.
The TextFSM paths can be specified as in ``textfsm_template``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``napalm_cli_textfsm_template_dict``.
platform_grain_name: ``os``
The name of the grain used to identify the platform name
in the TextFSM index file. Default: ``os``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_grain``.
platform_column_name: ``Platform``
The column name used to identify the platform,
exactly as specified in the TextFSM index file.
Default: ``Platform``.
.. versionadded:: 2018.3.0
.. note::
This is field is case sensitive, make sure
to assign the correct value to this option,
exactly as defined in the index file.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_column_name``.
index_file: ``index``
The name of the TextFSM index file, under the ``textfsm_path``. Default: ``index``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_index_file``.
saltenv: ``base``
Salt fileserver envrionment from which to retrieve the file.
Ignored if ``textfsm_path`` is not a ``salt://`` URL.
.. versionadded:: 2018.3.0
include_empty: ``False``
Include empty files under the ``textfsm_path``.
.. versionadded:: 2018.3.0
include_pat
Glob or regex to narrow down the files cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. versionadded:: 2018.3.0
exclude_pat
Glob or regex to exclude certain files from being cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. versionadded:: 2018.3.0
.. note::
If used with ``include_pat``, files matching this pattern will be
excluded from the subset of files defined by ``include_pat``.
CLI Example:
.. code-block:: bash
salt '*' net.cli "show version" "show chassis fan"
CLI Example with TextFSM template:
.. code-block:: bash
salt '*' net.cli textfsm_parse=True textfsm_path=salt://textfsm/
Example output:
.. code-block:: python
{
'show version and haiku': 'Hostname: re0.edge01.arn01
Model: mx480
Junos: 13.3R6.5
Help me, Obi-Wan
I just saw Episode Two
You're my only hope
',
'show chassis fan' : 'Item Status RPM Measurement
Top Rear Fan OK 3840 Spinning at intermediate-speed
Bottom Rear Fan OK 3840 Spinning at intermediate-speed
Top Middle Fan OK 3900 Spinning at intermediate-speed
Bottom Middle Fan OK 3840 Spinning at intermediate-speed
Top Front Fan OK 3810 Spinning at intermediate-speed
Bottom Front Fan OK 3840 Spinning at intermediate-speed
'
}
Example output with TextFSM parsing:
.. code-block:: json
{
"comment": "",
"result": true,
"out": {
"sh ver": [
{
"kernel": "9.1S3.5",
"documentation": "9.1S3.5",
"boot": "9.1S3.5",
"crypto": "9.1S3.5",
"chassis": "",
"routing": "9.1S3.5",
"base": "9.1S3.5",
"model": "mx960"
}
]
}
}
'''
raw_cli_outputs = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'cli',
**{
'commands': list(commands)
}
)
# thus we can display the output as is
# in case of errors, they'll be catched in the proxy
if not raw_cli_outputs['result']:
# Error -> dispaly the output as-is.
return raw_cli_outputs
textfsm_parse = kwargs.get('textfsm_parse') or __opts__.get('napalm_cli_textfsm_parse') or\
__pillar__.get('napalm_cli_textfsm_parse', False)
if not textfsm_parse:
# No TextFSM parsing required, return raw commands.
log.debug('No TextFSM parsing requested.')
return raw_cli_outputs
if 'textfsm.extract' not in __salt__ or 'textfsm.index' not in __salt__:
raw_cli_outputs['comment'] += 'Unable to process: is TextFSM installed?'
log.error(raw_cli_outputs['comment'])
return raw_cli_outputs
textfsm_template = kwargs.get('textfsm_template')
log.debug('textfsm_template: %s', textfsm_template)
textfsm_path = kwargs.get('textfsm_path') or __opts__.get('textfsm_path') or\
__pillar__.get('textfsm_path')
log.debug('textfsm_path: %s', textfsm_path)
textfsm_template_dict = kwargs.get('textfsm_template_dict') or __opts__.get('napalm_cli_textfsm_template_dict') or\
__pillar__.get('napalm_cli_textfsm_template_dict', {})
log.debug('TextFSM command-template mapping: %s', textfsm_template_dict)
index_file = kwargs.get('index_file') or __opts__.get('textfsm_index_file') or\
__pillar__.get('textfsm_index_file')
log.debug('index_file: %s', index_file)
platform_grain_name = kwargs.get('platform_grain_name') or __opts__.get('textfsm_platform_grain') or\
__pillar__.get('textfsm_platform_grain', 'os')
log.debug('platform_grain_name: %s', platform_grain_name)
platform_column_name = kwargs.get('platform_column_name') or __opts__.get('textfsm_platform_column_name') or\
__pillar__.get('textfsm_platform_column_name', 'Platform')
log.debug('platform_column_name: %s', platform_column_name)
saltenv = kwargs.get('saltenv', 'base')
include_empty = kwargs.get('include_empty', False)
include_pat = kwargs.get('include_pat')
exclude_pat = kwargs.get('exclude_pat')
processed_cli_outputs = {
'comment': raw_cli_outputs.get('comment', ''),
'result': raw_cli_outputs['result'],
'out': {}
}
log.debug('Starting to analyse the raw outputs')
for command in list(commands):
command_output = raw_cli_outputs['out'][command]
log.debug('Output from command: %s', command)
log.debug(command_output)
processed_command_output = None
if textfsm_path:
log.debug('Using the templates under %s', textfsm_path)
processed_cli_output = __salt__['textfsm.index'](command,
platform_grain_name=platform_grain_name,
platform_column_name=platform_column_name,
output=command_output.strip(),
textfsm_path=textfsm_path,
saltenv=saltenv,
include_empty=include_empty,
include_pat=include_pat,
exclude_pat=exclude_pat)
log.debug('Processed CLI output:')
log.debug(processed_cli_output)
if not processed_cli_output['result']:
log.debug('Apparently this didnt work, returnin the raw output')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {0}: {1}.'.format(command,
processed_cli_output['comment'])
log.error(processed_cli_outputs['comment'])
elif processed_cli_output['out']:
log.debug('All good, %s has a nice output!', command)
processed_command_output = processed_cli_output['out']
else:
comment = '''\nProcessing "{}" didn't fail, but didn't return anything either. Dumping raw.'''.format(
command)
processed_cli_outputs['comment'] += comment
log.error(comment)
processed_command_output = command_output
elif textfsm_template or command in textfsm_template_dict:
if command in textfsm_template_dict:
textfsm_template = textfsm_template_dict[command]
log.debug('Using %s to process the command: %s', textfsm_template, command)
processed_cli_output = __salt__['textfsm.extract'](textfsm_template,
raw_text=command_output,
saltenv=saltenv)
log.debug('Processed CLI output:')
log.debug(processed_cli_output)
if not processed_cli_output['result']:
log.debug('Apparently this didnt work, returning '
'the raw output')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {0}: {1}'.format(command,
processed_cli_output['comment'])
log.error(processed_cli_outputs['comment'])
elif processed_cli_output['out']:
log.debug('All good, %s has a nice output!', command)
processed_command_output = processed_cli_output['out']
else:
log.debug('Processing %s didnt fail, but didnt return'
' anything either. Dumping raw.', command)
processed_command_output = command_output
else:
log.error('No TextFSM template specified, or no TextFSM path defined')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {}.'.format(command)
processed_cli_outputs['out'][command] = processed_command_output
processed_cli_outputs['comment'] = processed_cli_outputs['comment'].strip()
return processed_cli_outputs
@salt.utils.napalm.proxy_napalm_wrap
def traceroute(destination, source=None, ttl=None, timeout=None, vrf=None, **kwargs): # pylint: disable=unused-argument
'''
Calls the method traceroute from the NAPALM driver object and returns a dictionary with the result of the traceroute
command executed on the device.
destination
Hostname or address of remote host
source
Source address to use in outgoing traceroute packets
ttl
IP maximum time-to-live value (or IPv6 maximum hop-limit value)
timeout
Number of seconds to wait for response (seconds)
vrf
VRF (routing instance) for traceroute attempt
.. versionadded:: 2016.11.4
CLI Example:
.. code-block:: bash
salt '*' net.traceroute 8.8.8.8
salt '*' net.traceroute 8.8.8.8 source=127.0.0.1 ttl=5 timeout=1
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'traceroute',
**{
'destination': destination,
'source': source,
'ttl': ttl,
'timeout': timeout,
'vrf': vrf
}
)
@salt.utils.napalm.proxy_napalm_wrap
def ping(destination, source=None, ttl=None, timeout=None, size=None, count=None, vrf=None, **kwargs): # pylint: disable=unused-argument
'''
Executes a ping on the network device and returns a dictionary as a result.
destination
Hostname or IP address of remote host
source
Source address of echo request
ttl
IP time-to-live value (IPv6 hop-limit value) (1..255 hops)
timeout
Maximum wait time after sending final packet (seconds)
size
Size of request packets (0..65468 bytes)
count
Number of ping requests to send (1..2000000000 packets)
vrf
VRF (routing instance) for ping attempt
.. versionadded:: 2016.11.4
CLI Example:
.. code-block:: bash
salt '*' net.ping 8.8.8.8
salt '*' net.ping 8.8.8.8 ttl=3 size=65468
salt '*' net.ping 8.8.8.8 source=127.0.0.1 timeout=1 count=100
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'ping',
**{
'destination': destination,
'source': source,
'ttl': ttl,
'timeout': timeout,
'size': size,
'count': count,
'vrf': vrf
}
)
@salt.utils.napalm.proxy_napalm_wrap
def arp(interface='', ipaddr='', macaddr='', **kwargs): # pylint: disable=unused-argument
'''
NAPALM returns a list of dictionaries with details of the ARP entries.
:param interface: interface name to filter on
:param ipaddr: IP address to filter on
:param macaddr: MAC address to filter on
:return: List of the entries in the ARP table
CLI Example:
.. code-block:: bash
salt '*' net.arp
salt '*' net.arp macaddr='5c:5e:ab:da:3c:f0'
Example output:
.. code-block:: python
[
{
'interface' : 'MgmtEth0/RSP0/CPU0/0',
'mac' : '5c:5e:ab:da:3c:f0',
'ip' : '172.17.17.1',
'age' : 1454496274.84
},
{
'interface': 'MgmtEth0/RSP0/CPU0/0',
'mac' : '66:0e:94:96:e0:ff',
'ip' : '172.17.17.2',
'age' : 1435641582.49
}
]
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_arp_table',
**{
}
)
if not proxy_output.get('result'):
return proxy_output
arp_table = proxy_output.get('out')
if interface:
arp_table = _filter_list(arp_table, 'interface', interface)
if ipaddr:
arp_table = _filter_list(arp_table, 'ip', ipaddr)
if macaddr:
arp_table = _filter_list(arp_table, 'mac', macaddr)
proxy_output.update({
'out': arp_table
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def ipaddrs(**kwargs): # pylint: disable=unused-argument
'''
Returns IP addresses configured on the device.
:return: A dictionary with the IPv4 and IPv6 addresses of the interfaces.
Returns all configured IP addresses on all interfaces as a dictionary
of dictionaries. Keys of the main dictionary represent the name of the
interface. Values of the main dictionary represent are dictionaries
that may consist of two keys 'ipv4' and 'ipv6' (one, both or none)
which are themselvs dictionaries with the IP addresses as keys.
CLI Example:
.. code-block:: bash
salt '*' net.ipaddrs
Example output:
.. code-block:: python
{
'FastEthernet8': {
'ipv4': {
'10.66.43.169': {
'prefix_length': 22
}
}
},
'Loopback555': {
'ipv4': {
'192.168.1.1': {
'prefix_length': 24
}
},
'ipv6': {
'1::1': {
'prefix_length': 64
},
'2001:DB8:1::1': {
'prefix_length': 64
},
'FE80::3': {
'prefix_length': 'N/A'
}
}
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_interfaces_ip',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def interfaces(**kwargs): # pylint: disable=unused-argument
'''
Returns details of the interfaces on the device.
:return: Returns a dictionary of dictionaries. The keys for the first
dictionary will be the interfaces in the devices.
CLI Example:
.. code-block:: bash
salt '*' net.interfaces
Example output:
.. code-block:: python
{
'Management1': {
'is_up': False,
'is_enabled': False,
'description': '',
'last_flapped': -1,
'speed': 1000,
'mac_address': 'dead:beef:dead',
},
'Ethernet1':{
'is_up': True,
'is_enabled': True,
'description': 'foo',
'last_flapped': 1429978575.1554043,
'speed': 1000,
'mac_address': 'beef:dead:beef',
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_interfaces',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
@salt.utils.napalm.proxy_napalm_wrap
def mac(address='', interface='', vlan=0, **kwargs): # pylint: disable=unused-argument
'''
Returns the MAC Address Table on the device.
:param address: MAC address to filter on
:param interface: Interface name to filter on
:param vlan: VLAN identifier
:return: A list of dictionaries representing the entries in the MAC Address Table
CLI Example:
.. code-block:: bash
salt '*' net.mac
salt '*' net.mac vlan=10
Example output:
.. code-block:: python
[
{
'mac' : '00:1c:58:29:4a:71',
'interface' : 'xe-3/0/2',
'static' : False,
'active' : True,
'moves' : 1,
'vlan' : 10,
'last_move' : 1454417742.58
},
{
'mac' : '8c:60:4f:58:e1:c1',
'interface' : 'xe-1/0/1',
'static' : False,
'active' : True,
'moves' : 2,
'vlan' : 42,
'last_move' : 1453191948.11
}
]
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_mac_address_table',
**{
}
)
if not proxy_output.get('result'):
# if negative, leave the output unchanged
return proxy_output
mac_address_table = proxy_output.get('out')
if vlan and isinstance(vlan, int):
mac_address_table = _filter_list(mac_address_table, 'vlan', vlan)
if address:
mac_address_table = _filter_list(mac_address_table, 'mac', address)
if interface:
mac_address_table = _filter_list(mac_address_table, 'interface', interface)
proxy_output.update({
'out': mac_address_table
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def config(source=None, **kwargs): # pylint: disable=unused-argument
'''
.. versionadded:: 2017.7.0
Return the whole configuration of the network device. By default, it will
return all possible configuration sources supported by the network device.
At most, there will be:
- running config
- startup config
- candidate config
To return only one of the configurations, you can use the ``source``
argument.
source
Which configuration type you want to display, default is all of them.
Options:
- running
- candidate
- startup
:return:
The object returned is a dictionary with the following keys:
- running (string): Representation of the native running configuration.
- candidate (string): Representation of the native candidate configuration.
If the device doesn't differentiate between running and startup
configuration this will an empty string.
- startup (string): Representation of the native startup configuration.
If the device doesn't differentiate between running and startup
configuration this will an empty string.
CLI Example:
.. code-block:: bash
salt '*' net.config
salt '*' net.config source=candidate
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_config',
**{
'retrieve': source
}
)
@salt.utils.napalm.proxy_napalm_wrap
def optics(**kwargs): # pylint: disable=unused-argument
'''
.. versionadded:: 2017.7.0
Fetches the power usage on the various transceivers installed
on the network device (in dBm), and returns a view that conforms with the
OpenConfig model openconfig-platform-transceiver.yang.
:return:
Returns a dictionary where the keys are as listed below:
* intf_name (unicode)
* physical_channels
* channels (list of dicts)
* index (int)
* state
* input_power
* instant (float)
* avg (float)
* min (float)
* max (float)
* output_power
* instant (float)
* avg (float)
* min (float)
* max (float)
* laser_bias_current
* instant (float)
* avg (float)
* min (float)
* max (float)
CLI Example:
.. code-block:: bash
salt '*' net.optics
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_optics',
**{
}
)
# <---- Call NAPALM getters --------------------------------------------------------------------------------------------
# ----- Configuration specific functions ------------------------------------------------------------------------------>
@salt.utils.napalm.proxy_napalm_wrap
def load_config(filename=None,
text=None,
test=False,
commit=True,
debug=False,
replace=False,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
commit_jid=None,
inherit_napalm_device=None,
saltenv='base',
**kwargs): # pylint: disable=unused-argument
'''
Applies configuration changes on the device. It can be loaded from a file or from inline string.
If you send both a filename and a string containing the configuration, the file has higher precedence.
By default this function will commit the changes. If there are no changes, it does not commit and
the flag ``already_configured`` will be set as ``True`` to point this out.
To avoid committing the configuration, set the argument ``test`` to ``True`` and will discard (dry run).
To keep the changes but not commit, set ``commit`` to ``False``.
To replace the config, set ``replace`` to ``True``.
filename
Path to the file containing the desired configuration.
This can be specified using the absolute path to the file,
or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
.. versionchanged:: 2018.3.0
text
String containing the desired configuration.
This argument is ignored when ``filename`` is specified.
test: False
Dry run? If set as ``True``, will apply the config, discard and return the changes. Default: ``False``
and will commit the changes on the device.
commit: True
Commit? Default: ``True``.
debug: False
Debug mode. Will insert a new key under the output dictionary, as ``loaded_config`` containing the raw
configuration loaded on the device.
.. versionadded:: 2016.11.2
replace: False
Load and replace the configuration. Default: ``False``.
.. versionadded:: 2016.11.2
commit_in: ``None``
Commit the changes in a specific number of minutes / hours. Example of
accepted formats: ``5`` (commit in 5 minutes), ``2m`` (commit in 2
minutes), ``1h`` (commit the changes in 1 hour)`, ``5h30m`` (commit
the changes in 5 hours and 30 minutes).
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
commit_at: ``None``
Commit the changes at a specific time. Example of accepted formats:
``1am`` (will commit the changes at the next 1AM), ``13:20`` (will
commit at 13:20), ``1:20am``, etc.
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
revert_in: ``None``
Commit and revert the changes in a specific number of minutes / hours.
Example of accepted formats: ``5`` (revert in 5 minutes), ``2m`` (revert
in 2 minutes), ``1h`` (revert the changes in 1 hour)`, ``5h30m`` (revert
the changes in 5 hours and 30 minutes).
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
revert_at: ``None``
Commit and revert the changes at a specific time. Example of accepted
formats: ``1am`` (will commit and revert the changes at the next 1AM),
``13:20`` (will commit and revert at 13:20), ``1:20am``, etc.
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
saltenv: ``base``
Specifies the Salt environment name.
.. versionadded:: 2018.3.0
:return: a dictionary having the following keys:
* result (bool): if the config was applied successfully. It is ``False`` only in case of failure. In case \
there are no changes to be applied and successfully performs all operations it is still ``True`` and so will be \
the ``already_configured`` flag (example below)
* comment (str): a message for the user
* already_configured (bool): flag to check if there were no changes applied
* loaded_config (str): the configuration loaded on the device. Requires ``debug`` to be set as ``True``
* diff (str): returns the config changes applied
CLI Example:
.. code-block:: bash
salt '*' net.load_config text='ntp peer 192.168.0.1'
salt '*' net.load_config filename='/absolute/path/to/your/file'
salt '*' net.load_config filename='/absolute/path/to/your/file' test=True
salt '*' net.load_config filename='/absolute/path/to/your/file' commit=False
Example output:
.. code-block:: python
{
'comment': 'Configuration discarded.',
'already_configured': False,
'result': True,
'diff': '[edit interfaces xe-0/0/5]+ description "Adding a description";'
}
'''
fun = 'load_merge_candidate'
if replace:
fun = 'load_replace_candidate'
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
if filename:
text = __salt__['cp.get_file_str'](filename, saltenv=saltenv)
if text is False:
# When using salt:// or https://, if the resource is not available,
# it will either raise an exception, or return False.
ret = {
'result': False,
'out': None
}
ret['comment'] = 'Unable to read from {}. Please specify a valid file or text.'.format(filename)
log.error(ret['comment'])
return ret
if commit_jid:
# When the commit_jid argument is passed, it probably is a scheduled
# commit to be executed, and filename is a temporary file which
# can be removed after reading it.
salt.utils.files.safe_rm(filename)
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
fun,
**{
'config': text
}
)
return _config_logic(napalm_device, # pylint: disable=undefined-variable
_loaded,
test=test,
debug=debug,
replace=replace,
commit_config=commit,
loaded_config=text,
commit_at=commit_at,
commit_in=commit_in,
revert_in=revert_in,
revert_at=revert_at,
commit_jid=commit_jid,
**kwargs)
@salt.utils.napalm.proxy_napalm_wrap
def load_template(template_name=None,
template_source=None,
context=None,
defaults=None,
template_engine='jinja',
saltenv='base',
template_hash=None,
template_hash_name=None,
skip_verify=False,
test=False,
commit=True,
debug=False,
replace=False,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
inherit_napalm_device=None, # pylint: disable=unused-argument
**template_vars):
'''
Renders a configuration template (default: Jinja) and loads the result on the device.
By default this function will commit the changes. If there are no changes,
it does not commit, discards he config and the flag ``already_configured``
will be set as ``True`` to point this out.
To avoid committing the configuration, set the argument ``test`` to ``True``
and will discard (dry run).
To preserve the changes, set ``commit`` to ``False``.
However, this is recommended to be used only in exceptional cases
when there are applied few consecutive states
and/or configuration changes.
Otherwise the user might forget that the config DB is locked
and the candidate config buffer is not cleared/merged in the running config.
To replace the config, set ``replace`` to ``True``.
template_name
Identifies path to the template source.
The template can be either stored on the local machine, either remotely.
The recommended location is under the ``file_roots``
as specified in the master config file.
For example, let's suppose the ``file_roots`` is configured as:
.. code-block:: yaml
file_roots:
base:
- /etc/salt/states
Placing the template under ``/etc/salt/states/templates/example.jinja``,
it can be used as ``salt://templates/example.jinja``.
Alternatively, for local files, the user can specify the absolute path.
If remotely, the source can be retrieved via ``http``, ``https`` or ``ftp``.
Examples:
- ``salt://my_template.jinja``
- ``/absolute/path/to/my_template.jinja``
- ``http://example.com/template.cheetah``
- ``https:/example.com/template.mako``
- ``ftp://example.com/template.py``
.. versionchanged:: 2019.2.0
This argument can now support a list of templates to be rendered.
The resulting configuration text is loaded at once, as a single
configuration chunk.
template_source: None
Inline config template to be rendered and loaded on the device.
template_hash: None
Hash of the template file. Format: ``{hash_type: 'md5', 'hsum': <md5sum>}``
.. versionadded:: 2016.11.2
context: None
Overrides default context variables passed to the template.
.. versionadded:: 2019.2.0
template_hash_name: None
When ``template_hash`` refers to a remote file,
this specifies the filename to look for in that file.
.. versionadded:: 2016.11.2
saltenv: ``base``
Specifies the template environment.
This will influence the relative imports inside the templates.
.. versionadded:: 2016.11.2
template_engine: jinja
The following templates engines are supported:
- :mod:`cheetah<salt.renderers.cheetah>`
- :mod:`genshi<salt.renderers.genshi>`
- :mod:`jinja<salt.renderers.jinja>`
- :mod:`mako<salt.renderers.mako>`
- :mod:`py<salt.renderers.py>`
- :mod:`wempy<salt.renderers.wempy>`
.. versionadded:: 2016.11.2
skip_verify: True
If ``True``, hash verification of remote file sources
(``http://``, ``https://``, ``ftp://``) will be skipped,
and the ``source_hash`` argument will be ignored.
.. versionadded:: 2016.11.2
test: False
Dry run? If set to ``True``, will apply the config,
discard and return the changes.
Default: ``False`` and will commit the changes on the device.
commit: True
Commit? (default: ``True``)
debug: False
Debug mode. Will insert a new key under the output dictionary,
as ``loaded_config`` containing the raw result after the template was rendered.
.. versionadded:: 2016.11.2
replace: False
Load and replace the configuration.
.. versionadded:: 2016.11.2
commit_in: ``None``
Commit the changes in a specific number of minutes / hours. Example of
accepted formats: ``5`` (commit in 5 minutes), ``2m`` (commit in 2
minutes), ``1h`` (commit the changes in 1 hour)`, ``5h30m`` (commit
the changes in 5 hours and 30 minutes).
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
commit_at: ``None``
Commit the changes at a specific time. Example of accepted formats:
``1am`` (will commit the changes at the next 1AM), ``13:20`` (will
commit at 13:20), ``1:20am``, etc.
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
revert_in: ``None``
Commit and revert the changes in a specific number of minutes / hours.
Example of accepted formats: ``5`` (revert in 5 minutes), ``2m`` (revert
in 2 minutes), ``1h`` (revert the changes in 1 hour)`, ``5h30m`` (revert
the changes in 5 hours and 30 minutes).
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
revert_at: ``None``
Commit and revert the changes at a specific time. Example of accepted
formats: ``1am`` (will commit and revert the changes at the next 1AM),
``13:20`` (will commit and revert at 13:20), ``1:20am``, etc.
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
defaults: None
Default variables/context passed to the template.
.. versionadded:: 2016.11.2
template_vars
Dictionary with the arguments/context to be used when the template is rendered.
.. note::
Do not explicitly specify this argument. This represents any other
variable that will be sent to the template rendering system.
Please see the examples below!
.. note::
It is more recommended to use the ``context`` argument to avoid
conflicts between CLI arguments and template variables.
:return: a dictionary having the following keys:
- result (bool): if the config was applied successfully. It is ``False``
only in case of failure. In case there are no changes to be applied and
successfully performs all operations it is still ``True`` and so will be
the ``already_configured`` flag (example below)
- comment (str): a message for the user
- already_configured (bool): flag to check if there were no changes applied
- loaded_config (str): the configuration loaded on the device, after
rendering the template. Requires ``debug`` to be set as ``True``
- diff (str): returns the config changes applied
The template can use variables from the ``grains``, ``pillar`` or ``opts``, for example:
.. code-block:: jinja
{% set router_model = grains.get('model') -%}
{% set router_vendor = grains.get('vendor') -%}
{% set os_version = grains.get('version') -%}
{% set hostname = pillar.get('proxy', {}).get('host') -%}
{% if router_vendor|lower == 'juniper' %}
system {
host-name {{hostname}};
}
{% elif router_vendor|lower == 'cisco' %}
hostname {{hostname}}
{% endif %}
CLI Examples:
.. code-block:: bash
salt '*' net.load_template set_ntp_peers peers=[192.168.0.1] # uses NAPALM default templates
# inline template:
salt -G 'os:junos' net.load_template template_source='system { host-name {{host_name}}; }' \
host_name='MX480.lab'
# inline template using grains info:
salt -G 'os:junos' net.load_template \
template_source='system { host-name {{grains.model}}.lab; }'
# if the device is a MX480, the command above will set the hostname as: MX480.lab
# inline template using pillar data:
salt -G 'os:junos' net.load_template template_source='system { host-name {{pillar.proxy.host}}; }'
salt '*' net.load_template https://bit.ly/2OhSgqP hostname=example # will commit
salt '*' net.load_template https://bit.ly/2OhSgqP hostname=example test=True # dry run
salt '*' net.load_template salt://templates/example.jinja debug=True # Using the salt:// URI
# render a mako template:
salt '*' net.load_template salt://templates/example.mako template_engine=mako debug=True
# render remote template
salt -G 'os:junos' net.load_template http://bit.ly/2fReJg7 test=True debug=True peers=['192.168.0.1']
salt -G 'os:ios' net.load_template http://bit.ly/2gKOj20 test=True debug=True peers=['192.168.0.1']
# render multiple templates at once
salt '*' net.load_template "['https://bit.ly/2OhSgqP', 'salt://templates/example.jinja']" context="{'hostname': 'example'}"
Example output:
.. code-block:: python
{
'comment': '',
'already_configured': False,
'result': True,
'diff': '[edit system]+ host-name edge01.bjm01',
'loaded_config': 'system { host-name edge01.bjm01; }''
}
'''
_rendered = ''
_loaded = {
'result': True,
'comment': '',
'out': None
}
loaded_config = None
# prechecks
deprecated_args = ('template_user', 'template_attrs', 'template_group', 'template_mode')
for deprecated_arg in deprecated_args:
if template_vars.get(deprecated_arg):
del template_vars[deprecated_arg]
salt.utils.versions.warn_until(
'Sodium',
('The \'{arg}\' argument to \'net.load_template\' is deprecated '
'and has been ignored').format(arg=deprecated_arg)
)
if template_engine not in salt.utils.templates.TEMPLATE_REGISTRY:
_loaded.update({
'result': False,
'comment': 'Invalid templating engine! Choose between: {tpl_eng_opts}'.format(
tpl_eng_opts=', '.join(list(salt.utils.templates.TEMPLATE_REGISTRY.keys()))
)
})
return _loaded # exit
# to check if will be rendered by salt or NAPALM
salt_render_prefixes = ('salt://', 'http://', 'https://', 'ftp://')
salt_render = False
file_exists = False
if not isinstance(template_name, (tuple, list)):
for salt_render_prefix in salt_render_prefixes:
if not salt_render:
salt_render = salt_render or template_name.startswith(salt_render_prefix)
file_exists = __salt__['file.file_exists'](template_name)
if template_source or file_exists or salt_render or isinstance(template_name, (tuple, list)):
# either inline template
# either template in a custom path
# either abs path send
# either starts with salt:// and
# then use Salt render system
if context is None:
context = {}
context.update(template_vars)
# if needed to render the template send as inline arg
if template_source:
# render the content
_rendered = __salt__['file.apply_template_on_contents'](
contents=template_source,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv
)
if not isinstance(_rendered, six.string_types):
if 'result' in _rendered:
_loaded['result'] = _rendered['result']
else:
_loaded['result'] = False
if 'comment' in _rendered:
_loaded['comment'] = _rendered['comment']
else:
_loaded['comment'] = 'Error while rendering the template.'
return _loaded
else:
# render the file - either local, either remote
if not isinstance(template_name, (list, tuple)):
template_name = [template_name]
if template_hash_name and not isinstance(template_hash_name, (list, tuple)):
template_hash_name = [template_hash_name]
elif not template_hash_name:
template_hash_name = [None] * len(template_name)
if template_hash and isinstance(template_hash, six.string_types) and not\
(template_hash.startswith('salt://') or template_hash.startswith('file://')):
# If the template hash is passed as string, and it's not a file
# (starts with the salt:// or file:// URI), then make it a list
# of 1 element (for the iteration below)
template_hash = [template_hash]
elif template_hash and isinstance(template_hash, six.string_types) and\
(template_hash.startswith('salt://') or template_hash.startswith('file://')):
# If the template hash is a file URI, then provide the same value
# for each of the templates in the list, as probably they all
# share the same hash file, otherwise the user should provide
# this as a list
template_hash = [template_hash] * len(template_name)
elif not template_hash:
template_hash = [None] * len(template_name)
for tpl_index, tpl_name in enumerate(template_name):
tpl_hash = template_hash[tpl_index]
tpl_hash_name = template_hash_name[tpl_index]
_rand_filename = __salt__['random.hash'](tpl_name, 'md5')
_temp_file = __salt__['file.join']('/tmp', _rand_filename)
_managed = __salt__['file.get_managed'](name=_temp_file,
source=tpl_name,
source_hash=tpl_hash,
source_hash_name=tpl_hash_name,
user=None,
group=None,
mode=None,
attrs=None,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv,
skip_verify=skip_verify)
if not isinstance(_managed, (list, tuple)) and isinstance(_managed, six.string_types):
_loaded['comment'] += _managed
_loaded['result'] = False
elif isinstance(_managed, (list, tuple)) and not _managed:
_loaded['result'] = False
_loaded['comment'] += 'Error while rendering the template.'
elif isinstance(_managed, (list, tuple)) and not _managed[0]:
_loaded['result'] = False
_loaded['comment'] += _managed[-1] # contains the error message
if _loaded['result']: # all good
_temp_tpl_file = _managed[0]
_temp_tpl_file_exists = __salt__['file.file_exists'](_temp_tpl_file)
if not _temp_tpl_file_exists:
_loaded['result'] = False
_loaded['comment'] += 'Error while rendering the template.'
return _loaded
_rendered += __salt__['file.read'](_temp_tpl_file)
__salt__['file.remove'](_temp_tpl_file)
else:
return _loaded # exit
loaded_config = _rendered
if _loaded['result']: # all good
fun = 'load_merge_candidate'
if replace: # replace requested
fun = 'load_replace_candidate'
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
fun,
**{
'config': _rendered
}
)
else:
salt.utils.versions.warn_until(
'Sodium',
'Native NAPALM templates support will be removed in the Sodium '
'release. Please consider using the Salt rendering pipeline instead.'
'If you are using the \'netntp\', \'netsnmp\', or \'netusers\' Salt '
'State modules, you can ignore this message'
)
# otherwise, use NAPALM render system, injecting pillar/grains/opts vars
load_templates_params = defaults if defaults else {}
load_templates_params.update(template_vars)
load_templates_params.update(
{
'template_name': template_name,
'template_source': template_source, # inline template
'pillar': __pillar__, # inject pillar content
'grains': __grains__, # inject grains content
'opts': __opts__ # inject opts content
}
)
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
# so we'll set the CLOSE global explicitly as False
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'load_template',
**load_templates_params
)
return _config_logic(napalm_device, # pylint: disable=undefined-variable
_loaded,
test=test,
debug=debug,
replace=replace,
commit_config=commit,
loaded_config=loaded_config,
commit_at=commit_at,
commit_in=commit_in,
revert_in=revert_in,
revert_at=revert_at,
**template_vars)
@salt.utils.napalm.proxy_napalm_wrap
def commit(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Commits the configuration changes made on the network device.
CLI Example:
.. code-block:: bash
salt '*' net.commit
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'commit_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def discard_config(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
"""
Discards the changes applied.
CLI Example:
.. code-block:: bash
salt '*' net.discard_config
"""
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'discard_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def compare_config(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Returns the difference between the running config and the candidate config.
CLI Example:
.. code-block:: bash
salt '*' net.compare_config
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'compare_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def rollback(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Rollbacks the configuration.
CLI Example:
.. code-block:: bash
salt '*' net.rollback
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'rollback',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def config_changed(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Will prompt if the configuration has been changed.
:return: A tuple with a boolean that specifies if the config was changed on the device.\
And a string that provides more details of the reason why the configuration was not changed.
CLI Example:
.. code-block:: bash
salt '*' net.config_changed
'''
is_config_changed = False
reason = ''
try_compare = compare_config(inherit_napalm_device=napalm_device) # pylint: disable=undefined-variable
if try_compare.get('result'):
if try_compare.get('out'):
is_config_changed = True
else:
reason = 'Configuration was not changed on the device.'
else:
reason = try_compare.get('comment')
return is_config_changed, reason
@salt.utils.napalm.proxy_napalm_wrap
def config_control(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Will check if the configuration was changed.
If differences found, will try to commit.
In case commit unsuccessful, will try to rollback.
:return: A tuple with a boolean that specifies if the config was changed/committed/rollbacked on the device.\
And a string that provides more details of the reason why the configuration was not committed properly.
CLI Example:
.. code-block:: bash
salt '*' net.config_control
'''
result = True
comment = ''
changed, not_changed_rsn = config_changed(inherit_napalm_device=napalm_device) # pylint: disable=undefined-variable
if not changed:
return (changed, not_changed_rsn)
# config changed, thus let's try to commit
try_commit = commit()
if not try_commit.get('result'):
result = False
comment = 'Unable to commit the changes: {reason}.\n\
Will try to rollback now!'.format(
reason=try_commit.get('comment')
)
try_rollback = rollback()
if not try_rollback.get('result'):
comment += '\nCannot rollback! {reason}'.format(
reason=try_rollback.get('comment')
)
return result, comment
def cancel_commit(jid):
'''
.. versionadded:: 2019.2.0
Cancel a commit scheduled to be executed via the ``commit_in`` and
``commit_at`` arguments from the
:py:func:`net.load_template <salt.modules.napalm_network.load_template>` or
:py:func:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit ID is displayed when the commit is scheduled
via the functions named above.
CLI Example:
.. code-block:: bash
salt '*' net.cancel_commit 20180726083540640360
'''
job_name = '__napalm_commit_{}'.format(jid)
removed = __salt__['schedule.delete'](job_name)
if removed['result']:
saved = __salt__['schedule.save']()
removed['comment'] = 'Commit #{jid} cancelled.'.format(jid=jid)
else:
removed['comment'] = 'Unable to find commit #{jid}.'.format(jid=jid)
return removed
def confirm_commit(jid):
'''
.. versionadded:: 2019.2.0
Confirm a commit scheduled to be reverted via the ``revert_in`` and
``revert_at`` arguments from the
:mod:`net.load_template <salt.modules.napalm_network.load_template>` or
:mod:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit ID is displayed when the commit confirmed
is scheduled via the functions named above.
CLI Example:
.. code-block:: bash
salt '*' net.confirm_commit 20180726083540640360
'''
if __grains__['os'] == 'junos':
# Confirm the commit, by committing (i.e., invoking the RPC call)
confirmed = __salt__['napalm.junos_commit']()
confirmed['result'] = confirmed.pop('out')
confirmed['comment'] = confirmed.pop('message')
else:
confirmed = cancel_commit(jid)
if confirmed['result']:
confirmed['comment'] = 'Commit #{jid} confirmed.'.format(jid=jid)
return confirmed
def save_config(source=None,
path=None):
'''
.. versionadded:: 2019.2.0
Save the configuration to a file on the local file system.
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``,
``startup``. Default: ``running``.
path
Absolute path to file where to save the configuration.
To push the files to the Master, use
:mod:`cp.push <salt.modules.cp.push>` Execution function.
CLI Example:
.. code-block:: bash
salt '*' net.save_config source=running
'''
if not source:
source = 'running'
if not path:
path = salt.utils.files.mkstemp()
running_config = __salt__['net.config'](source=source)
if not running_config or not running_config['result']:
log.error('Unable to retrieve the config')
return running_config
with salt.utils.files.fopen(path, 'w') as fh_:
fh_.write(running_config['out'][source])
return {
'result': True,
'out': path,
'comment': '{source} config saved to {path}'.format(source=source, path=path)
}
def replace_pattern(pattern,
repl,
count=0,
flags=8,
bufsize=1,
append_if_not_found=False,
prepend_if_not_found=False,
not_found_content=None,
search_only=False,
show_changes=True,
backslash_literal=False,
source=None,
path=None,
test=False,
replace=True,
debug=False,
commit=True):
'''
.. versionadded:: 2019.2.0
Replace occurrences of a pattern in the configuration source. If
``show_changes`` is ``True``, then a diff of what changed will be returned,
otherwise a ``True`` will be returned when changes are made, and ``False``
when no changes are made.
This is a pure Python implementation that wraps Python's :py:func:`~re.sub`.
pattern
A regular expression, to be matched using Python's
:py:func:`~re.search`.
repl
The replacement text.
count: ``0``
Maximum number of pattern occurrences to be replaced. If count is a
positive integer ``n``, only ``n`` occurrences will be replaced,
otherwise all occurrences will be replaced.
flags (list or int): ``8``
A list of flags defined in the ``re`` module documentation from the
Python standard library. Each list item should be a string that will
correlate to the human-friendly flag name. E.g., ``['IGNORECASE',
'MULTILINE']``. Optionally, ``flags`` may be an int, with a value
corresponding to the XOR (``|``) of all the desired flags. Defaults to
8 (which supports 'MULTILINE').
bufsize (int or str): ``1``
How much of the configuration to buffer into memory at once. The
default value ``1`` processes one line at a time. The special value
``file`` may be specified which will read the entire file into memory
before processing.
append_if_not_found: ``False``
If set to ``True``, and pattern is not found, then the content will be
appended to the file.
prepend_if_not_found: ``False``
If set to ``True`` and pattern is not found, then the content will be
prepended to the file.
not_found_content
Content to use for append/prepend if not found. If None (default), uses
``repl``. Useful when ``repl`` uses references to group in pattern.
search_only: ``False``
If set to true, this no changes will be performed on the file, and this
function will simply return ``True`` if the pattern was matched, and
``False`` if not.
show_changes: ``True``
If ``True``, return a diff of changes made. Otherwise, return ``True``
if changes were made, and ``False`` if not.
backslash_literal: ``False``
Interpret backslashes as literal backslashes for the repl and not
escape characters. This will help when using append/prepend so that
the backslashes are not interpreted for the repl on the second run of
the state.
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path
Save the temporary configuration to a specific path, then read from
there.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' net.replace_pattern "bind-address\\s*=" "bind-address:"
CLI Example:
.. code-block:: bash
salt '*' net.replace_pattern PREFIX-LIST_NAME new-prefix-list-name
salt '*' net.replace_pattern bgp-group-name new-bgp-group-name count=1
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
replace_pattern = __salt__['file.replace'](path,
pattern,
repl,
count=count,
flags=flags,
bufsize=bufsize,
append_if_not_found=append_if_not_found,
prepend_if_not_found=prepend_if_not_found,
not_found_content=not_found_content,
search_only=search_only,
show_changes=show_changes,
backslash_literal=backslash_literal)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
def blockreplace(marker_start,
marker_end,
content='',
append_if_not_found=False,
prepend_if_not_found=False,
show_changes=True,
append_newline=False,
source='running',
path=None,
test=False,
commit=True,
debug=False,
replace=True):
'''
.. versionadded:: 2019.2.0
Replace content of the configuration source, delimited by the line markers.
A block of content delimited by comments can help you manage several lines
without worrying about old entries removal.
marker_start
The line content identifying a line as the start of the content block.
Note that the whole line containing this marker will be considered,
so whitespace or extra content before or after the marker is included
in final output.
marker_end
The line content identifying a line as the end of the content block.
Note that the whole line containing this marker will be considered,
so whitespace or extra content before or after the marker is included
in final output.
content
The content to be used between the two lines identified by
``marker_start`` and ``marker_stop``.
append_if_not_found: ``False``
If markers are not found and set to True then, the markers and content
will be appended to the file.
prepend_if_not_found: ``False``
If markers are not found and set to True then, the markers and content
will be prepended to the file.
append_newline: ``False``
Controls whether or not a newline is appended to the content block.
If the value of this argument is ``True`` then a newline will be added
to the content block. If it is ``False``, then a newline will not be
added to the content block. If it is ``None`` then a newline will only
be added to the content block if it does not already end in a newline.
show_changes: ``True``
Controls how changes are presented. If ``True``, this function will
return the of the changes made.
If ``False``, then it will return a boolean (``True`` if any changes
were made, otherwise False).
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path: ``None``
Save the temporary configuration to a specific path, then read from
there. This argument is optional, can be used when you prefers a
particular location of the temporary file.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
CLI Example:
.. code-block:: bash
salt '*' net.blockreplace 'ntp' 'interface' ''
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
replace_pattern = __salt__['file.blockreplace'](path,
marker_start=marker_start,
marker_end=marker_end,
content=content,
append_if_not_found=append_if_not_found,
prepend_if_not_found=prepend_if_not_found,
show_changes=show_changes,
append_newline=append_newline)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
def patch(patchfile,
options='',
saltenv='base',
source_hash=None,
show_changes=True,
source='running',
path=None,
test=False,
commit=True,
debug=False,
replace=True):
'''
.. versionadded:: 2019.2.0
Apply a patch to the configuration source, and load the result into the
running config of the device.
patchfile
A patch file to apply to the configuration source.
options
Options to pass to patch.
source_hash
If the patch file (specified via the ``patchfile`` argument) is an
HTTP(S) or FTP URL and the file exists in the minion's file cache, this
option can be passed to keep the minion from re-downloading the file if
the cached copy matches the specified hash.
show_changes: ``True``
Controls how changes are presented. If ``True``, this function will
return the of the changes made.
If ``False``, then it will return a boolean (``True`` if any changes
were made, otherwise False).
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path: ``None``
Save the temporary configuration to a specific path, then read from
there. This argument is optional, can the user prefers a particular
location of the temporary file.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
CLI Example:
.. code-block:: bash
salt '*' net.patch https://example.com/running_config.patch
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
patchfile_cache = __salt__['cp.cache_file'](patchfile)
if patchfile_cache is False:
return {
'out': None,
'result': False,
'comment': 'The file "{}" does not exist.'.format(patchfile)
}
replace_pattern = __salt__['file.patch'](path,
patchfile_cache,
options=options)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
# <---- Configuration specific functions -------------------------------------------------------------------------------
|
saltstack/salt
|
salt/modules/napalm_network.py
|
mac
|
python
|
def mac(address='', interface='', vlan=0, **kwargs): # pylint: disable=unused-argument
'''
Returns the MAC Address Table on the device.
:param address: MAC address to filter on
:param interface: Interface name to filter on
:param vlan: VLAN identifier
:return: A list of dictionaries representing the entries in the MAC Address Table
CLI Example:
.. code-block:: bash
salt '*' net.mac
salt '*' net.mac vlan=10
Example output:
.. code-block:: python
[
{
'mac' : '00:1c:58:29:4a:71',
'interface' : 'xe-3/0/2',
'static' : False,
'active' : True,
'moves' : 1,
'vlan' : 10,
'last_move' : 1454417742.58
},
{
'mac' : '8c:60:4f:58:e1:c1',
'interface' : 'xe-1/0/1',
'static' : False,
'active' : True,
'moves' : 2,
'vlan' : 42,
'last_move' : 1453191948.11
}
]
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_mac_address_table',
**{
}
)
if not proxy_output.get('result'):
# if negative, leave the output unchanged
return proxy_output
mac_address_table = proxy_output.get('out')
if vlan and isinstance(vlan, int):
mac_address_table = _filter_list(mac_address_table, 'vlan', vlan)
if address:
mac_address_table = _filter_list(mac_address_table, 'mac', address)
if interface:
mac_address_table = _filter_list(mac_address_table, 'interface', interface)
proxy_output.update({
'out': mac_address_table
})
return proxy_output
|
Returns the MAC Address Table on the device.
:param address: MAC address to filter on
:param interface: Interface name to filter on
:param vlan: VLAN identifier
:return: A list of dictionaries representing the entries in the MAC Address Table
CLI Example:
.. code-block:: bash
salt '*' net.mac
salt '*' net.mac vlan=10
Example output:
.. code-block:: python
[
{
'mac' : '00:1c:58:29:4a:71',
'interface' : 'xe-3/0/2',
'static' : False,
'active' : True,
'moves' : 1,
'vlan' : 10,
'last_move' : 1454417742.58
},
{
'mac' : '8c:60:4f:58:e1:c1',
'interface' : 'xe-1/0/1',
'static' : False,
'active' : True,
'moves' : 2,
'vlan' : 42,
'last_move' : 1453191948.11
}
]
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_network.py#L1121-L1190
|
[
"def call(napalm_device, method, *args, **kwargs):\n '''\n Calls arbitrary methods from the network driver instance.\n Please check the readthedocs_ page for the updated list of getters.\n\n .. _readthedocs: http://napalm.readthedocs.org/en/latest/support/index.html#getters-support-matrix\n\n method\n Specifies the name of the method to be called.\n\n *args\n Arguments.\n\n **kwargs\n More arguments.\n\n :return: A dictionary with three keys:\n\n * result (True/False): if the operation succeeded\n * out (object): returns the object as-is from the call\n * comment (string): provides more details in case the call failed\n * traceback (string): complete traceback in case of exception. \\\n Please submit an issue including this traceback \\\n on the `correct driver repo`_ and make sure to read the FAQ_\n\n .. _`correct driver repo`: https://github.com/napalm-automation/napalm/issues/new\n .. FAQ_: https://github.com/napalm-automation/napalm#faq\n\n Example:\n\n .. code-block:: python\n\n salt.utils.napalm.call(\n napalm_object,\n 'cli',\n [\n 'show version',\n 'show chassis fan'\n ]\n )\n '''\n result = False\n out = None\n opts = napalm_device.get('__opts__', {})\n retry = kwargs.pop('__retry', True) # retry executing the task?\n force_reconnect = kwargs.get('force_reconnect', False)\n if force_reconnect:\n log.debug('Forced reconnection initiated')\n log.debug('The current opts (under the proxy key):')\n log.debug(opts['proxy'])\n opts['proxy'].update(**kwargs)\n log.debug('Updated to:')\n log.debug(opts['proxy'])\n napalm_device = get_device(opts)\n try:\n if not napalm_device.get('UP', False):\n raise Exception('not connected')\n # if connected will try to execute desired command\n kwargs_copy = {}\n kwargs_copy.update(kwargs)\n for karg, warg in six.iteritems(kwargs_copy):\n # lets clear None arguments\n # to not be sent to NAPALM methods\n if warg is None:\n kwargs.pop(karg)\n out = getattr(napalm_device.get('DRIVER'), method)(*args, **kwargs)\n # calls the method with the specified parameters\n result = True\n except Exception as error:\n # either not connected\n # either unable to execute the command\n hostname = napalm_device.get('HOSTNAME', '[unspecified hostname]')\n err_tb = traceback.format_exc() # let's get the full traceback and display for debugging reasons.\n if isinstance(error, NotImplementedError):\n comment = '{method} is not implemented for the NAPALM {driver} driver!'.format(\n method=method,\n driver=napalm_device.get('DRIVER_NAME')\n )\n elif retry and HAS_CONN_CLOSED_EXC_CLASS and isinstance(error, ConnectionClosedException):\n # Received disconection whilst executing the operation.\n # Instructed to retry (default behaviour)\n # thus trying to re-establish the connection\n # and re-execute the command\n # if any of the operations (close, open, call) will rise again ConnectionClosedException\n # it will fail loudly.\n kwargs['__retry'] = False # do not attempt re-executing\n comment = 'Disconnected from {device}. Trying to reconnect.'.format(device=hostname)\n log.error(err_tb)\n log.error(comment)\n log.debug('Clearing the connection with %s', hostname)\n call(napalm_device, 'close', __retry=False) # safely close the connection\n # Make sure we don't leave any TCP connection open behind\n # if we fail to close properly, we might not be able to access the\n log.debug('Re-opening the connection with %s', hostname)\n call(napalm_device, 'open', __retry=False)\n log.debug('Connection re-opened with %s', hostname)\n log.debug('Re-executing %s', method)\n return call(napalm_device, method, *args, **kwargs)\n # If still not able to reconnect and execute the task,\n # the proxy keepalive feature (if enabled) will attempt\n # to reconnect.\n # If the device is using a SSH-based connection, the failure\n # will also notify the paramiko transport and the `is_alive` flag\n # is going to be set correctly.\n # More background: the network device may decide to disconnect,\n # although the SSH session itself is alive and usable, the reason\n # being the lack of activity on the CLI.\n # Paramiko's keepalive doesn't help in this case, as the ServerAliveInterval\n # are targeting the transport layer, whilst the device takes the decision\n # when there isn't any activity on the CLI, thus at the application layer.\n # Moreover, the disconnect is silent and paramiko's is_alive flag will\n # continue to return True, although the connection is already unusable.\n # For more info, see https://github.com/paramiko/paramiko/issues/813.\n # But after a command fails, the `is_alive` flag becomes aware of these\n # changes and will return False from there on. And this is how the\n # Salt proxy keepalive helps: immediately after the first failure, it\n # will know the state of the connection and will try reconnecting.\n else:\n comment = 'Cannot execute \"{method}\" on {device}{port} as {user}. Reason: {error}!'.format(\n device=napalm_device.get('HOSTNAME', '[unspecified hostname]'),\n port=(':{port}'.format(port=napalm_device.get('OPTIONAL_ARGS', {}).get('port'))\n if napalm_device.get('OPTIONAL_ARGS', {}).get('port') else ''),\n user=napalm_device.get('USERNAME', ''),\n method=method,\n error=error\n )\n log.error(comment)\n log.error(err_tb)\n return {\n 'out': {},\n 'result': False,\n 'comment': comment,\n 'traceback': err_tb\n }\n finally:\n if opts and not_always_alive(opts) and napalm_device.get('CLOSE', True):\n # either running in a not-always-alive proxy\n # either running in a regular minion\n # close the connection when the call is over\n # unless the CLOSE is explicitly set as False\n napalm_device['DRIVER'].close()\n return {\n 'out': out,\n 'result': result,\n 'comment': ''\n }\n"
] |
# -*- coding: utf-8 -*-
'''
NAPALM Network
==============
Basic methods for interaction with the network device through the virtual proxy 'napalm'.
:codeauthor: Mircea Ulinic <mircea@cloudflare.com> & Jerome Fleury <jf@cloudflare.com>
:maturity: new
:depends: napalm
:platform: unix
Dependencies
------------
- :mod:`napalm proxy minion <salt.proxy.napalm>`
.. versionadded:: 2016.11.0
.. versionchanged:: 2017.7.0
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import time
import logging
import datetime
log = logging.getLogger(__name__)
# Import Salt libs
from salt.ext import six
import salt.utils.files
import salt.utils.napalm
import salt.utils.versions
import salt.utils.templates
# Import 3rd-party libs
try:
import jxmlease # pylint: disable=unused-import
HAS_JXMLEASE = True
except ImportError:
HAS_JXMLEASE = False
# ----------------------------------------------------------------------------------------------------------------------
# module properties
# ----------------------------------------------------------------------------------------------------------------------
__virtualname__ = 'net'
__proxyenabled__ = ['*']
__virtual_aliases__ = ('napalm_net',)
# uses NAPALM-based proxy to interact with network devices
# ----------------------------------------------------------------------------------------------------------------------
# property functions
# ----------------------------------------------------------------------------------------------------------------------
def __virtual__():
'''
NAPALM library must be installed for this module to work and run in a (proxy) minion.
'''
return salt.utils.napalm.virtual(__opts__, __virtualname__, __file__)
# ----------------------------------------------------------------------------------------------------------------------
# helper functions -- will not be exported
# ----------------------------------------------------------------------------------------------------------------------
def _filter_list(input_list, search_key, search_value):
'''
Filters a list of dictionary by a set of key-value pair.
:param input_list: is a list of dictionaries
:param search_key: is the key we are looking for
:param search_value: is the value we are looking for the key specified in search_key
:return: filered list of dictionaries
'''
output_list = list()
for dictionary in input_list:
if dictionary.get(search_key) == search_value:
output_list.append(dictionary)
return output_list
def _filter_dict(input_dict, search_key, search_value):
'''
Filters a dictionary of dictionaries by a key-value pair.
:param input_dict: is a dictionary whose values are lists of dictionaries
:param search_key: is the key in the leaf dictionaries
:param search_values: is the value in the leaf dictionaries
:return: filtered dictionary
'''
output_dict = dict()
for key, key_list in six.iteritems(input_dict):
key_list_filtered = _filter_list(key_list, search_key, search_value)
if key_list_filtered:
output_dict[key] = key_list_filtered
return output_dict
def _safe_commit_config(loaded_result, napalm_device):
_commit = commit(inherit_napalm_device=napalm_device) # calls the function commit, defined below
if not _commit.get('result', False):
# if unable to commit
loaded_result['comment'] += _commit['comment'] if _commit.get('comment') else 'Unable to commit.'
loaded_result['result'] = False
# unable to commit, something went wrong
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
return _commit
def _safe_dicard_config(loaded_result, napalm_device):
'''
'''
log.debug('Discarding the config')
log.debug(loaded_result)
_discarded = discard_config(inherit_napalm_device=napalm_device)
if not _discarded.get('result', False):
loaded_result['comment'] += _discarded['comment'] if _discarded.get('comment') \
else 'Unable to discard config.'
loaded_result['result'] = False
# make sure it notifies
# that something went wrong
_explicit_close(napalm_device)
__context__['retcode'] = 1
return loaded_result
return _discarded
def _explicit_close(napalm_device):
'''
Will explicily close the config session with the network device,
when running in a now-always-alive proxy minion or regular minion.
This helper must be used in configuration-related functions,
as the session is preserved and not closed before making any changes.
'''
if salt.utils.napalm.not_always_alive(__opts__):
# force closing the configuration session
# when running in a non-always-alive proxy
# or regular minion
try:
napalm_device['DRIVER'].close()
except Exception as err:
log.error('Unable to close the temp connection with the device:')
log.error(err)
log.error('Please report.')
def _config_logic(napalm_device,
loaded_result,
test=False,
debug=False,
replace=False,
commit_config=True,
loaded_config=None,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
commit_jid=None,
**kwargs):
'''
Builds the config logic for `load_config` and `load_template` functions.
'''
# As the Salt logic is built around independent events
# when it comes to configuration changes in the
# candidate DB on the network devices, we need to
# make sure we're using the same session.
# Hence, we need to pass the same object around.
# the napalm_device object is inherited from
# the load_config or load_template functions
# and forwarded to compare, discard, commit etc.
# then the decorator will make sure that
# if not proxy (when the connection is always alive)
# and the `inherit_napalm_device` is set,
# `napalm_device` will be overridden.
# See `salt.utils.napalm.proxy_napalm_wrap` decorator.
current_jid = kwargs.get('__pub_jid')
if not current_jid:
current_jid = '{0:%Y%m%d%H%M%S%f}'.format(datetime.datetime.now())
loaded_result['already_configured'] = False
loaded_result['loaded_config'] = ''
if debug:
loaded_result['loaded_config'] = loaded_config
_compare = compare_config(inherit_napalm_device=napalm_device)
if _compare.get('result', False):
loaded_result['diff'] = _compare.get('out')
loaded_result.pop('out', '') # not needed
else:
loaded_result['diff'] = None
loaded_result['result'] = False
loaded_result['comment'] = _compare.get('comment')
__context__['retcode'] = 1
return loaded_result
_loaded_res = loaded_result.get('result', False)
if not _loaded_res or test:
# if unable to load the config (errors / warnings)
# or in testing mode,
# will discard the config
if loaded_result['comment']:
loaded_result['comment'] += '\n'
if not loaded_result.get('diff', ''):
loaded_result['already_configured'] = True
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
loaded_result['comment'] += 'Configuration discarded.'
# loaded_result['result'] = False not necessary
# as the result can be true when test=True
_explicit_close(napalm_device)
if not loaded_result['result']:
__context__['retcode'] = 1
return loaded_result
if not test and commit_config:
# if not in testing mode and trying to commit
if commit_jid:
log.info('Committing the JID: %s', str(commit_jid))
removed = cancel_commit(commit_jid)
log.debug('Cleaned up the commit from the schedule')
log.debug(removed['comment'])
if loaded_result.get('diff', ''):
# if not testing mode
# and also the user wants to commit (default)
# and there are changes to commit
if commit_in or commit_at:
commit_time = __utils__['timeutil.get_time_at'](time_in=commit_in,
time_at=commit_in)
# schedule job
scheduled_job_name = '__napalm_commit_{}'.format(current_jid)
temp_file = salt.utils.files.mkstemp()
with salt.utils.files.fopen(temp_file, 'w') as fp_:
fp_.write(loaded_config)
scheduled = __salt__['schedule.add'](scheduled_job_name,
function='net.load_config',
job_kwargs={
'filename': temp_file,
'commit_jid': current_jid,
'replace': replace
},
once=commit_time)
log.debug('Scheduling job')
log.debug(scheduled)
saved = __salt__['schedule.save']() # ensure the schedule is
# persistent cross Minion restart
discarded = _safe_dicard_config(loaded_result, napalm_device)
# discard the changes
if not discarded['result']:
discarded['comment'] += ('Scheduled the job to be executed at {schedule_ts}, '
'but was unable to discard the config: \n').format(schedule_ts=commit_time)
return discarded
loaded_result['comment'] = ('Changes discarded for now, and scheduled commit at: {schedule_ts}.\n'
'The commit ID is: {current_jid}.\n'
'To discard this commit, you can execute: \n\n'
'salt {min_id} net.cancel_commit {current_jid}').format(schedule_ts=commit_time,
min_id=__opts__['id'],
current_jid=current_jid)
loaded_result['commit_id'] = current_jid
return loaded_result
log.debug('About to commit:')
log.debug(loaded_result['diff'])
if revert_in or revert_at:
revert_time = __utils__['timeutil.get_time_at'](time_in=revert_in,
time_at=revert_at)
if __grains__['os'] == 'junos':
if not HAS_JXMLEASE:
loaded_result['comment'] = ('This feature requires the library jxmlease to be installed.\n'
'To install, please execute: ``pip install jxmlease``.')
loaded_result['result'] = False
return loaded_result
timestamp_at = __utils__['timeutil.get_timestamp_at'](time_in=revert_in,
time_at=revert_at)
minutes = int((timestamp_at - time.time())/60)
_comm = __salt__['napalm.junos_commit'](confirm=minutes)
if not _comm['out']:
# If unable to commit confirm, should try to bail out
loaded_result['comment'] = 'Unable to commit confirm: {}'.format(_comm['message'])
loaded_result['result'] = False
# But before exiting, we must gracefully discard the config
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
else:
temp_file = salt.utils.files.mkstemp()
running_config = __salt__['net.config'](source='running')['out']['running']
with salt.utils.files.fopen(temp_file, 'w') as fp_:
fp_.write(running_config)
committed = _safe_commit_config(loaded_result, napalm_device)
if not committed['result']:
# If unable to commit, dicard the config (which is
# already done by the _safe_commit_config function), and
# return with the command and other details.
return loaded_result
scheduled_job_name = '__napalm_commit_{}'.format(current_jid)
scheduled = __salt__['schedule.add'](scheduled_job_name,
function='net.load_config',
job_kwargs={
'filename': temp_file,
'commit_jid': current_jid,
'replace': True
},
once=revert_time)
log.debug('Scheduling commit confirmed')
log.debug(scheduled)
saved = __salt__['schedule.save']()
loaded_result['comment'] = ('The commit ID is: {current_jid}.\n'
'This commit will be reverted at: {schedule_ts}, unless confirmed.\n'
'To confirm the commit and avoid reverting, you can execute:\n\n'
'salt {min_id} net.confirm_commit {current_jid}').format(schedule_ts=revert_time,
min_id=__opts__['id'],
current_jid=current_jid)
loaded_result['commit_id'] = current_jid
return loaded_result
committed = _safe_commit_config(loaded_result, napalm_device)
if not committed['result']:
return loaded_result
else:
# would like to commit, but there's no change
# need to call discard_config() to release the config DB
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
loaded_result['already_configured'] = True
loaded_result['comment'] = 'Already configured.'
_explicit_close(napalm_device)
if not loaded_result['result']:
__context__['retcode'] = 1
return loaded_result
# ----------------------------------------------------------------------------------------------------------------------
# callable functions
# ----------------------------------------------------------------------------------------------------------------------
@salt.utils.napalm.proxy_napalm_wrap
def connected(**kwargs): # pylint: disable=unused-argument
'''
Specifies if the connection to the device succeeded.
CLI Example:
.. code-block:: bash
salt '*' net.connected
'''
return {
'out': napalm_device.get('UP', False) # pylint: disable=undefined-variable
}
@salt.utils.napalm.proxy_napalm_wrap
def facts(**kwargs): # pylint: disable=unused-argument
'''
Returns characteristics of the network device.
:return: a dictionary with the following keys:
* uptime - Uptime of the device in seconds.
* vendor - Manufacturer of the device.
* model - Device model.
* hostname - Hostname of the device
* fqdn - Fqdn of the device
* os_version - String with the OS version running on the device.
* serial_number - Serial number of the device
* interface_list - List of the interfaces of the device
CLI Example:
.. code-block:: bash
salt '*' net.facts
Example output:
.. code-block:: python
{
'os_version': '13.3R6.5',
'uptime': 10117140,
'interface_list': [
'lc-0/0/0',
'pfe-0/0/0',
'pfh-0/0/0',
'xe-0/0/0',
'xe-0/0/1',
'xe-0/0/2',
'xe-0/0/3',
'gr-0/0/10',
'ip-0/0/10'
],
'vendor': 'Juniper',
'serial_number': 'JN131356FBFA',
'model': 'MX480',
'hostname': 're0.edge05.syd01',
'fqdn': 're0.edge05.syd01'
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_facts',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def environment(**kwargs): # pylint: disable=unused-argument
'''
Returns the environment of the device.
CLI Example:
.. code-block:: bash
salt '*' net.environment
Example output:
.. code-block:: python
{
'fans': {
'Bottom Rear Fan': {
'status': True
},
'Bottom Middle Fan': {
'status': True
},
'Top Middle Fan': {
'status': True
},
'Bottom Front Fan': {
'status': True
},
'Top Front Fan': {
'status': True
},
'Top Rear Fan': {
'status': True
}
},
'memory': {
'available_ram': 16349,
'used_ram': 4934
},
'temperature': {
'FPC 0 Exhaust A': {
'is_alert': False,
'temperature': 35.0,
'is_critical': False
}
},
'cpu': {
'1': {
'%usage': 19.0
},
'0': {
'%usage': 35.0
}
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_environment',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def cli(*commands, **kwargs): # pylint: disable=unused-argument
'''
Returns a dictionary with the raw output of all commands passed as arguments.
commands
List of commands to be executed on the device.
textfsm_parse: ``False``
Try parsing the outputs using the TextFSM templates.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``napalm_cli_textfsm_parse``.
textfsm_path
The path where the TextFSM templates can be found. This option implies
the usage of the TextFSM index file.
``textfsm_path`` can be either absolute path on the server,
either specified using the following URL mschemes: ``file://``,
``salt://``, ``http://``, ``https://``, ``ftp://``,
``s3://``, ``swift://``.
.. versionadded:: 2018.3.0
.. note::
This needs to be a directory with a flat structure, having an
index file (whose name can be specified using the ``index_file`` option)
and a number of TextFSM templates.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_path``.
textfsm_template
The path to a certain the TextFSM template.
This can be specified using the absolute path
to the file, or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
.. versionadded:: 2018.3.0
textfsm_template_dict
A dictionary with the mapping between a command
and the corresponding TextFSM path to use to extract the data.
The TextFSM paths can be specified as in ``textfsm_template``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``napalm_cli_textfsm_template_dict``.
platform_grain_name: ``os``
The name of the grain used to identify the platform name
in the TextFSM index file. Default: ``os``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_grain``.
platform_column_name: ``Platform``
The column name used to identify the platform,
exactly as specified in the TextFSM index file.
Default: ``Platform``.
.. versionadded:: 2018.3.0
.. note::
This is field is case sensitive, make sure
to assign the correct value to this option,
exactly as defined in the index file.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_column_name``.
index_file: ``index``
The name of the TextFSM index file, under the ``textfsm_path``. Default: ``index``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_index_file``.
saltenv: ``base``
Salt fileserver envrionment from which to retrieve the file.
Ignored if ``textfsm_path`` is not a ``salt://`` URL.
.. versionadded:: 2018.3.0
include_empty: ``False``
Include empty files under the ``textfsm_path``.
.. versionadded:: 2018.3.0
include_pat
Glob or regex to narrow down the files cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. versionadded:: 2018.3.0
exclude_pat
Glob or regex to exclude certain files from being cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. versionadded:: 2018.3.0
.. note::
If used with ``include_pat``, files matching this pattern will be
excluded from the subset of files defined by ``include_pat``.
CLI Example:
.. code-block:: bash
salt '*' net.cli "show version" "show chassis fan"
CLI Example with TextFSM template:
.. code-block:: bash
salt '*' net.cli textfsm_parse=True textfsm_path=salt://textfsm/
Example output:
.. code-block:: python
{
'show version and haiku': 'Hostname: re0.edge01.arn01
Model: mx480
Junos: 13.3R6.5
Help me, Obi-Wan
I just saw Episode Two
You're my only hope
',
'show chassis fan' : 'Item Status RPM Measurement
Top Rear Fan OK 3840 Spinning at intermediate-speed
Bottom Rear Fan OK 3840 Spinning at intermediate-speed
Top Middle Fan OK 3900 Spinning at intermediate-speed
Bottom Middle Fan OK 3840 Spinning at intermediate-speed
Top Front Fan OK 3810 Spinning at intermediate-speed
Bottom Front Fan OK 3840 Spinning at intermediate-speed
'
}
Example output with TextFSM parsing:
.. code-block:: json
{
"comment": "",
"result": true,
"out": {
"sh ver": [
{
"kernel": "9.1S3.5",
"documentation": "9.1S3.5",
"boot": "9.1S3.5",
"crypto": "9.1S3.5",
"chassis": "",
"routing": "9.1S3.5",
"base": "9.1S3.5",
"model": "mx960"
}
]
}
}
'''
raw_cli_outputs = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'cli',
**{
'commands': list(commands)
}
)
# thus we can display the output as is
# in case of errors, they'll be catched in the proxy
if not raw_cli_outputs['result']:
# Error -> dispaly the output as-is.
return raw_cli_outputs
textfsm_parse = kwargs.get('textfsm_parse') or __opts__.get('napalm_cli_textfsm_parse') or\
__pillar__.get('napalm_cli_textfsm_parse', False)
if not textfsm_parse:
# No TextFSM parsing required, return raw commands.
log.debug('No TextFSM parsing requested.')
return raw_cli_outputs
if 'textfsm.extract' not in __salt__ or 'textfsm.index' not in __salt__:
raw_cli_outputs['comment'] += 'Unable to process: is TextFSM installed?'
log.error(raw_cli_outputs['comment'])
return raw_cli_outputs
textfsm_template = kwargs.get('textfsm_template')
log.debug('textfsm_template: %s', textfsm_template)
textfsm_path = kwargs.get('textfsm_path') or __opts__.get('textfsm_path') or\
__pillar__.get('textfsm_path')
log.debug('textfsm_path: %s', textfsm_path)
textfsm_template_dict = kwargs.get('textfsm_template_dict') or __opts__.get('napalm_cli_textfsm_template_dict') or\
__pillar__.get('napalm_cli_textfsm_template_dict', {})
log.debug('TextFSM command-template mapping: %s', textfsm_template_dict)
index_file = kwargs.get('index_file') or __opts__.get('textfsm_index_file') or\
__pillar__.get('textfsm_index_file')
log.debug('index_file: %s', index_file)
platform_grain_name = kwargs.get('platform_grain_name') or __opts__.get('textfsm_platform_grain') or\
__pillar__.get('textfsm_platform_grain', 'os')
log.debug('platform_grain_name: %s', platform_grain_name)
platform_column_name = kwargs.get('platform_column_name') or __opts__.get('textfsm_platform_column_name') or\
__pillar__.get('textfsm_platform_column_name', 'Platform')
log.debug('platform_column_name: %s', platform_column_name)
saltenv = kwargs.get('saltenv', 'base')
include_empty = kwargs.get('include_empty', False)
include_pat = kwargs.get('include_pat')
exclude_pat = kwargs.get('exclude_pat')
processed_cli_outputs = {
'comment': raw_cli_outputs.get('comment', ''),
'result': raw_cli_outputs['result'],
'out': {}
}
log.debug('Starting to analyse the raw outputs')
for command in list(commands):
command_output = raw_cli_outputs['out'][command]
log.debug('Output from command: %s', command)
log.debug(command_output)
processed_command_output = None
if textfsm_path:
log.debug('Using the templates under %s', textfsm_path)
processed_cli_output = __salt__['textfsm.index'](command,
platform_grain_name=platform_grain_name,
platform_column_name=platform_column_name,
output=command_output.strip(),
textfsm_path=textfsm_path,
saltenv=saltenv,
include_empty=include_empty,
include_pat=include_pat,
exclude_pat=exclude_pat)
log.debug('Processed CLI output:')
log.debug(processed_cli_output)
if not processed_cli_output['result']:
log.debug('Apparently this didnt work, returnin the raw output')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {0}: {1}.'.format(command,
processed_cli_output['comment'])
log.error(processed_cli_outputs['comment'])
elif processed_cli_output['out']:
log.debug('All good, %s has a nice output!', command)
processed_command_output = processed_cli_output['out']
else:
comment = '''\nProcessing "{}" didn't fail, but didn't return anything either. Dumping raw.'''.format(
command)
processed_cli_outputs['comment'] += comment
log.error(comment)
processed_command_output = command_output
elif textfsm_template or command in textfsm_template_dict:
if command in textfsm_template_dict:
textfsm_template = textfsm_template_dict[command]
log.debug('Using %s to process the command: %s', textfsm_template, command)
processed_cli_output = __salt__['textfsm.extract'](textfsm_template,
raw_text=command_output,
saltenv=saltenv)
log.debug('Processed CLI output:')
log.debug(processed_cli_output)
if not processed_cli_output['result']:
log.debug('Apparently this didnt work, returning '
'the raw output')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {0}: {1}'.format(command,
processed_cli_output['comment'])
log.error(processed_cli_outputs['comment'])
elif processed_cli_output['out']:
log.debug('All good, %s has a nice output!', command)
processed_command_output = processed_cli_output['out']
else:
log.debug('Processing %s didnt fail, but didnt return'
' anything either. Dumping raw.', command)
processed_command_output = command_output
else:
log.error('No TextFSM template specified, or no TextFSM path defined')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {}.'.format(command)
processed_cli_outputs['out'][command] = processed_command_output
processed_cli_outputs['comment'] = processed_cli_outputs['comment'].strip()
return processed_cli_outputs
@salt.utils.napalm.proxy_napalm_wrap
def traceroute(destination, source=None, ttl=None, timeout=None, vrf=None, **kwargs): # pylint: disable=unused-argument
'''
Calls the method traceroute from the NAPALM driver object and returns a dictionary with the result of the traceroute
command executed on the device.
destination
Hostname or address of remote host
source
Source address to use in outgoing traceroute packets
ttl
IP maximum time-to-live value (or IPv6 maximum hop-limit value)
timeout
Number of seconds to wait for response (seconds)
vrf
VRF (routing instance) for traceroute attempt
.. versionadded:: 2016.11.4
CLI Example:
.. code-block:: bash
salt '*' net.traceroute 8.8.8.8
salt '*' net.traceroute 8.8.8.8 source=127.0.0.1 ttl=5 timeout=1
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'traceroute',
**{
'destination': destination,
'source': source,
'ttl': ttl,
'timeout': timeout,
'vrf': vrf
}
)
@salt.utils.napalm.proxy_napalm_wrap
def ping(destination, source=None, ttl=None, timeout=None, size=None, count=None, vrf=None, **kwargs): # pylint: disable=unused-argument
'''
Executes a ping on the network device and returns a dictionary as a result.
destination
Hostname or IP address of remote host
source
Source address of echo request
ttl
IP time-to-live value (IPv6 hop-limit value) (1..255 hops)
timeout
Maximum wait time after sending final packet (seconds)
size
Size of request packets (0..65468 bytes)
count
Number of ping requests to send (1..2000000000 packets)
vrf
VRF (routing instance) for ping attempt
.. versionadded:: 2016.11.4
CLI Example:
.. code-block:: bash
salt '*' net.ping 8.8.8.8
salt '*' net.ping 8.8.8.8 ttl=3 size=65468
salt '*' net.ping 8.8.8.8 source=127.0.0.1 timeout=1 count=100
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'ping',
**{
'destination': destination,
'source': source,
'ttl': ttl,
'timeout': timeout,
'size': size,
'count': count,
'vrf': vrf
}
)
@salt.utils.napalm.proxy_napalm_wrap
def arp(interface='', ipaddr='', macaddr='', **kwargs): # pylint: disable=unused-argument
'''
NAPALM returns a list of dictionaries with details of the ARP entries.
:param interface: interface name to filter on
:param ipaddr: IP address to filter on
:param macaddr: MAC address to filter on
:return: List of the entries in the ARP table
CLI Example:
.. code-block:: bash
salt '*' net.arp
salt '*' net.arp macaddr='5c:5e:ab:da:3c:f0'
Example output:
.. code-block:: python
[
{
'interface' : 'MgmtEth0/RSP0/CPU0/0',
'mac' : '5c:5e:ab:da:3c:f0',
'ip' : '172.17.17.1',
'age' : 1454496274.84
},
{
'interface': 'MgmtEth0/RSP0/CPU0/0',
'mac' : '66:0e:94:96:e0:ff',
'ip' : '172.17.17.2',
'age' : 1435641582.49
}
]
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_arp_table',
**{
}
)
if not proxy_output.get('result'):
return proxy_output
arp_table = proxy_output.get('out')
if interface:
arp_table = _filter_list(arp_table, 'interface', interface)
if ipaddr:
arp_table = _filter_list(arp_table, 'ip', ipaddr)
if macaddr:
arp_table = _filter_list(arp_table, 'mac', macaddr)
proxy_output.update({
'out': arp_table
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def ipaddrs(**kwargs): # pylint: disable=unused-argument
'''
Returns IP addresses configured on the device.
:return: A dictionary with the IPv4 and IPv6 addresses of the interfaces.
Returns all configured IP addresses on all interfaces as a dictionary
of dictionaries. Keys of the main dictionary represent the name of the
interface. Values of the main dictionary represent are dictionaries
that may consist of two keys 'ipv4' and 'ipv6' (one, both or none)
which are themselvs dictionaries with the IP addresses as keys.
CLI Example:
.. code-block:: bash
salt '*' net.ipaddrs
Example output:
.. code-block:: python
{
'FastEthernet8': {
'ipv4': {
'10.66.43.169': {
'prefix_length': 22
}
}
},
'Loopback555': {
'ipv4': {
'192.168.1.1': {
'prefix_length': 24
}
},
'ipv6': {
'1::1': {
'prefix_length': 64
},
'2001:DB8:1::1': {
'prefix_length': 64
},
'FE80::3': {
'prefix_length': 'N/A'
}
}
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_interfaces_ip',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def interfaces(**kwargs): # pylint: disable=unused-argument
'''
Returns details of the interfaces on the device.
:return: Returns a dictionary of dictionaries. The keys for the first
dictionary will be the interfaces in the devices.
CLI Example:
.. code-block:: bash
salt '*' net.interfaces
Example output:
.. code-block:: python
{
'Management1': {
'is_up': False,
'is_enabled': False,
'description': '',
'last_flapped': -1,
'speed': 1000,
'mac_address': 'dead:beef:dead',
},
'Ethernet1':{
'is_up': True,
'is_enabled': True,
'description': 'foo',
'last_flapped': 1429978575.1554043,
'speed': 1000,
'mac_address': 'beef:dead:beef',
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_interfaces',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def lldp(interface='', **kwargs): # pylint: disable=unused-argument
'''
Returns a detailed view of the LLDP neighbors.
:param interface: interface name to filter on
:return: A dictionary with the LLDL neighbors. The keys are the
interfaces with LLDP activated on.
CLI Example:
.. code-block:: bash
salt '*' net.lldp
salt '*' net.lldp interface='TenGigE0/0/0/8'
Example output:
.. code-block:: python
{
'TenGigE0/0/0/8': [
{
'parent_interface': 'Bundle-Ether8',
'interface_description': 'TenGigE0/0/0/8',
'remote_chassis_id': '8c60.4f69.e96c',
'remote_system_name': 'switch',
'remote_port': 'Eth2/2/1',
'remote_port_description': 'Ethernet2/2/1',
'remote_system_description': 'Cisco Nexus Operating System (NX-OS) Software 7.1(0)N1(1a)
TAC support: http://www.cisco.com/tac
Copyright (c) 2002-2015, Cisco Systems, Inc. All rights reserved.',
'remote_system_capab': 'B, R',
'remote_system_enable_capab': 'B'
}
]
}
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_lldp_neighbors_detail',
**{
}
)
if not proxy_output.get('result'):
return proxy_output
lldp_neighbors = proxy_output.get('out')
if interface:
lldp_neighbors = {interface: lldp_neighbors.get(interface)}
proxy_output.update({
'out': lldp_neighbors
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
@salt.utils.napalm.proxy_napalm_wrap
def config(source=None, **kwargs): # pylint: disable=unused-argument
'''
.. versionadded:: 2017.7.0
Return the whole configuration of the network device. By default, it will
return all possible configuration sources supported by the network device.
At most, there will be:
- running config
- startup config
- candidate config
To return only one of the configurations, you can use the ``source``
argument.
source
Which configuration type you want to display, default is all of them.
Options:
- running
- candidate
- startup
:return:
The object returned is a dictionary with the following keys:
- running (string): Representation of the native running configuration.
- candidate (string): Representation of the native candidate configuration.
If the device doesn't differentiate between running and startup
configuration this will an empty string.
- startup (string): Representation of the native startup configuration.
If the device doesn't differentiate between running and startup
configuration this will an empty string.
CLI Example:
.. code-block:: bash
salt '*' net.config
salt '*' net.config source=candidate
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_config',
**{
'retrieve': source
}
)
@salt.utils.napalm.proxy_napalm_wrap
def optics(**kwargs): # pylint: disable=unused-argument
'''
.. versionadded:: 2017.7.0
Fetches the power usage on the various transceivers installed
on the network device (in dBm), and returns a view that conforms with the
OpenConfig model openconfig-platform-transceiver.yang.
:return:
Returns a dictionary where the keys are as listed below:
* intf_name (unicode)
* physical_channels
* channels (list of dicts)
* index (int)
* state
* input_power
* instant (float)
* avg (float)
* min (float)
* max (float)
* output_power
* instant (float)
* avg (float)
* min (float)
* max (float)
* laser_bias_current
* instant (float)
* avg (float)
* min (float)
* max (float)
CLI Example:
.. code-block:: bash
salt '*' net.optics
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_optics',
**{
}
)
# <---- Call NAPALM getters --------------------------------------------------------------------------------------------
# ----- Configuration specific functions ------------------------------------------------------------------------------>
@salt.utils.napalm.proxy_napalm_wrap
def load_config(filename=None,
text=None,
test=False,
commit=True,
debug=False,
replace=False,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
commit_jid=None,
inherit_napalm_device=None,
saltenv='base',
**kwargs): # pylint: disable=unused-argument
'''
Applies configuration changes on the device. It can be loaded from a file or from inline string.
If you send both a filename and a string containing the configuration, the file has higher precedence.
By default this function will commit the changes. If there are no changes, it does not commit and
the flag ``already_configured`` will be set as ``True`` to point this out.
To avoid committing the configuration, set the argument ``test`` to ``True`` and will discard (dry run).
To keep the changes but not commit, set ``commit`` to ``False``.
To replace the config, set ``replace`` to ``True``.
filename
Path to the file containing the desired configuration.
This can be specified using the absolute path to the file,
or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
.. versionchanged:: 2018.3.0
text
String containing the desired configuration.
This argument is ignored when ``filename`` is specified.
test: False
Dry run? If set as ``True``, will apply the config, discard and return the changes. Default: ``False``
and will commit the changes on the device.
commit: True
Commit? Default: ``True``.
debug: False
Debug mode. Will insert a new key under the output dictionary, as ``loaded_config`` containing the raw
configuration loaded on the device.
.. versionadded:: 2016.11.2
replace: False
Load and replace the configuration. Default: ``False``.
.. versionadded:: 2016.11.2
commit_in: ``None``
Commit the changes in a specific number of minutes / hours. Example of
accepted formats: ``5`` (commit in 5 minutes), ``2m`` (commit in 2
minutes), ``1h`` (commit the changes in 1 hour)`, ``5h30m`` (commit
the changes in 5 hours and 30 minutes).
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
commit_at: ``None``
Commit the changes at a specific time. Example of accepted formats:
``1am`` (will commit the changes at the next 1AM), ``13:20`` (will
commit at 13:20), ``1:20am``, etc.
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
revert_in: ``None``
Commit and revert the changes in a specific number of minutes / hours.
Example of accepted formats: ``5`` (revert in 5 minutes), ``2m`` (revert
in 2 minutes), ``1h`` (revert the changes in 1 hour)`, ``5h30m`` (revert
the changes in 5 hours and 30 minutes).
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
revert_at: ``None``
Commit and revert the changes at a specific time. Example of accepted
formats: ``1am`` (will commit and revert the changes at the next 1AM),
``13:20`` (will commit and revert at 13:20), ``1:20am``, etc.
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
saltenv: ``base``
Specifies the Salt environment name.
.. versionadded:: 2018.3.0
:return: a dictionary having the following keys:
* result (bool): if the config was applied successfully. It is ``False`` only in case of failure. In case \
there are no changes to be applied and successfully performs all operations it is still ``True`` and so will be \
the ``already_configured`` flag (example below)
* comment (str): a message for the user
* already_configured (bool): flag to check if there were no changes applied
* loaded_config (str): the configuration loaded on the device. Requires ``debug`` to be set as ``True``
* diff (str): returns the config changes applied
CLI Example:
.. code-block:: bash
salt '*' net.load_config text='ntp peer 192.168.0.1'
salt '*' net.load_config filename='/absolute/path/to/your/file'
salt '*' net.load_config filename='/absolute/path/to/your/file' test=True
salt '*' net.load_config filename='/absolute/path/to/your/file' commit=False
Example output:
.. code-block:: python
{
'comment': 'Configuration discarded.',
'already_configured': False,
'result': True,
'diff': '[edit interfaces xe-0/0/5]+ description "Adding a description";'
}
'''
fun = 'load_merge_candidate'
if replace:
fun = 'load_replace_candidate'
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
if filename:
text = __salt__['cp.get_file_str'](filename, saltenv=saltenv)
if text is False:
# When using salt:// or https://, if the resource is not available,
# it will either raise an exception, or return False.
ret = {
'result': False,
'out': None
}
ret['comment'] = 'Unable to read from {}. Please specify a valid file or text.'.format(filename)
log.error(ret['comment'])
return ret
if commit_jid:
# When the commit_jid argument is passed, it probably is a scheduled
# commit to be executed, and filename is a temporary file which
# can be removed after reading it.
salt.utils.files.safe_rm(filename)
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
fun,
**{
'config': text
}
)
return _config_logic(napalm_device, # pylint: disable=undefined-variable
_loaded,
test=test,
debug=debug,
replace=replace,
commit_config=commit,
loaded_config=text,
commit_at=commit_at,
commit_in=commit_in,
revert_in=revert_in,
revert_at=revert_at,
commit_jid=commit_jid,
**kwargs)
@salt.utils.napalm.proxy_napalm_wrap
def load_template(template_name=None,
template_source=None,
context=None,
defaults=None,
template_engine='jinja',
saltenv='base',
template_hash=None,
template_hash_name=None,
skip_verify=False,
test=False,
commit=True,
debug=False,
replace=False,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
inherit_napalm_device=None, # pylint: disable=unused-argument
**template_vars):
'''
Renders a configuration template (default: Jinja) and loads the result on the device.
By default this function will commit the changes. If there are no changes,
it does not commit, discards he config and the flag ``already_configured``
will be set as ``True`` to point this out.
To avoid committing the configuration, set the argument ``test`` to ``True``
and will discard (dry run).
To preserve the changes, set ``commit`` to ``False``.
However, this is recommended to be used only in exceptional cases
when there are applied few consecutive states
and/or configuration changes.
Otherwise the user might forget that the config DB is locked
and the candidate config buffer is not cleared/merged in the running config.
To replace the config, set ``replace`` to ``True``.
template_name
Identifies path to the template source.
The template can be either stored on the local machine, either remotely.
The recommended location is under the ``file_roots``
as specified in the master config file.
For example, let's suppose the ``file_roots`` is configured as:
.. code-block:: yaml
file_roots:
base:
- /etc/salt/states
Placing the template under ``/etc/salt/states/templates/example.jinja``,
it can be used as ``salt://templates/example.jinja``.
Alternatively, for local files, the user can specify the absolute path.
If remotely, the source can be retrieved via ``http``, ``https`` or ``ftp``.
Examples:
- ``salt://my_template.jinja``
- ``/absolute/path/to/my_template.jinja``
- ``http://example.com/template.cheetah``
- ``https:/example.com/template.mako``
- ``ftp://example.com/template.py``
.. versionchanged:: 2019.2.0
This argument can now support a list of templates to be rendered.
The resulting configuration text is loaded at once, as a single
configuration chunk.
template_source: None
Inline config template to be rendered and loaded on the device.
template_hash: None
Hash of the template file. Format: ``{hash_type: 'md5', 'hsum': <md5sum>}``
.. versionadded:: 2016.11.2
context: None
Overrides default context variables passed to the template.
.. versionadded:: 2019.2.0
template_hash_name: None
When ``template_hash`` refers to a remote file,
this specifies the filename to look for in that file.
.. versionadded:: 2016.11.2
saltenv: ``base``
Specifies the template environment.
This will influence the relative imports inside the templates.
.. versionadded:: 2016.11.2
template_engine: jinja
The following templates engines are supported:
- :mod:`cheetah<salt.renderers.cheetah>`
- :mod:`genshi<salt.renderers.genshi>`
- :mod:`jinja<salt.renderers.jinja>`
- :mod:`mako<salt.renderers.mako>`
- :mod:`py<salt.renderers.py>`
- :mod:`wempy<salt.renderers.wempy>`
.. versionadded:: 2016.11.2
skip_verify: True
If ``True``, hash verification of remote file sources
(``http://``, ``https://``, ``ftp://``) will be skipped,
and the ``source_hash`` argument will be ignored.
.. versionadded:: 2016.11.2
test: False
Dry run? If set to ``True``, will apply the config,
discard and return the changes.
Default: ``False`` and will commit the changes on the device.
commit: True
Commit? (default: ``True``)
debug: False
Debug mode. Will insert a new key under the output dictionary,
as ``loaded_config`` containing the raw result after the template was rendered.
.. versionadded:: 2016.11.2
replace: False
Load and replace the configuration.
.. versionadded:: 2016.11.2
commit_in: ``None``
Commit the changes in a specific number of minutes / hours. Example of
accepted formats: ``5`` (commit in 5 minutes), ``2m`` (commit in 2
minutes), ``1h`` (commit the changes in 1 hour)`, ``5h30m`` (commit
the changes in 5 hours and 30 minutes).
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
commit_at: ``None``
Commit the changes at a specific time. Example of accepted formats:
``1am`` (will commit the changes at the next 1AM), ``13:20`` (will
commit at 13:20), ``1:20am``, etc.
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
revert_in: ``None``
Commit and revert the changes in a specific number of minutes / hours.
Example of accepted formats: ``5`` (revert in 5 minutes), ``2m`` (revert
in 2 minutes), ``1h`` (revert the changes in 1 hour)`, ``5h30m`` (revert
the changes in 5 hours and 30 minutes).
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
revert_at: ``None``
Commit and revert the changes at a specific time. Example of accepted
formats: ``1am`` (will commit and revert the changes at the next 1AM),
``13:20`` (will commit and revert at 13:20), ``1:20am``, etc.
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
defaults: None
Default variables/context passed to the template.
.. versionadded:: 2016.11.2
template_vars
Dictionary with the arguments/context to be used when the template is rendered.
.. note::
Do not explicitly specify this argument. This represents any other
variable that will be sent to the template rendering system.
Please see the examples below!
.. note::
It is more recommended to use the ``context`` argument to avoid
conflicts between CLI arguments and template variables.
:return: a dictionary having the following keys:
- result (bool): if the config was applied successfully. It is ``False``
only in case of failure. In case there are no changes to be applied and
successfully performs all operations it is still ``True`` and so will be
the ``already_configured`` flag (example below)
- comment (str): a message for the user
- already_configured (bool): flag to check if there were no changes applied
- loaded_config (str): the configuration loaded on the device, after
rendering the template. Requires ``debug`` to be set as ``True``
- diff (str): returns the config changes applied
The template can use variables from the ``grains``, ``pillar`` or ``opts``, for example:
.. code-block:: jinja
{% set router_model = grains.get('model') -%}
{% set router_vendor = grains.get('vendor') -%}
{% set os_version = grains.get('version') -%}
{% set hostname = pillar.get('proxy', {}).get('host') -%}
{% if router_vendor|lower == 'juniper' %}
system {
host-name {{hostname}};
}
{% elif router_vendor|lower == 'cisco' %}
hostname {{hostname}}
{% endif %}
CLI Examples:
.. code-block:: bash
salt '*' net.load_template set_ntp_peers peers=[192.168.0.1] # uses NAPALM default templates
# inline template:
salt -G 'os:junos' net.load_template template_source='system { host-name {{host_name}}; }' \
host_name='MX480.lab'
# inline template using grains info:
salt -G 'os:junos' net.load_template \
template_source='system { host-name {{grains.model}}.lab; }'
# if the device is a MX480, the command above will set the hostname as: MX480.lab
# inline template using pillar data:
salt -G 'os:junos' net.load_template template_source='system { host-name {{pillar.proxy.host}}; }'
salt '*' net.load_template https://bit.ly/2OhSgqP hostname=example # will commit
salt '*' net.load_template https://bit.ly/2OhSgqP hostname=example test=True # dry run
salt '*' net.load_template salt://templates/example.jinja debug=True # Using the salt:// URI
# render a mako template:
salt '*' net.load_template salt://templates/example.mako template_engine=mako debug=True
# render remote template
salt -G 'os:junos' net.load_template http://bit.ly/2fReJg7 test=True debug=True peers=['192.168.0.1']
salt -G 'os:ios' net.load_template http://bit.ly/2gKOj20 test=True debug=True peers=['192.168.0.1']
# render multiple templates at once
salt '*' net.load_template "['https://bit.ly/2OhSgqP', 'salt://templates/example.jinja']" context="{'hostname': 'example'}"
Example output:
.. code-block:: python
{
'comment': '',
'already_configured': False,
'result': True,
'diff': '[edit system]+ host-name edge01.bjm01',
'loaded_config': 'system { host-name edge01.bjm01; }''
}
'''
_rendered = ''
_loaded = {
'result': True,
'comment': '',
'out': None
}
loaded_config = None
# prechecks
deprecated_args = ('template_user', 'template_attrs', 'template_group', 'template_mode')
for deprecated_arg in deprecated_args:
if template_vars.get(deprecated_arg):
del template_vars[deprecated_arg]
salt.utils.versions.warn_until(
'Sodium',
('The \'{arg}\' argument to \'net.load_template\' is deprecated '
'and has been ignored').format(arg=deprecated_arg)
)
if template_engine not in salt.utils.templates.TEMPLATE_REGISTRY:
_loaded.update({
'result': False,
'comment': 'Invalid templating engine! Choose between: {tpl_eng_opts}'.format(
tpl_eng_opts=', '.join(list(salt.utils.templates.TEMPLATE_REGISTRY.keys()))
)
})
return _loaded # exit
# to check if will be rendered by salt or NAPALM
salt_render_prefixes = ('salt://', 'http://', 'https://', 'ftp://')
salt_render = False
file_exists = False
if not isinstance(template_name, (tuple, list)):
for salt_render_prefix in salt_render_prefixes:
if not salt_render:
salt_render = salt_render or template_name.startswith(salt_render_prefix)
file_exists = __salt__['file.file_exists'](template_name)
if template_source or file_exists or salt_render or isinstance(template_name, (tuple, list)):
# either inline template
# either template in a custom path
# either abs path send
# either starts with salt:// and
# then use Salt render system
if context is None:
context = {}
context.update(template_vars)
# if needed to render the template send as inline arg
if template_source:
# render the content
_rendered = __salt__['file.apply_template_on_contents'](
contents=template_source,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv
)
if not isinstance(_rendered, six.string_types):
if 'result' in _rendered:
_loaded['result'] = _rendered['result']
else:
_loaded['result'] = False
if 'comment' in _rendered:
_loaded['comment'] = _rendered['comment']
else:
_loaded['comment'] = 'Error while rendering the template.'
return _loaded
else:
# render the file - either local, either remote
if not isinstance(template_name, (list, tuple)):
template_name = [template_name]
if template_hash_name and not isinstance(template_hash_name, (list, tuple)):
template_hash_name = [template_hash_name]
elif not template_hash_name:
template_hash_name = [None] * len(template_name)
if template_hash and isinstance(template_hash, six.string_types) and not\
(template_hash.startswith('salt://') or template_hash.startswith('file://')):
# If the template hash is passed as string, and it's not a file
# (starts with the salt:// or file:// URI), then make it a list
# of 1 element (for the iteration below)
template_hash = [template_hash]
elif template_hash and isinstance(template_hash, six.string_types) and\
(template_hash.startswith('salt://') or template_hash.startswith('file://')):
# If the template hash is a file URI, then provide the same value
# for each of the templates in the list, as probably they all
# share the same hash file, otherwise the user should provide
# this as a list
template_hash = [template_hash] * len(template_name)
elif not template_hash:
template_hash = [None] * len(template_name)
for tpl_index, tpl_name in enumerate(template_name):
tpl_hash = template_hash[tpl_index]
tpl_hash_name = template_hash_name[tpl_index]
_rand_filename = __salt__['random.hash'](tpl_name, 'md5')
_temp_file = __salt__['file.join']('/tmp', _rand_filename)
_managed = __salt__['file.get_managed'](name=_temp_file,
source=tpl_name,
source_hash=tpl_hash,
source_hash_name=tpl_hash_name,
user=None,
group=None,
mode=None,
attrs=None,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv,
skip_verify=skip_verify)
if not isinstance(_managed, (list, tuple)) and isinstance(_managed, six.string_types):
_loaded['comment'] += _managed
_loaded['result'] = False
elif isinstance(_managed, (list, tuple)) and not _managed:
_loaded['result'] = False
_loaded['comment'] += 'Error while rendering the template.'
elif isinstance(_managed, (list, tuple)) and not _managed[0]:
_loaded['result'] = False
_loaded['comment'] += _managed[-1] # contains the error message
if _loaded['result']: # all good
_temp_tpl_file = _managed[0]
_temp_tpl_file_exists = __salt__['file.file_exists'](_temp_tpl_file)
if not _temp_tpl_file_exists:
_loaded['result'] = False
_loaded['comment'] += 'Error while rendering the template.'
return _loaded
_rendered += __salt__['file.read'](_temp_tpl_file)
__salt__['file.remove'](_temp_tpl_file)
else:
return _loaded # exit
loaded_config = _rendered
if _loaded['result']: # all good
fun = 'load_merge_candidate'
if replace: # replace requested
fun = 'load_replace_candidate'
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
fun,
**{
'config': _rendered
}
)
else:
salt.utils.versions.warn_until(
'Sodium',
'Native NAPALM templates support will be removed in the Sodium '
'release. Please consider using the Salt rendering pipeline instead.'
'If you are using the \'netntp\', \'netsnmp\', or \'netusers\' Salt '
'State modules, you can ignore this message'
)
# otherwise, use NAPALM render system, injecting pillar/grains/opts vars
load_templates_params = defaults if defaults else {}
load_templates_params.update(template_vars)
load_templates_params.update(
{
'template_name': template_name,
'template_source': template_source, # inline template
'pillar': __pillar__, # inject pillar content
'grains': __grains__, # inject grains content
'opts': __opts__ # inject opts content
}
)
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
# so we'll set the CLOSE global explicitly as False
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'load_template',
**load_templates_params
)
return _config_logic(napalm_device, # pylint: disable=undefined-variable
_loaded,
test=test,
debug=debug,
replace=replace,
commit_config=commit,
loaded_config=loaded_config,
commit_at=commit_at,
commit_in=commit_in,
revert_in=revert_in,
revert_at=revert_at,
**template_vars)
@salt.utils.napalm.proxy_napalm_wrap
def commit(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Commits the configuration changes made on the network device.
CLI Example:
.. code-block:: bash
salt '*' net.commit
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'commit_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def discard_config(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
"""
Discards the changes applied.
CLI Example:
.. code-block:: bash
salt '*' net.discard_config
"""
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'discard_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def compare_config(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Returns the difference between the running config and the candidate config.
CLI Example:
.. code-block:: bash
salt '*' net.compare_config
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'compare_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def rollback(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Rollbacks the configuration.
CLI Example:
.. code-block:: bash
salt '*' net.rollback
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'rollback',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def config_changed(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Will prompt if the configuration has been changed.
:return: A tuple with a boolean that specifies if the config was changed on the device.\
And a string that provides more details of the reason why the configuration was not changed.
CLI Example:
.. code-block:: bash
salt '*' net.config_changed
'''
is_config_changed = False
reason = ''
try_compare = compare_config(inherit_napalm_device=napalm_device) # pylint: disable=undefined-variable
if try_compare.get('result'):
if try_compare.get('out'):
is_config_changed = True
else:
reason = 'Configuration was not changed on the device.'
else:
reason = try_compare.get('comment')
return is_config_changed, reason
@salt.utils.napalm.proxy_napalm_wrap
def config_control(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Will check if the configuration was changed.
If differences found, will try to commit.
In case commit unsuccessful, will try to rollback.
:return: A tuple with a boolean that specifies if the config was changed/committed/rollbacked on the device.\
And a string that provides more details of the reason why the configuration was not committed properly.
CLI Example:
.. code-block:: bash
salt '*' net.config_control
'''
result = True
comment = ''
changed, not_changed_rsn = config_changed(inherit_napalm_device=napalm_device) # pylint: disable=undefined-variable
if not changed:
return (changed, not_changed_rsn)
# config changed, thus let's try to commit
try_commit = commit()
if not try_commit.get('result'):
result = False
comment = 'Unable to commit the changes: {reason}.\n\
Will try to rollback now!'.format(
reason=try_commit.get('comment')
)
try_rollback = rollback()
if not try_rollback.get('result'):
comment += '\nCannot rollback! {reason}'.format(
reason=try_rollback.get('comment')
)
return result, comment
def cancel_commit(jid):
'''
.. versionadded:: 2019.2.0
Cancel a commit scheduled to be executed via the ``commit_in`` and
``commit_at`` arguments from the
:py:func:`net.load_template <salt.modules.napalm_network.load_template>` or
:py:func:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit ID is displayed when the commit is scheduled
via the functions named above.
CLI Example:
.. code-block:: bash
salt '*' net.cancel_commit 20180726083540640360
'''
job_name = '__napalm_commit_{}'.format(jid)
removed = __salt__['schedule.delete'](job_name)
if removed['result']:
saved = __salt__['schedule.save']()
removed['comment'] = 'Commit #{jid} cancelled.'.format(jid=jid)
else:
removed['comment'] = 'Unable to find commit #{jid}.'.format(jid=jid)
return removed
def confirm_commit(jid):
'''
.. versionadded:: 2019.2.0
Confirm a commit scheduled to be reverted via the ``revert_in`` and
``revert_at`` arguments from the
:mod:`net.load_template <salt.modules.napalm_network.load_template>` or
:mod:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit ID is displayed when the commit confirmed
is scheduled via the functions named above.
CLI Example:
.. code-block:: bash
salt '*' net.confirm_commit 20180726083540640360
'''
if __grains__['os'] == 'junos':
# Confirm the commit, by committing (i.e., invoking the RPC call)
confirmed = __salt__['napalm.junos_commit']()
confirmed['result'] = confirmed.pop('out')
confirmed['comment'] = confirmed.pop('message')
else:
confirmed = cancel_commit(jid)
if confirmed['result']:
confirmed['comment'] = 'Commit #{jid} confirmed.'.format(jid=jid)
return confirmed
def save_config(source=None,
path=None):
'''
.. versionadded:: 2019.2.0
Save the configuration to a file on the local file system.
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``,
``startup``. Default: ``running``.
path
Absolute path to file where to save the configuration.
To push the files to the Master, use
:mod:`cp.push <salt.modules.cp.push>` Execution function.
CLI Example:
.. code-block:: bash
salt '*' net.save_config source=running
'''
if not source:
source = 'running'
if not path:
path = salt.utils.files.mkstemp()
running_config = __salt__['net.config'](source=source)
if not running_config or not running_config['result']:
log.error('Unable to retrieve the config')
return running_config
with salt.utils.files.fopen(path, 'w') as fh_:
fh_.write(running_config['out'][source])
return {
'result': True,
'out': path,
'comment': '{source} config saved to {path}'.format(source=source, path=path)
}
def replace_pattern(pattern,
repl,
count=0,
flags=8,
bufsize=1,
append_if_not_found=False,
prepend_if_not_found=False,
not_found_content=None,
search_only=False,
show_changes=True,
backslash_literal=False,
source=None,
path=None,
test=False,
replace=True,
debug=False,
commit=True):
'''
.. versionadded:: 2019.2.0
Replace occurrences of a pattern in the configuration source. If
``show_changes`` is ``True``, then a diff of what changed will be returned,
otherwise a ``True`` will be returned when changes are made, and ``False``
when no changes are made.
This is a pure Python implementation that wraps Python's :py:func:`~re.sub`.
pattern
A regular expression, to be matched using Python's
:py:func:`~re.search`.
repl
The replacement text.
count: ``0``
Maximum number of pattern occurrences to be replaced. If count is a
positive integer ``n``, only ``n`` occurrences will be replaced,
otherwise all occurrences will be replaced.
flags (list or int): ``8``
A list of flags defined in the ``re`` module documentation from the
Python standard library. Each list item should be a string that will
correlate to the human-friendly flag name. E.g., ``['IGNORECASE',
'MULTILINE']``. Optionally, ``flags`` may be an int, with a value
corresponding to the XOR (``|``) of all the desired flags. Defaults to
8 (which supports 'MULTILINE').
bufsize (int or str): ``1``
How much of the configuration to buffer into memory at once. The
default value ``1`` processes one line at a time. The special value
``file`` may be specified which will read the entire file into memory
before processing.
append_if_not_found: ``False``
If set to ``True``, and pattern is not found, then the content will be
appended to the file.
prepend_if_not_found: ``False``
If set to ``True`` and pattern is not found, then the content will be
prepended to the file.
not_found_content
Content to use for append/prepend if not found. If None (default), uses
``repl``. Useful when ``repl`` uses references to group in pattern.
search_only: ``False``
If set to true, this no changes will be performed on the file, and this
function will simply return ``True`` if the pattern was matched, and
``False`` if not.
show_changes: ``True``
If ``True``, return a diff of changes made. Otherwise, return ``True``
if changes were made, and ``False`` if not.
backslash_literal: ``False``
Interpret backslashes as literal backslashes for the repl and not
escape characters. This will help when using append/prepend so that
the backslashes are not interpreted for the repl on the second run of
the state.
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path
Save the temporary configuration to a specific path, then read from
there.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' net.replace_pattern "bind-address\\s*=" "bind-address:"
CLI Example:
.. code-block:: bash
salt '*' net.replace_pattern PREFIX-LIST_NAME new-prefix-list-name
salt '*' net.replace_pattern bgp-group-name new-bgp-group-name count=1
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
replace_pattern = __salt__['file.replace'](path,
pattern,
repl,
count=count,
flags=flags,
bufsize=bufsize,
append_if_not_found=append_if_not_found,
prepend_if_not_found=prepend_if_not_found,
not_found_content=not_found_content,
search_only=search_only,
show_changes=show_changes,
backslash_literal=backslash_literal)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
def blockreplace(marker_start,
marker_end,
content='',
append_if_not_found=False,
prepend_if_not_found=False,
show_changes=True,
append_newline=False,
source='running',
path=None,
test=False,
commit=True,
debug=False,
replace=True):
'''
.. versionadded:: 2019.2.0
Replace content of the configuration source, delimited by the line markers.
A block of content delimited by comments can help you manage several lines
without worrying about old entries removal.
marker_start
The line content identifying a line as the start of the content block.
Note that the whole line containing this marker will be considered,
so whitespace or extra content before or after the marker is included
in final output.
marker_end
The line content identifying a line as the end of the content block.
Note that the whole line containing this marker will be considered,
so whitespace or extra content before or after the marker is included
in final output.
content
The content to be used between the two lines identified by
``marker_start`` and ``marker_stop``.
append_if_not_found: ``False``
If markers are not found and set to True then, the markers and content
will be appended to the file.
prepend_if_not_found: ``False``
If markers are not found and set to True then, the markers and content
will be prepended to the file.
append_newline: ``False``
Controls whether or not a newline is appended to the content block.
If the value of this argument is ``True`` then a newline will be added
to the content block. If it is ``False``, then a newline will not be
added to the content block. If it is ``None`` then a newline will only
be added to the content block if it does not already end in a newline.
show_changes: ``True``
Controls how changes are presented. If ``True``, this function will
return the of the changes made.
If ``False``, then it will return a boolean (``True`` if any changes
were made, otherwise False).
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path: ``None``
Save the temporary configuration to a specific path, then read from
there. This argument is optional, can be used when you prefers a
particular location of the temporary file.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
CLI Example:
.. code-block:: bash
salt '*' net.blockreplace 'ntp' 'interface' ''
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
replace_pattern = __salt__['file.blockreplace'](path,
marker_start=marker_start,
marker_end=marker_end,
content=content,
append_if_not_found=append_if_not_found,
prepend_if_not_found=prepend_if_not_found,
show_changes=show_changes,
append_newline=append_newline)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
def patch(patchfile,
options='',
saltenv='base',
source_hash=None,
show_changes=True,
source='running',
path=None,
test=False,
commit=True,
debug=False,
replace=True):
'''
.. versionadded:: 2019.2.0
Apply a patch to the configuration source, and load the result into the
running config of the device.
patchfile
A patch file to apply to the configuration source.
options
Options to pass to patch.
source_hash
If the patch file (specified via the ``patchfile`` argument) is an
HTTP(S) or FTP URL and the file exists in the minion's file cache, this
option can be passed to keep the minion from re-downloading the file if
the cached copy matches the specified hash.
show_changes: ``True``
Controls how changes are presented. If ``True``, this function will
return the of the changes made.
If ``False``, then it will return a boolean (``True`` if any changes
were made, otherwise False).
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path: ``None``
Save the temporary configuration to a specific path, then read from
there. This argument is optional, can the user prefers a particular
location of the temporary file.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
CLI Example:
.. code-block:: bash
salt '*' net.patch https://example.com/running_config.patch
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
patchfile_cache = __salt__['cp.cache_file'](patchfile)
if patchfile_cache is False:
return {
'out': None,
'result': False,
'comment': 'The file "{}" does not exist.'.format(patchfile)
}
replace_pattern = __salt__['file.patch'](path,
patchfile_cache,
options=options)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
# <---- Configuration specific functions -------------------------------------------------------------------------------
|
saltstack/salt
|
salt/modules/napalm_network.py
|
load_config
|
python
|
def load_config(filename=None,
text=None,
test=False,
commit=True,
debug=False,
replace=False,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
commit_jid=None,
inherit_napalm_device=None,
saltenv='base',
**kwargs): # pylint: disable=unused-argument
'''
Applies configuration changes on the device. It can be loaded from a file or from inline string.
If you send both a filename and a string containing the configuration, the file has higher precedence.
By default this function will commit the changes. If there are no changes, it does not commit and
the flag ``already_configured`` will be set as ``True`` to point this out.
To avoid committing the configuration, set the argument ``test`` to ``True`` and will discard (dry run).
To keep the changes but not commit, set ``commit`` to ``False``.
To replace the config, set ``replace`` to ``True``.
filename
Path to the file containing the desired configuration.
This can be specified using the absolute path to the file,
or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
.. versionchanged:: 2018.3.0
text
String containing the desired configuration.
This argument is ignored when ``filename`` is specified.
test: False
Dry run? If set as ``True``, will apply the config, discard and return the changes. Default: ``False``
and will commit the changes on the device.
commit: True
Commit? Default: ``True``.
debug: False
Debug mode. Will insert a new key under the output dictionary, as ``loaded_config`` containing the raw
configuration loaded on the device.
.. versionadded:: 2016.11.2
replace: False
Load and replace the configuration. Default: ``False``.
.. versionadded:: 2016.11.2
commit_in: ``None``
Commit the changes in a specific number of minutes / hours. Example of
accepted formats: ``5`` (commit in 5 minutes), ``2m`` (commit in 2
minutes), ``1h`` (commit the changes in 1 hour)`, ``5h30m`` (commit
the changes in 5 hours and 30 minutes).
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
commit_at: ``None``
Commit the changes at a specific time. Example of accepted formats:
``1am`` (will commit the changes at the next 1AM), ``13:20`` (will
commit at 13:20), ``1:20am``, etc.
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
revert_in: ``None``
Commit and revert the changes in a specific number of minutes / hours.
Example of accepted formats: ``5`` (revert in 5 minutes), ``2m`` (revert
in 2 minutes), ``1h`` (revert the changes in 1 hour)`, ``5h30m`` (revert
the changes in 5 hours and 30 minutes).
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
revert_at: ``None``
Commit and revert the changes at a specific time. Example of accepted
formats: ``1am`` (will commit and revert the changes at the next 1AM),
``13:20`` (will commit and revert at 13:20), ``1:20am``, etc.
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
saltenv: ``base``
Specifies the Salt environment name.
.. versionadded:: 2018.3.0
:return: a dictionary having the following keys:
* result (bool): if the config was applied successfully. It is ``False`` only in case of failure. In case \
there are no changes to be applied and successfully performs all operations it is still ``True`` and so will be \
the ``already_configured`` flag (example below)
* comment (str): a message for the user
* already_configured (bool): flag to check if there were no changes applied
* loaded_config (str): the configuration loaded on the device. Requires ``debug`` to be set as ``True``
* diff (str): returns the config changes applied
CLI Example:
.. code-block:: bash
salt '*' net.load_config text='ntp peer 192.168.0.1'
salt '*' net.load_config filename='/absolute/path/to/your/file'
salt '*' net.load_config filename='/absolute/path/to/your/file' test=True
salt '*' net.load_config filename='/absolute/path/to/your/file' commit=False
Example output:
.. code-block:: python
{
'comment': 'Configuration discarded.',
'already_configured': False,
'result': True,
'diff': '[edit interfaces xe-0/0/5]+ description "Adding a description";'
}
'''
fun = 'load_merge_candidate'
if replace:
fun = 'load_replace_candidate'
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
if filename:
text = __salt__['cp.get_file_str'](filename, saltenv=saltenv)
if text is False:
# When using salt:// or https://, if the resource is not available,
# it will either raise an exception, or return False.
ret = {
'result': False,
'out': None
}
ret['comment'] = 'Unable to read from {}. Please specify a valid file or text.'.format(filename)
log.error(ret['comment'])
return ret
if commit_jid:
# When the commit_jid argument is passed, it probably is a scheduled
# commit to be executed, and filename is a temporary file which
# can be removed after reading it.
salt.utils.files.safe_rm(filename)
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
fun,
**{
'config': text
}
)
return _config_logic(napalm_device, # pylint: disable=undefined-variable
_loaded,
test=test,
debug=debug,
replace=replace,
commit_config=commit,
loaded_config=text,
commit_at=commit_at,
commit_in=commit_in,
revert_in=revert_in,
revert_at=revert_at,
commit_jid=commit_jid,
**kwargs)
|
Applies configuration changes on the device. It can be loaded from a file or from inline string.
If you send both a filename and a string containing the configuration, the file has higher precedence.
By default this function will commit the changes. If there are no changes, it does not commit and
the flag ``already_configured`` will be set as ``True`` to point this out.
To avoid committing the configuration, set the argument ``test`` to ``True`` and will discard (dry run).
To keep the changes but not commit, set ``commit`` to ``False``.
To replace the config, set ``replace`` to ``True``.
filename
Path to the file containing the desired configuration.
This can be specified using the absolute path to the file,
or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
.. versionchanged:: 2018.3.0
text
String containing the desired configuration.
This argument is ignored when ``filename`` is specified.
test: False
Dry run? If set as ``True``, will apply the config, discard and return the changes. Default: ``False``
and will commit the changes on the device.
commit: True
Commit? Default: ``True``.
debug: False
Debug mode. Will insert a new key under the output dictionary, as ``loaded_config`` containing the raw
configuration loaded on the device.
.. versionadded:: 2016.11.2
replace: False
Load and replace the configuration. Default: ``False``.
.. versionadded:: 2016.11.2
commit_in: ``None``
Commit the changes in a specific number of minutes / hours. Example of
accepted formats: ``5`` (commit in 5 minutes), ``2m`` (commit in 2
minutes), ``1h`` (commit the changes in 1 hour)`, ``5h30m`` (commit
the changes in 5 hours and 30 minutes).
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
commit_at: ``None``
Commit the changes at a specific time. Example of accepted formats:
``1am`` (will commit the changes at the next 1AM), ``13:20`` (will
commit at 13:20), ``1:20am``, etc.
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
revert_in: ``None``
Commit and revert the changes in a specific number of minutes / hours.
Example of accepted formats: ``5`` (revert in 5 minutes), ``2m`` (revert
in 2 minutes), ``1h`` (revert the changes in 1 hour)`, ``5h30m`` (revert
the changes in 5 hours and 30 minutes).
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
revert_at: ``None``
Commit and revert the changes at a specific time. Example of accepted
formats: ``1am`` (will commit and revert the changes at the next 1AM),
``13:20`` (will commit and revert at 13:20), ``1:20am``, etc.
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
saltenv: ``base``
Specifies the Salt environment name.
.. versionadded:: 2018.3.0
:return: a dictionary having the following keys:
* result (bool): if the config was applied successfully. It is ``False`` only in case of failure. In case \
there are no changes to be applied and successfully performs all operations it is still ``True`` and so will be \
the ``already_configured`` flag (example below)
* comment (str): a message for the user
* already_configured (bool): flag to check if there were no changes applied
* loaded_config (str): the configuration loaded on the device. Requires ``debug`` to be set as ``True``
* diff (str): returns the config changes applied
CLI Example:
.. code-block:: bash
salt '*' net.load_config text='ntp peer 192.168.0.1'
salt '*' net.load_config filename='/absolute/path/to/your/file'
salt '*' net.load_config filename='/absolute/path/to/your/file' test=True
salt '*' net.load_config filename='/absolute/path/to/your/file' commit=False
Example output:
.. code-block:: python
{
'comment': 'Configuration discarded.',
'already_configured': False,
'result': True,
'diff': '[edit interfaces xe-0/0/5]+ description "Adding a description";'
}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_network.py#L1296-L1551
|
[
"def call(napalm_device, method, *args, **kwargs):\n '''\n Calls arbitrary methods from the network driver instance.\n Please check the readthedocs_ page for the updated list of getters.\n\n .. _readthedocs: http://napalm.readthedocs.org/en/latest/support/index.html#getters-support-matrix\n\n method\n Specifies the name of the method to be called.\n\n *args\n Arguments.\n\n **kwargs\n More arguments.\n\n :return: A dictionary with three keys:\n\n * result (True/False): if the operation succeeded\n * out (object): returns the object as-is from the call\n * comment (string): provides more details in case the call failed\n * traceback (string): complete traceback in case of exception. \\\n Please submit an issue including this traceback \\\n on the `correct driver repo`_ and make sure to read the FAQ_\n\n .. _`correct driver repo`: https://github.com/napalm-automation/napalm/issues/new\n .. FAQ_: https://github.com/napalm-automation/napalm#faq\n\n Example:\n\n .. code-block:: python\n\n salt.utils.napalm.call(\n napalm_object,\n 'cli',\n [\n 'show version',\n 'show chassis fan'\n ]\n )\n '''\n result = False\n out = None\n opts = napalm_device.get('__opts__', {})\n retry = kwargs.pop('__retry', True) # retry executing the task?\n force_reconnect = kwargs.get('force_reconnect', False)\n if force_reconnect:\n log.debug('Forced reconnection initiated')\n log.debug('The current opts (under the proxy key):')\n log.debug(opts['proxy'])\n opts['proxy'].update(**kwargs)\n log.debug('Updated to:')\n log.debug(opts['proxy'])\n napalm_device = get_device(opts)\n try:\n if not napalm_device.get('UP', False):\n raise Exception('not connected')\n # if connected will try to execute desired command\n kwargs_copy = {}\n kwargs_copy.update(kwargs)\n for karg, warg in six.iteritems(kwargs_copy):\n # lets clear None arguments\n # to not be sent to NAPALM methods\n if warg is None:\n kwargs.pop(karg)\n out = getattr(napalm_device.get('DRIVER'), method)(*args, **kwargs)\n # calls the method with the specified parameters\n result = True\n except Exception as error:\n # either not connected\n # either unable to execute the command\n hostname = napalm_device.get('HOSTNAME', '[unspecified hostname]')\n err_tb = traceback.format_exc() # let's get the full traceback and display for debugging reasons.\n if isinstance(error, NotImplementedError):\n comment = '{method} is not implemented for the NAPALM {driver} driver!'.format(\n method=method,\n driver=napalm_device.get('DRIVER_NAME')\n )\n elif retry and HAS_CONN_CLOSED_EXC_CLASS and isinstance(error, ConnectionClosedException):\n # Received disconection whilst executing the operation.\n # Instructed to retry (default behaviour)\n # thus trying to re-establish the connection\n # and re-execute the command\n # if any of the operations (close, open, call) will rise again ConnectionClosedException\n # it will fail loudly.\n kwargs['__retry'] = False # do not attempt re-executing\n comment = 'Disconnected from {device}. Trying to reconnect.'.format(device=hostname)\n log.error(err_tb)\n log.error(comment)\n log.debug('Clearing the connection with %s', hostname)\n call(napalm_device, 'close', __retry=False) # safely close the connection\n # Make sure we don't leave any TCP connection open behind\n # if we fail to close properly, we might not be able to access the\n log.debug('Re-opening the connection with %s', hostname)\n call(napalm_device, 'open', __retry=False)\n log.debug('Connection re-opened with %s', hostname)\n log.debug('Re-executing %s', method)\n return call(napalm_device, method, *args, **kwargs)\n # If still not able to reconnect and execute the task,\n # the proxy keepalive feature (if enabled) will attempt\n # to reconnect.\n # If the device is using a SSH-based connection, the failure\n # will also notify the paramiko transport and the `is_alive` flag\n # is going to be set correctly.\n # More background: the network device may decide to disconnect,\n # although the SSH session itself is alive and usable, the reason\n # being the lack of activity on the CLI.\n # Paramiko's keepalive doesn't help in this case, as the ServerAliveInterval\n # are targeting the transport layer, whilst the device takes the decision\n # when there isn't any activity on the CLI, thus at the application layer.\n # Moreover, the disconnect is silent and paramiko's is_alive flag will\n # continue to return True, although the connection is already unusable.\n # For more info, see https://github.com/paramiko/paramiko/issues/813.\n # But after a command fails, the `is_alive` flag becomes aware of these\n # changes and will return False from there on. And this is how the\n # Salt proxy keepalive helps: immediately after the first failure, it\n # will know the state of the connection and will try reconnecting.\n else:\n comment = 'Cannot execute \"{method}\" on {device}{port} as {user}. Reason: {error}!'.format(\n device=napalm_device.get('HOSTNAME', '[unspecified hostname]'),\n port=(':{port}'.format(port=napalm_device.get('OPTIONAL_ARGS', {}).get('port'))\n if napalm_device.get('OPTIONAL_ARGS', {}).get('port') else ''),\n user=napalm_device.get('USERNAME', ''),\n method=method,\n error=error\n )\n log.error(comment)\n log.error(err_tb)\n return {\n 'out': {},\n 'result': False,\n 'comment': comment,\n 'traceback': err_tb\n }\n finally:\n if opts and not_always_alive(opts) and napalm_device.get('CLOSE', True):\n # either running in a not-always-alive proxy\n # either running in a regular minion\n # close the connection when the call is over\n # unless the CLOSE is explicitly set as False\n napalm_device['DRIVER'].close()\n return {\n 'out': out,\n 'result': result,\n 'comment': ''\n }\n",
"def safe_rm(tgt):\n '''\n Safely remove a file\n '''\n try:\n os.remove(tgt)\n except (IOError, OSError):\n pass\n",
"def not_always_alive(opts):\n '''\n Should this proxy be always alive?\n '''\n return (is_proxy(opts) and not is_always_alive(opts)) or is_minion(opts)\n",
"def _config_logic(napalm_device,\n loaded_result,\n test=False,\n debug=False,\n replace=False,\n commit_config=True,\n loaded_config=None,\n commit_in=None,\n commit_at=None,\n revert_in=None,\n revert_at=None,\n commit_jid=None,\n **kwargs):\n '''\n Builds the config logic for `load_config` and `load_template` functions.\n '''\n # As the Salt logic is built around independent events\n # when it comes to configuration changes in the\n # candidate DB on the network devices, we need to\n # make sure we're using the same session.\n # Hence, we need to pass the same object around.\n # the napalm_device object is inherited from\n # the load_config or load_template functions\n # and forwarded to compare, discard, commit etc.\n # then the decorator will make sure that\n # if not proxy (when the connection is always alive)\n # and the `inherit_napalm_device` is set,\n # `napalm_device` will be overridden.\n # See `salt.utils.napalm.proxy_napalm_wrap` decorator.\n\n current_jid = kwargs.get('__pub_jid')\n if not current_jid:\n current_jid = '{0:%Y%m%d%H%M%S%f}'.format(datetime.datetime.now())\n\n loaded_result['already_configured'] = False\n\n loaded_result['loaded_config'] = ''\n if debug:\n loaded_result['loaded_config'] = loaded_config\n\n _compare = compare_config(inherit_napalm_device=napalm_device)\n if _compare.get('result', False):\n loaded_result['diff'] = _compare.get('out')\n loaded_result.pop('out', '') # not needed\n else:\n loaded_result['diff'] = None\n loaded_result['result'] = False\n loaded_result['comment'] = _compare.get('comment')\n __context__['retcode'] = 1\n return loaded_result\n\n _loaded_res = loaded_result.get('result', False)\n if not _loaded_res or test:\n # if unable to load the config (errors / warnings)\n # or in testing mode,\n # will discard the config\n if loaded_result['comment']:\n loaded_result['comment'] += '\\n'\n if not loaded_result.get('diff', ''):\n loaded_result['already_configured'] = True\n discarded = _safe_dicard_config(loaded_result, napalm_device)\n if not discarded['result']:\n return loaded_result\n loaded_result['comment'] += 'Configuration discarded.'\n # loaded_result['result'] = False not necessary\n # as the result can be true when test=True\n _explicit_close(napalm_device)\n if not loaded_result['result']:\n __context__['retcode'] = 1\n return loaded_result\n\n if not test and commit_config:\n # if not in testing mode and trying to commit\n if commit_jid:\n log.info('Committing the JID: %s', str(commit_jid))\n removed = cancel_commit(commit_jid)\n log.debug('Cleaned up the commit from the schedule')\n log.debug(removed['comment'])\n if loaded_result.get('diff', ''):\n # if not testing mode\n # and also the user wants to commit (default)\n # and there are changes to commit\n if commit_in or commit_at:\n commit_time = __utils__['timeutil.get_time_at'](time_in=commit_in,\n time_at=commit_in)\n # schedule job\n scheduled_job_name = '__napalm_commit_{}'.format(current_jid)\n temp_file = salt.utils.files.mkstemp()\n with salt.utils.files.fopen(temp_file, 'w') as fp_:\n fp_.write(loaded_config)\n scheduled = __salt__['schedule.add'](scheduled_job_name,\n function='net.load_config',\n job_kwargs={\n 'filename': temp_file,\n 'commit_jid': current_jid,\n 'replace': replace\n },\n once=commit_time)\n log.debug('Scheduling job')\n log.debug(scheduled)\n saved = __salt__['schedule.save']() # ensure the schedule is\n # persistent cross Minion restart\n discarded = _safe_dicard_config(loaded_result, napalm_device)\n # discard the changes\n if not discarded['result']:\n discarded['comment'] += ('Scheduled the job to be executed at {schedule_ts}, '\n 'but was unable to discard the config: \\n').format(schedule_ts=commit_time)\n return discarded\n loaded_result['comment'] = ('Changes discarded for now, and scheduled commit at: {schedule_ts}.\\n'\n 'The commit ID is: {current_jid}.\\n'\n 'To discard this commit, you can execute: \\n\\n'\n 'salt {min_id} net.cancel_commit {current_jid}').format(schedule_ts=commit_time,\n min_id=__opts__['id'],\n current_jid=current_jid)\n loaded_result['commit_id'] = current_jid\n return loaded_result\n log.debug('About to commit:')\n log.debug(loaded_result['diff'])\n if revert_in or revert_at:\n revert_time = __utils__['timeutil.get_time_at'](time_in=revert_in,\n time_at=revert_at)\n if __grains__['os'] == 'junos':\n if not HAS_JXMLEASE:\n loaded_result['comment'] = ('This feature requires the library jxmlease to be installed.\\n'\n 'To install, please execute: ``pip install jxmlease``.')\n loaded_result['result'] = False\n return loaded_result\n timestamp_at = __utils__['timeutil.get_timestamp_at'](time_in=revert_in,\n time_at=revert_at)\n minutes = int((timestamp_at - time.time())/60)\n _comm = __salt__['napalm.junos_commit'](confirm=minutes)\n if not _comm['out']:\n # If unable to commit confirm, should try to bail out\n loaded_result['comment'] = 'Unable to commit confirm: {}'.format(_comm['message'])\n loaded_result['result'] = False\n # But before exiting, we must gracefully discard the config\n discarded = _safe_dicard_config(loaded_result, napalm_device)\n if not discarded['result']:\n return loaded_result\n else:\n temp_file = salt.utils.files.mkstemp()\n running_config = __salt__['net.config'](source='running')['out']['running']\n with salt.utils.files.fopen(temp_file, 'w') as fp_:\n fp_.write(running_config)\n committed = _safe_commit_config(loaded_result, napalm_device)\n if not committed['result']:\n # If unable to commit, dicard the config (which is\n # already done by the _safe_commit_config function), and\n # return with the command and other details.\n return loaded_result\n scheduled_job_name = '__napalm_commit_{}'.format(current_jid)\n scheduled = __salt__['schedule.add'](scheduled_job_name,\n function='net.load_config',\n job_kwargs={\n 'filename': temp_file,\n 'commit_jid': current_jid,\n 'replace': True\n },\n once=revert_time)\n log.debug('Scheduling commit confirmed')\n log.debug(scheduled)\n saved = __salt__['schedule.save']()\n loaded_result['comment'] = ('The commit ID is: {current_jid}.\\n'\n 'This commit will be reverted at: {schedule_ts}, unless confirmed.\\n'\n 'To confirm the commit and avoid reverting, you can execute:\\n\\n'\n 'salt {min_id} net.confirm_commit {current_jid}').format(schedule_ts=revert_time,\n min_id=__opts__['id'],\n current_jid=current_jid)\n loaded_result['commit_id'] = current_jid\n return loaded_result\n committed = _safe_commit_config(loaded_result, napalm_device)\n if not committed['result']:\n return loaded_result\n else:\n # would like to commit, but there's no change\n # need to call discard_config() to release the config DB\n discarded = _safe_dicard_config(loaded_result, napalm_device)\n if not discarded['result']:\n return loaded_result\n loaded_result['already_configured'] = True\n loaded_result['comment'] = 'Already configured.'\n _explicit_close(napalm_device)\n if not loaded_result['result']:\n __context__['retcode'] = 1\n return loaded_result\n"
] |
# -*- coding: utf-8 -*-
'''
NAPALM Network
==============
Basic methods for interaction with the network device through the virtual proxy 'napalm'.
:codeauthor: Mircea Ulinic <mircea@cloudflare.com> & Jerome Fleury <jf@cloudflare.com>
:maturity: new
:depends: napalm
:platform: unix
Dependencies
------------
- :mod:`napalm proxy minion <salt.proxy.napalm>`
.. versionadded:: 2016.11.0
.. versionchanged:: 2017.7.0
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import time
import logging
import datetime
log = logging.getLogger(__name__)
# Import Salt libs
from salt.ext import six
import salt.utils.files
import salt.utils.napalm
import salt.utils.versions
import salt.utils.templates
# Import 3rd-party libs
try:
import jxmlease # pylint: disable=unused-import
HAS_JXMLEASE = True
except ImportError:
HAS_JXMLEASE = False
# ----------------------------------------------------------------------------------------------------------------------
# module properties
# ----------------------------------------------------------------------------------------------------------------------
__virtualname__ = 'net'
__proxyenabled__ = ['*']
__virtual_aliases__ = ('napalm_net',)
# uses NAPALM-based proxy to interact with network devices
# ----------------------------------------------------------------------------------------------------------------------
# property functions
# ----------------------------------------------------------------------------------------------------------------------
def __virtual__():
'''
NAPALM library must be installed for this module to work and run in a (proxy) minion.
'''
return salt.utils.napalm.virtual(__opts__, __virtualname__, __file__)
# ----------------------------------------------------------------------------------------------------------------------
# helper functions -- will not be exported
# ----------------------------------------------------------------------------------------------------------------------
def _filter_list(input_list, search_key, search_value):
'''
Filters a list of dictionary by a set of key-value pair.
:param input_list: is a list of dictionaries
:param search_key: is the key we are looking for
:param search_value: is the value we are looking for the key specified in search_key
:return: filered list of dictionaries
'''
output_list = list()
for dictionary in input_list:
if dictionary.get(search_key) == search_value:
output_list.append(dictionary)
return output_list
def _filter_dict(input_dict, search_key, search_value):
'''
Filters a dictionary of dictionaries by a key-value pair.
:param input_dict: is a dictionary whose values are lists of dictionaries
:param search_key: is the key in the leaf dictionaries
:param search_values: is the value in the leaf dictionaries
:return: filtered dictionary
'''
output_dict = dict()
for key, key_list in six.iteritems(input_dict):
key_list_filtered = _filter_list(key_list, search_key, search_value)
if key_list_filtered:
output_dict[key] = key_list_filtered
return output_dict
def _safe_commit_config(loaded_result, napalm_device):
_commit = commit(inherit_napalm_device=napalm_device) # calls the function commit, defined below
if not _commit.get('result', False):
# if unable to commit
loaded_result['comment'] += _commit['comment'] if _commit.get('comment') else 'Unable to commit.'
loaded_result['result'] = False
# unable to commit, something went wrong
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
return _commit
def _safe_dicard_config(loaded_result, napalm_device):
'''
'''
log.debug('Discarding the config')
log.debug(loaded_result)
_discarded = discard_config(inherit_napalm_device=napalm_device)
if not _discarded.get('result', False):
loaded_result['comment'] += _discarded['comment'] if _discarded.get('comment') \
else 'Unable to discard config.'
loaded_result['result'] = False
# make sure it notifies
# that something went wrong
_explicit_close(napalm_device)
__context__['retcode'] = 1
return loaded_result
return _discarded
def _explicit_close(napalm_device):
'''
Will explicily close the config session with the network device,
when running in a now-always-alive proxy minion or regular minion.
This helper must be used in configuration-related functions,
as the session is preserved and not closed before making any changes.
'''
if salt.utils.napalm.not_always_alive(__opts__):
# force closing the configuration session
# when running in a non-always-alive proxy
# or regular minion
try:
napalm_device['DRIVER'].close()
except Exception as err:
log.error('Unable to close the temp connection with the device:')
log.error(err)
log.error('Please report.')
def _config_logic(napalm_device,
loaded_result,
test=False,
debug=False,
replace=False,
commit_config=True,
loaded_config=None,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
commit_jid=None,
**kwargs):
'''
Builds the config logic for `load_config` and `load_template` functions.
'''
# As the Salt logic is built around independent events
# when it comes to configuration changes in the
# candidate DB on the network devices, we need to
# make sure we're using the same session.
# Hence, we need to pass the same object around.
# the napalm_device object is inherited from
# the load_config or load_template functions
# and forwarded to compare, discard, commit etc.
# then the decorator will make sure that
# if not proxy (when the connection is always alive)
# and the `inherit_napalm_device` is set,
# `napalm_device` will be overridden.
# See `salt.utils.napalm.proxy_napalm_wrap` decorator.
current_jid = kwargs.get('__pub_jid')
if not current_jid:
current_jid = '{0:%Y%m%d%H%M%S%f}'.format(datetime.datetime.now())
loaded_result['already_configured'] = False
loaded_result['loaded_config'] = ''
if debug:
loaded_result['loaded_config'] = loaded_config
_compare = compare_config(inherit_napalm_device=napalm_device)
if _compare.get('result', False):
loaded_result['diff'] = _compare.get('out')
loaded_result.pop('out', '') # not needed
else:
loaded_result['diff'] = None
loaded_result['result'] = False
loaded_result['comment'] = _compare.get('comment')
__context__['retcode'] = 1
return loaded_result
_loaded_res = loaded_result.get('result', False)
if not _loaded_res or test:
# if unable to load the config (errors / warnings)
# or in testing mode,
# will discard the config
if loaded_result['comment']:
loaded_result['comment'] += '\n'
if not loaded_result.get('diff', ''):
loaded_result['already_configured'] = True
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
loaded_result['comment'] += 'Configuration discarded.'
# loaded_result['result'] = False not necessary
# as the result can be true when test=True
_explicit_close(napalm_device)
if not loaded_result['result']:
__context__['retcode'] = 1
return loaded_result
if not test and commit_config:
# if not in testing mode and trying to commit
if commit_jid:
log.info('Committing the JID: %s', str(commit_jid))
removed = cancel_commit(commit_jid)
log.debug('Cleaned up the commit from the schedule')
log.debug(removed['comment'])
if loaded_result.get('diff', ''):
# if not testing mode
# and also the user wants to commit (default)
# and there are changes to commit
if commit_in or commit_at:
commit_time = __utils__['timeutil.get_time_at'](time_in=commit_in,
time_at=commit_in)
# schedule job
scheduled_job_name = '__napalm_commit_{}'.format(current_jid)
temp_file = salt.utils.files.mkstemp()
with salt.utils.files.fopen(temp_file, 'w') as fp_:
fp_.write(loaded_config)
scheduled = __salt__['schedule.add'](scheduled_job_name,
function='net.load_config',
job_kwargs={
'filename': temp_file,
'commit_jid': current_jid,
'replace': replace
},
once=commit_time)
log.debug('Scheduling job')
log.debug(scheduled)
saved = __salt__['schedule.save']() # ensure the schedule is
# persistent cross Minion restart
discarded = _safe_dicard_config(loaded_result, napalm_device)
# discard the changes
if not discarded['result']:
discarded['comment'] += ('Scheduled the job to be executed at {schedule_ts}, '
'but was unable to discard the config: \n').format(schedule_ts=commit_time)
return discarded
loaded_result['comment'] = ('Changes discarded for now, and scheduled commit at: {schedule_ts}.\n'
'The commit ID is: {current_jid}.\n'
'To discard this commit, you can execute: \n\n'
'salt {min_id} net.cancel_commit {current_jid}').format(schedule_ts=commit_time,
min_id=__opts__['id'],
current_jid=current_jid)
loaded_result['commit_id'] = current_jid
return loaded_result
log.debug('About to commit:')
log.debug(loaded_result['diff'])
if revert_in or revert_at:
revert_time = __utils__['timeutil.get_time_at'](time_in=revert_in,
time_at=revert_at)
if __grains__['os'] == 'junos':
if not HAS_JXMLEASE:
loaded_result['comment'] = ('This feature requires the library jxmlease to be installed.\n'
'To install, please execute: ``pip install jxmlease``.')
loaded_result['result'] = False
return loaded_result
timestamp_at = __utils__['timeutil.get_timestamp_at'](time_in=revert_in,
time_at=revert_at)
minutes = int((timestamp_at - time.time())/60)
_comm = __salt__['napalm.junos_commit'](confirm=minutes)
if not _comm['out']:
# If unable to commit confirm, should try to bail out
loaded_result['comment'] = 'Unable to commit confirm: {}'.format(_comm['message'])
loaded_result['result'] = False
# But before exiting, we must gracefully discard the config
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
else:
temp_file = salt.utils.files.mkstemp()
running_config = __salt__['net.config'](source='running')['out']['running']
with salt.utils.files.fopen(temp_file, 'w') as fp_:
fp_.write(running_config)
committed = _safe_commit_config(loaded_result, napalm_device)
if not committed['result']:
# If unable to commit, dicard the config (which is
# already done by the _safe_commit_config function), and
# return with the command and other details.
return loaded_result
scheduled_job_name = '__napalm_commit_{}'.format(current_jid)
scheduled = __salt__['schedule.add'](scheduled_job_name,
function='net.load_config',
job_kwargs={
'filename': temp_file,
'commit_jid': current_jid,
'replace': True
},
once=revert_time)
log.debug('Scheduling commit confirmed')
log.debug(scheduled)
saved = __salt__['schedule.save']()
loaded_result['comment'] = ('The commit ID is: {current_jid}.\n'
'This commit will be reverted at: {schedule_ts}, unless confirmed.\n'
'To confirm the commit and avoid reverting, you can execute:\n\n'
'salt {min_id} net.confirm_commit {current_jid}').format(schedule_ts=revert_time,
min_id=__opts__['id'],
current_jid=current_jid)
loaded_result['commit_id'] = current_jid
return loaded_result
committed = _safe_commit_config(loaded_result, napalm_device)
if not committed['result']:
return loaded_result
else:
# would like to commit, but there's no change
# need to call discard_config() to release the config DB
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
loaded_result['already_configured'] = True
loaded_result['comment'] = 'Already configured.'
_explicit_close(napalm_device)
if not loaded_result['result']:
__context__['retcode'] = 1
return loaded_result
# ----------------------------------------------------------------------------------------------------------------------
# callable functions
# ----------------------------------------------------------------------------------------------------------------------
@salt.utils.napalm.proxy_napalm_wrap
def connected(**kwargs): # pylint: disable=unused-argument
'''
Specifies if the connection to the device succeeded.
CLI Example:
.. code-block:: bash
salt '*' net.connected
'''
return {
'out': napalm_device.get('UP', False) # pylint: disable=undefined-variable
}
@salt.utils.napalm.proxy_napalm_wrap
def facts(**kwargs): # pylint: disable=unused-argument
'''
Returns characteristics of the network device.
:return: a dictionary with the following keys:
* uptime - Uptime of the device in seconds.
* vendor - Manufacturer of the device.
* model - Device model.
* hostname - Hostname of the device
* fqdn - Fqdn of the device
* os_version - String with the OS version running on the device.
* serial_number - Serial number of the device
* interface_list - List of the interfaces of the device
CLI Example:
.. code-block:: bash
salt '*' net.facts
Example output:
.. code-block:: python
{
'os_version': '13.3R6.5',
'uptime': 10117140,
'interface_list': [
'lc-0/0/0',
'pfe-0/0/0',
'pfh-0/0/0',
'xe-0/0/0',
'xe-0/0/1',
'xe-0/0/2',
'xe-0/0/3',
'gr-0/0/10',
'ip-0/0/10'
],
'vendor': 'Juniper',
'serial_number': 'JN131356FBFA',
'model': 'MX480',
'hostname': 're0.edge05.syd01',
'fqdn': 're0.edge05.syd01'
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_facts',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def environment(**kwargs): # pylint: disable=unused-argument
'''
Returns the environment of the device.
CLI Example:
.. code-block:: bash
salt '*' net.environment
Example output:
.. code-block:: python
{
'fans': {
'Bottom Rear Fan': {
'status': True
},
'Bottom Middle Fan': {
'status': True
},
'Top Middle Fan': {
'status': True
},
'Bottom Front Fan': {
'status': True
},
'Top Front Fan': {
'status': True
},
'Top Rear Fan': {
'status': True
}
},
'memory': {
'available_ram': 16349,
'used_ram': 4934
},
'temperature': {
'FPC 0 Exhaust A': {
'is_alert': False,
'temperature': 35.0,
'is_critical': False
}
},
'cpu': {
'1': {
'%usage': 19.0
},
'0': {
'%usage': 35.0
}
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_environment',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def cli(*commands, **kwargs): # pylint: disable=unused-argument
'''
Returns a dictionary with the raw output of all commands passed as arguments.
commands
List of commands to be executed on the device.
textfsm_parse: ``False``
Try parsing the outputs using the TextFSM templates.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``napalm_cli_textfsm_parse``.
textfsm_path
The path where the TextFSM templates can be found. This option implies
the usage of the TextFSM index file.
``textfsm_path`` can be either absolute path on the server,
either specified using the following URL mschemes: ``file://``,
``salt://``, ``http://``, ``https://``, ``ftp://``,
``s3://``, ``swift://``.
.. versionadded:: 2018.3.0
.. note::
This needs to be a directory with a flat structure, having an
index file (whose name can be specified using the ``index_file`` option)
and a number of TextFSM templates.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_path``.
textfsm_template
The path to a certain the TextFSM template.
This can be specified using the absolute path
to the file, or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
.. versionadded:: 2018.3.0
textfsm_template_dict
A dictionary with the mapping between a command
and the corresponding TextFSM path to use to extract the data.
The TextFSM paths can be specified as in ``textfsm_template``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``napalm_cli_textfsm_template_dict``.
platform_grain_name: ``os``
The name of the grain used to identify the platform name
in the TextFSM index file. Default: ``os``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_grain``.
platform_column_name: ``Platform``
The column name used to identify the platform,
exactly as specified in the TextFSM index file.
Default: ``Platform``.
.. versionadded:: 2018.3.0
.. note::
This is field is case sensitive, make sure
to assign the correct value to this option,
exactly as defined in the index file.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_column_name``.
index_file: ``index``
The name of the TextFSM index file, under the ``textfsm_path``. Default: ``index``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_index_file``.
saltenv: ``base``
Salt fileserver envrionment from which to retrieve the file.
Ignored if ``textfsm_path`` is not a ``salt://`` URL.
.. versionadded:: 2018.3.0
include_empty: ``False``
Include empty files under the ``textfsm_path``.
.. versionadded:: 2018.3.0
include_pat
Glob or regex to narrow down the files cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. versionadded:: 2018.3.0
exclude_pat
Glob or regex to exclude certain files from being cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. versionadded:: 2018.3.0
.. note::
If used with ``include_pat``, files matching this pattern will be
excluded from the subset of files defined by ``include_pat``.
CLI Example:
.. code-block:: bash
salt '*' net.cli "show version" "show chassis fan"
CLI Example with TextFSM template:
.. code-block:: bash
salt '*' net.cli textfsm_parse=True textfsm_path=salt://textfsm/
Example output:
.. code-block:: python
{
'show version and haiku': 'Hostname: re0.edge01.arn01
Model: mx480
Junos: 13.3R6.5
Help me, Obi-Wan
I just saw Episode Two
You're my only hope
',
'show chassis fan' : 'Item Status RPM Measurement
Top Rear Fan OK 3840 Spinning at intermediate-speed
Bottom Rear Fan OK 3840 Spinning at intermediate-speed
Top Middle Fan OK 3900 Spinning at intermediate-speed
Bottom Middle Fan OK 3840 Spinning at intermediate-speed
Top Front Fan OK 3810 Spinning at intermediate-speed
Bottom Front Fan OK 3840 Spinning at intermediate-speed
'
}
Example output with TextFSM parsing:
.. code-block:: json
{
"comment": "",
"result": true,
"out": {
"sh ver": [
{
"kernel": "9.1S3.5",
"documentation": "9.1S3.5",
"boot": "9.1S3.5",
"crypto": "9.1S3.5",
"chassis": "",
"routing": "9.1S3.5",
"base": "9.1S3.5",
"model": "mx960"
}
]
}
}
'''
raw_cli_outputs = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'cli',
**{
'commands': list(commands)
}
)
# thus we can display the output as is
# in case of errors, they'll be catched in the proxy
if not raw_cli_outputs['result']:
# Error -> dispaly the output as-is.
return raw_cli_outputs
textfsm_parse = kwargs.get('textfsm_parse') or __opts__.get('napalm_cli_textfsm_parse') or\
__pillar__.get('napalm_cli_textfsm_parse', False)
if not textfsm_parse:
# No TextFSM parsing required, return raw commands.
log.debug('No TextFSM parsing requested.')
return raw_cli_outputs
if 'textfsm.extract' not in __salt__ or 'textfsm.index' not in __salt__:
raw_cli_outputs['comment'] += 'Unable to process: is TextFSM installed?'
log.error(raw_cli_outputs['comment'])
return raw_cli_outputs
textfsm_template = kwargs.get('textfsm_template')
log.debug('textfsm_template: %s', textfsm_template)
textfsm_path = kwargs.get('textfsm_path') or __opts__.get('textfsm_path') or\
__pillar__.get('textfsm_path')
log.debug('textfsm_path: %s', textfsm_path)
textfsm_template_dict = kwargs.get('textfsm_template_dict') or __opts__.get('napalm_cli_textfsm_template_dict') or\
__pillar__.get('napalm_cli_textfsm_template_dict', {})
log.debug('TextFSM command-template mapping: %s', textfsm_template_dict)
index_file = kwargs.get('index_file') or __opts__.get('textfsm_index_file') or\
__pillar__.get('textfsm_index_file')
log.debug('index_file: %s', index_file)
platform_grain_name = kwargs.get('platform_grain_name') or __opts__.get('textfsm_platform_grain') or\
__pillar__.get('textfsm_platform_grain', 'os')
log.debug('platform_grain_name: %s', platform_grain_name)
platform_column_name = kwargs.get('platform_column_name') or __opts__.get('textfsm_platform_column_name') or\
__pillar__.get('textfsm_platform_column_name', 'Platform')
log.debug('platform_column_name: %s', platform_column_name)
saltenv = kwargs.get('saltenv', 'base')
include_empty = kwargs.get('include_empty', False)
include_pat = kwargs.get('include_pat')
exclude_pat = kwargs.get('exclude_pat')
processed_cli_outputs = {
'comment': raw_cli_outputs.get('comment', ''),
'result': raw_cli_outputs['result'],
'out': {}
}
log.debug('Starting to analyse the raw outputs')
for command in list(commands):
command_output = raw_cli_outputs['out'][command]
log.debug('Output from command: %s', command)
log.debug(command_output)
processed_command_output = None
if textfsm_path:
log.debug('Using the templates under %s', textfsm_path)
processed_cli_output = __salt__['textfsm.index'](command,
platform_grain_name=platform_grain_name,
platform_column_name=platform_column_name,
output=command_output.strip(),
textfsm_path=textfsm_path,
saltenv=saltenv,
include_empty=include_empty,
include_pat=include_pat,
exclude_pat=exclude_pat)
log.debug('Processed CLI output:')
log.debug(processed_cli_output)
if not processed_cli_output['result']:
log.debug('Apparently this didnt work, returnin the raw output')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {0}: {1}.'.format(command,
processed_cli_output['comment'])
log.error(processed_cli_outputs['comment'])
elif processed_cli_output['out']:
log.debug('All good, %s has a nice output!', command)
processed_command_output = processed_cli_output['out']
else:
comment = '''\nProcessing "{}" didn't fail, but didn't return anything either. Dumping raw.'''.format(
command)
processed_cli_outputs['comment'] += comment
log.error(comment)
processed_command_output = command_output
elif textfsm_template or command in textfsm_template_dict:
if command in textfsm_template_dict:
textfsm_template = textfsm_template_dict[command]
log.debug('Using %s to process the command: %s', textfsm_template, command)
processed_cli_output = __salt__['textfsm.extract'](textfsm_template,
raw_text=command_output,
saltenv=saltenv)
log.debug('Processed CLI output:')
log.debug(processed_cli_output)
if not processed_cli_output['result']:
log.debug('Apparently this didnt work, returning '
'the raw output')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {0}: {1}'.format(command,
processed_cli_output['comment'])
log.error(processed_cli_outputs['comment'])
elif processed_cli_output['out']:
log.debug('All good, %s has a nice output!', command)
processed_command_output = processed_cli_output['out']
else:
log.debug('Processing %s didnt fail, but didnt return'
' anything either. Dumping raw.', command)
processed_command_output = command_output
else:
log.error('No TextFSM template specified, or no TextFSM path defined')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {}.'.format(command)
processed_cli_outputs['out'][command] = processed_command_output
processed_cli_outputs['comment'] = processed_cli_outputs['comment'].strip()
return processed_cli_outputs
@salt.utils.napalm.proxy_napalm_wrap
def traceroute(destination, source=None, ttl=None, timeout=None, vrf=None, **kwargs): # pylint: disable=unused-argument
'''
Calls the method traceroute from the NAPALM driver object and returns a dictionary with the result of the traceroute
command executed on the device.
destination
Hostname or address of remote host
source
Source address to use in outgoing traceroute packets
ttl
IP maximum time-to-live value (or IPv6 maximum hop-limit value)
timeout
Number of seconds to wait for response (seconds)
vrf
VRF (routing instance) for traceroute attempt
.. versionadded:: 2016.11.4
CLI Example:
.. code-block:: bash
salt '*' net.traceroute 8.8.8.8
salt '*' net.traceroute 8.8.8.8 source=127.0.0.1 ttl=5 timeout=1
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'traceroute',
**{
'destination': destination,
'source': source,
'ttl': ttl,
'timeout': timeout,
'vrf': vrf
}
)
@salt.utils.napalm.proxy_napalm_wrap
def ping(destination, source=None, ttl=None, timeout=None, size=None, count=None, vrf=None, **kwargs): # pylint: disable=unused-argument
'''
Executes a ping on the network device and returns a dictionary as a result.
destination
Hostname or IP address of remote host
source
Source address of echo request
ttl
IP time-to-live value (IPv6 hop-limit value) (1..255 hops)
timeout
Maximum wait time after sending final packet (seconds)
size
Size of request packets (0..65468 bytes)
count
Number of ping requests to send (1..2000000000 packets)
vrf
VRF (routing instance) for ping attempt
.. versionadded:: 2016.11.4
CLI Example:
.. code-block:: bash
salt '*' net.ping 8.8.8.8
salt '*' net.ping 8.8.8.8 ttl=3 size=65468
salt '*' net.ping 8.8.8.8 source=127.0.0.1 timeout=1 count=100
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'ping',
**{
'destination': destination,
'source': source,
'ttl': ttl,
'timeout': timeout,
'size': size,
'count': count,
'vrf': vrf
}
)
@salt.utils.napalm.proxy_napalm_wrap
def arp(interface='', ipaddr='', macaddr='', **kwargs): # pylint: disable=unused-argument
'''
NAPALM returns a list of dictionaries with details of the ARP entries.
:param interface: interface name to filter on
:param ipaddr: IP address to filter on
:param macaddr: MAC address to filter on
:return: List of the entries in the ARP table
CLI Example:
.. code-block:: bash
salt '*' net.arp
salt '*' net.arp macaddr='5c:5e:ab:da:3c:f0'
Example output:
.. code-block:: python
[
{
'interface' : 'MgmtEth0/RSP0/CPU0/0',
'mac' : '5c:5e:ab:da:3c:f0',
'ip' : '172.17.17.1',
'age' : 1454496274.84
},
{
'interface': 'MgmtEth0/RSP0/CPU0/0',
'mac' : '66:0e:94:96:e0:ff',
'ip' : '172.17.17.2',
'age' : 1435641582.49
}
]
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_arp_table',
**{
}
)
if not proxy_output.get('result'):
return proxy_output
arp_table = proxy_output.get('out')
if interface:
arp_table = _filter_list(arp_table, 'interface', interface)
if ipaddr:
arp_table = _filter_list(arp_table, 'ip', ipaddr)
if macaddr:
arp_table = _filter_list(arp_table, 'mac', macaddr)
proxy_output.update({
'out': arp_table
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def ipaddrs(**kwargs): # pylint: disable=unused-argument
'''
Returns IP addresses configured on the device.
:return: A dictionary with the IPv4 and IPv6 addresses of the interfaces.
Returns all configured IP addresses on all interfaces as a dictionary
of dictionaries. Keys of the main dictionary represent the name of the
interface. Values of the main dictionary represent are dictionaries
that may consist of two keys 'ipv4' and 'ipv6' (one, both or none)
which are themselvs dictionaries with the IP addresses as keys.
CLI Example:
.. code-block:: bash
salt '*' net.ipaddrs
Example output:
.. code-block:: python
{
'FastEthernet8': {
'ipv4': {
'10.66.43.169': {
'prefix_length': 22
}
}
},
'Loopback555': {
'ipv4': {
'192.168.1.1': {
'prefix_length': 24
}
},
'ipv6': {
'1::1': {
'prefix_length': 64
},
'2001:DB8:1::1': {
'prefix_length': 64
},
'FE80::3': {
'prefix_length': 'N/A'
}
}
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_interfaces_ip',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def interfaces(**kwargs): # pylint: disable=unused-argument
'''
Returns details of the interfaces on the device.
:return: Returns a dictionary of dictionaries. The keys for the first
dictionary will be the interfaces in the devices.
CLI Example:
.. code-block:: bash
salt '*' net.interfaces
Example output:
.. code-block:: python
{
'Management1': {
'is_up': False,
'is_enabled': False,
'description': '',
'last_flapped': -1,
'speed': 1000,
'mac_address': 'dead:beef:dead',
},
'Ethernet1':{
'is_up': True,
'is_enabled': True,
'description': 'foo',
'last_flapped': 1429978575.1554043,
'speed': 1000,
'mac_address': 'beef:dead:beef',
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_interfaces',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def lldp(interface='', **kwargs): # pylint: disable=unused-argument
'''
Returns a detailed view of the LLDP neighbors.
:param interface: interface name to filter on
:return: A dictionary with the LLDL neighbors. The keys are the
interfaces with LLDP activated on.
CLI Example:
.. code-block:: bash
salt '*' net.lldp
salt '*' net.lldp interface='TenGigE0/0/0/8'
Example output:
.. code-block:: python
{
'TenGigE0/0/0/8': [
{
'parent_interface': 'Bundle-Ether8',
'interface_description': 'TenGigE0/0/0/8',
'remote_chassis_id': '8c60.4f69.e96c',
'remote_system_name': 'switch',
'remote_port': 'Eth2/2/1',
'remote_port_description': 'Ethernet2/2/1',
'remote_system_description': 'Cisco Nexus Operating System (NX-OS) Software 7.1(0)N1(1a)
TAC support: http://www.cisco.com/tac
Copyright (c) 2002-2015, Cisco Systems, Inc. All rights reserved.',
'remote_system_capab': 'B, R',
'remote_system_enable_capab': 'B'
}
]
}
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_lldp_neighbors_detail',
**{
}
)
if not proxy_output.get('result'):
return proxy_output
lldp_neighbors = proxy_output.get('out')
if interface:
lldp_neighbors = {interface: lldp_neighbors.get(interface)}
proxy_output.update({
'out': lldp_neighbors
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def mac(address='', interface='', vlan=0, **kwargs): # pylint: disable=unused-argument
'''
Returns the MAC Address Table on the device.
:param address: MAC address to filter on
:param interface: Interface name to filter on
:param vlan: VLAN identifier
:return: A list of dictionaries representing the entries in the MAC Address Table
CLI Example:
.. code-block:: bash
salt '*' net.mac
salt '*' net.mac vlan=10
Example output:
.. code-block:: python
[
{
'mac' : '00:1c:58:29:4a:71',
'interface' : 'xe-3/0/2',
'static' : False,
'active' : True,
'moves' : 1,
'vlan' : 10,
'last_move' : 1454417742.58
},
{
'mac' : '8c:60:4f:58:e1:c1',
'interface' : 'xe-1/0/1',
'static' : False,
'active' : True,
'moves' : 2,
'vlan' : 42,
'last_move' : 1453191948.11
}
]
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_mac_address_table',
**{
}
)
if not proxy_output.get('result'):
# if negative, leave the output unchanged
return proxy_output
mac_address_table = proxy_output.get('out')
if vlan and isinstance(vlan, int):
mac_address_table = _filter_list(mac_address_table, 'vlan', vlan)
if address:
mac_address_table = _filter_list(mac_address_table, 'mac', address)
if interface:
mac_address_table = _filter_list(mac_address_table, 'interface', interface)
proxy_output.update({
'out': mac_address_table
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def config(source=None, **kwargs): # pylint: disable=unused-argument
'''
.. versionadded:: 2017.7.0
Return the whole configuration of the network device. By default, it will
return all possible configuration sources supported by the network device.
At most, there will be:
- running config
- startup config
- candidate config
To return only one of the configurations, you can use the ``source``
argument.
source
Which configuration type you want to display, default is all of them.
Options:
- running
- candidate
- startup
:return:
The object returned is a dictionary with the following keys:
- running (string): Representation of the native running configuration.
- candidate (string): Representation of the native candidate configuration.
If the device doesn't differentiate between running and startup
configuration this will an empty string.
- startup (string): Representation of the native startup configuration.
If the device doesn't differentiate between running and startup
configuration this will an empty string.
CLI Example:
.. code-block:: bash
salt '*' net.config
salt '*' net.config source=candidate
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_config',
**{
'retrieve': source
}
)
@salt.utils.napalm.proxy_napalm_wrap
def optics(**kwargs): # pylint: disable=unused-argument
'''
.. versionadded:: 2017.7.0
Fetches the power usage on the various transceivers installed
on the network device (in dBm), and returns a view that conforms with the
OpenConfig model openconfig-platform-transceiver.yang.
:return:
Returns a dictionary where the keys are as listed below:
* intf_name (unicode)
* physical_channels
* channels (list of dicts)
* index (int)
* state
* input_power
* instant (float)
* avg (float)
* min (float)
* max (float)
* output_power
* instant (float)
* avg (float)
* min (float)
* max (float)
* laser_bias_current
* instant (float)
* avg (float)
* min (float)
* max (float)
CLI Example:
.. code-block:: bash
salt '*' net.optics
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_optics',
**{
}
)
# <---- Call NAPALM getters --------------------------------------------------------------------------------------------
# ----- Configuration specific functions ------------------------------------------------------------------------------>
@salt.utils.napalm.proxy_napalm_wrap
@salt.utils.napalm.proxy_napalm_wrap
def load_template(template_name=None,
template_source=None,
context=None,
defaults=None,
template_engine='jinja',
saltenv='base',
template_hash=None,
template_hash_name=None,
skip_verify=False,
test=False,
commit=True,
debug=False,
replace=False,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
inherit_napalm_device=None, # pylint: disable=unused-argument
**template_vars):
'''
Renders a configuration template (default: Jinja) and loads the result on the device.
By default this function will commit the changes. If there are no changes,
it does not commit, discards he config and the flag ``already_configured``
will be set as ``True`` to point this out.
To avoid committing the configuration, set the argument ``test`` to ``True``
and will discard (dry run).
To preserve the changes, set ``commit`` to ``False``.
However, this is recommended to be used only in exceptional cases
when there are applied few consecutive states
and/or configuration changes.
Otherwise the user might forget that the config DB is locked
and the candidate config buffer is not cleared/merged in the running config.
To replace the config, set ``replace`` to ``True``.
template_name
Identifies path to the template source.
The template can be either stored on the local machine, either remotely.
The recommended location is under the ``file_roots``
as specified in the master config file.
For example, let's suppose the ``file_roots`` is configured as:
.. code-block:: yaml
file_roots:
base:
- /etc/salt/states
Placing the template under ``/etc/salt/states/templates/example.jinja``,
it can be used as ``salt://templates/example.jinja``.
Alternatively, for local files, the user can specify the absolute path.
If remotely, the source can be retrieved via ``http``, ``https`` or ``ftp``.
Examples:
- ``salt://my_template.jinja``
- ``/absolute/path/to/my_template.jinja``
- ``http://example.com/template.cheetah``
- ``https:/example.com/template.mako``
- ``ftp://example.com/template.py``
.. versionchanged:: 2019.2.0
This argument can now support a list of templates to be rendered.
The resulting configuration text is loaded at once, as a single
configuration chunk.
template_source: None
Inline config template to be rendered and loaded on the device.
template_hash: None
Hash of the template file. Format: ``{hash_type: 'md5', 'hsum': <md5sum>}``
.. versionadded:: 2016.11.2
context: None
Overrides default context variables passed to the template.
.. versionadded:: 2019.2.0
template_hash_name: None
When ``template_hash`` refers to a remote file,
this specifies the filename to look for in that file.
.. versionadded:: 2016.11.2
saltenv: ``base``
Specifies the template environment.
This will influence the relative imports inside the templates.
.. versionadded:: 2016.11.2
template_engine: jinja
The following templates engines are supported:
- :mod:`cheetah<salt.renderers.cheetah>`
- :mod:`genshi<salt.renderers.genshi>`
- :mod:`jinja<salt.renderers.jinja>`
- :mod:`mako<salt.renderers.mako>`
- :mod:`py<salt.renderers.py>`
- :mod:`wempy<salt.renderers.wempy>`
.. versionadded:: 2016.11.2
skip_verify: True
If ``True``, hash verification of remote file sources
(``http://``, ``https://``, ``ftp://``) will be skipped,
and the ``source_hash`` argument will be ignored.
.. versionadded:: 2016.11.2
test: False
Dry run? If set to ``True``, will apply the config,
discard and return the changes.
Default: ``False`` and will commit the changes on the device.
commit: True
Commit? (default: ``True``)
debug: False
Debug mode. Will insert a new key under the output dictionary,
as ``loaded_config`` containing the raw result after the template was rendered.
.. versionadded:: 2016.11.2
replace: False
Load and replace the configuration.
.. versionadded:: 2016.11.2
commit_in: ``None``
Commit the changes in a specific number of minutes / hours. Example of
accepted formats: ``5`` (commit in 5 minutes), ``2m`` (commit in 2
minutes), ``1h`` (commit the changes in 1 hour)`, ``5h30m`` (commit
the changes in 5 hours and 30 minutes).
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
commit_at: ``None``
Commit the changes at a specific time. Example of accepted formats:
``1am`` (will commit the changes at the next 1AM), ``13:20`` (will
commit at 13:20), ``1:20am``, etc.
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
revert_in: ``None``
Commit and revert the changes in a specific number of minutes / hours.
Example of accepted formats: ``5`` (revert in 5 minutes), ``2m`` (revert
in 2 minutes), ``1h`` (revert the changes in 1 hour)`, ``5h30m`` (revert
the changes in 5 hours and 30 minutes).
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
revert_at: ``None``
Commit and revert the changes at a specific time. Example of accepted
formats: ``1am`` (will commit and revert the changes at the next 1AM),
``13:20`` (will commit and revert at 13:20), ``1:20am``, etc.
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
defaults: None
Default variables/context passed to the template.
.. versionadded:: 2016.11.2
template_vars
Dictionary with the arguments/context to be used when the template is rendered.
.. note::
Do not explicitly specify this argument. This represents any other
variable that will be sent to the template rendering system.
Please see the examples below!
.. note::
It is more recommended to use the ``context`` argument to avoid
conflicts between CLI arguments and template variables.
:return: a dictionary having the following keys:
- result (bool): if the config was applied successfully. It is ``False``
only in case of failure. In case there are no changes to be applied and
successfully performs all operations it is still ``True`` and so will be
the ``already_configured`` flag (example below)
- comment (str): a message for the user
- already_configured (bool): flag to check if there were no changes applied
- loaded_config (str): the configuration loaded on the device, after
rendering the template. Requires ``debug`` to be set as ``True``
- diff (str): returns the config changes applied
The template can use variables from the ``grains``, ``pillar`` or ``opts``, for example:
.. code-block:: jinja
{% set router_model = grains.get('model') -%}
{% set router_vendor = grains.get('vendor') -%}
{% set os_version = grains.get('version') -%}
{% set hostname = pillar.get('proxy', {}).get('host') -%}
{% if router_vendor|lower == 'juniper' %}
system {
host-name {{hostname}};
}
{% elif router_vendor|lower == 'cisco' %}
hostname {{hostname}}
{% endif %}
CLI Examples:
.. code-block:: bash
salt '*' net.load_template set_ntp_peers peers=[192.168.0.1] # uses NAPALM default templates
# inline template:
salt -G 'os:junos' net.load_template template_source='system { host-name {{host_name}}; }' \
host_name='MX480.lab'
# inline template using grains info:
salt -G 'os:junos' net.load_template \
template_source='system { host-name {{grains.model}}.lab; }'
# if the device is a MX480, the command above will set the hostname as: MX480.lab
# inline template using pillar data:
salt -G 'os:junos' net.load_template template_source='system { host-name {{pillar.proxy.host}}; }'
salt '*' net.load_template https://bit.ly/2OhSgqP hostname=example # will commit
salt '*' net.load_template https://bit.ly/2OhSgqP hostname=example test=True # dry run
salt '*' net.load_template salt://templates/example.jinja debug=True # Using the salt:// URI
# render a mako template:
salt '*' net.load_template salt://templates/example.mako template_engine=mako debug=True
# render remote template
salt -G 'os:junos' net.load_template http://bit.ly/2fReJg7 test=True debug=True peers=['192.168.0.1']
salt -G 'os:ios' net.load_template http://bit.ly/2gKOj20 test=True debug=True peers=['192.168.0.1']
# render multiple templates at once
salt '*' net.load_template "['https://bit.ly/2OhSgqP', 'salt://templates/example.jinja']" context="{'hostname': 'example'}"
Example output:
.. code-block:: python
{
'comment': '',
'already_configured': False,
'result': True,
'diff': '[edit system]+ host-name edge01.bjm01',
'loaded_config': 'system { host-name edge01.bjm01; }''
}
'''
_rendered = ''
_loaded = {
'result': True,
'comment': '',
'out': None
}
loaded_config = None
# prechecks
deprecated_args = ('template_user', 'template_attrs', 'template_group', 'template_mode')
for deprecated_arg in deprecated_args:
if template_vars.get(deprecated_arg):
del template_vars[deprecated_arg]
salt.utils.versions.warn_until(
'Sodium',
('The \'{arg}\' argument to \'net.load_template\' is deprecated '
'and has been ignored').format(arg=deprecated_arg)
)
if template_engine not in salt.utils.templates.TEMPLATE_REGISTRY:
_loaded.update({
'result': False,
'comment': 'Invalid templating engine! Choose between: {tpl_eng_opts}'.format(
tpl_eng_opts=', '.join(list(salt.utils.templates.TEMPLATE_REGISTRY.keys()))
)
})
return _loaded # exit
# to check if will be rendered by salt or NAPALM
salt_render_prefixes = ('salt://', 'http://', 'https://', 'ftp://')
salt_render = False
file_exists = False
if not isinstance(template_name, (tuple, list)):
for salt_render_prefix in salt_render_prefixes:
if not salt_render:
salt_render = salt_render or template_name.startswith(salt_render_prefix)
file_exists = __salt__['file.file_exists'](template_name)
if template_source or file_exists or salt_render or isinstance(template_name, (tuple, list)):
# either inline template
# either template in a custom path
# either abs path send
# either starts with salt:// and
# then use Salt render system
if context is None:
context = {}
context.update(template_vars)
# if needed to render the template send as inline arg
if template_source:
# render the content
_rendered = __salt__['file.apply_template_on_contents'](
contents=template_source,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv
)
if not isinstance(_rendered, six.string_types):
if 'result' in _rendered:
_loaded['result'] = _rendered['result']
else:
_loaded['result'] = False
if 'comment' in _rendered:
_loaded['comment'] = _rendered['comment']
else:
_loaded['comment'] = 'Error while rendering the template.'
return _loaded
else:
# render the file - either local, either remote
if not isinstance(template_name, (list, tuple)):
template_name = [template_name]
if template_hash_name and not isinstance(template_hash_name, (list, tuple)):
template_hash_name = [template_hash_name]
elif not template_hash_name:
template_hash_name = [None] * len(template_name)
if template_hash and isinstance(template_hash, six.string_types) and not\
(template_hash.startswith('salt://') or template_hash.startswith('file://')):
# If the template hash is passed as string, and it's not a file
# (starts with the salt:// or file:// URI), then make it a list
# of 1 element (for the iteration below)
template_hash = [template_hash]
elif template_hash and isinstance(template_hash, six.string_types) and\
(template_hash.startswith('salt://') or template_hash.startswith('file://')):
# If the template hash is a file URI, then provide the same value
# for each of the templates in the list, as probably they all
# share the same hash file, otherwise the user should provide
# this as a list
template_hash = [template_hash] * len(template_name)
elif not template_hash:
template_hash = [None] * len(template_name)
for tpl_index, tpl_name in enumerate(template_name):
tpl_hash = template_hash[tpl_index]
tpl_hash_name = template_hash_name[tpl_index]
_rand_filename = __salt__['random.hash'](tpl_name, 'md5')
_temp_file = __salt__['file.join']('/tmp', _rand_filename)
_managed = __salt__['file.get_managed'](name=_temp_file,
source=tpl_name,
source_hash=tpl_hash,
source_hash_name=tpl_hash_name,
user=None,
group=None,
mode=None,
attrs=None,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv,
skip_verify=skip_verify)
if not isinstance(_managed, (list, tuple)) and isinstance(_managed, six.string_types):
_loaded['comment'] += _managed
_loaded['result'] = False
elif isinstance(_managed, (list, tuple)) and not _managed:
_loaded['result'] = False
_loaded['comment'] += 'Error while rendering the template.'
elif isinstance(_managed, (list, tuple)) and not _managed[0]:
_loaded['result'] = False
_loaded['comment'] += _managed[-1] # contains the error message
if _loaded['result']: # all good
_temp_tpl_file = _managed[0]
_temp_tpl_file_exists = __salt__['file.file_exists'](_temp_tpl_file)
if not _temp_tpl_file_exists:
_loaded['result'] = False
_loaded['comment'] += 'Error while rendering the template.'
return _loaded
_rendered += __salt__['file.read'](_temp_tpl_file)
__salt__['file.remove'](_temp_tpl_file)
else:
return _loaded # exit
loaded_config = _rendered
if _loaded['result']: # all good
fun = 'load_merge_candidate'
if replace: # replace requested
fun = 'load_replace_candidate'
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
fun,
**{
'config': _rendered
}
)
else:
salt.utils.versions.warn_until(
'Sodium',
'Native NAPALM templates support will be removed in the Sodium '
'release. Please consider using the Salt rendering pipeline instead.'
'If you are using the \'netntp\', \'netsnmp\', or \'netusers\' Salt '
'State modules, you can ignore this message'
)
# otherwise, use NAPALM render system, injecting pillar/grains/opts vars
load_templates_params = defaults if defaults else {}
load_templates_params.update(template_vars)
load_templates_params.update(
{
'template_name': template_name,
'template_source': template_source, # inline template
'pillar': __pillar__, # inject pillar content
'grains': __grains__, # inject grains content
'opts': __opts__ # inject opts content
}
)
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
# so we'll set the CLOSE global explicitly as False
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'load_template',
**load_templates_params
)
return _config_logic(napalm_device, # pylint: disable=undefined-variable
_loaded,
test=test,
debug=debug,
replace=replace,
commit_config=commit,
loaded_config=loaded_config,
commit_at=commit_at,
commit_in=commit_in,
revert_in=revert_in,
revert_at=revert_at,
**template_vars)
@salt.utils.napalm.proxy_napalm_wrap
def commit(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Commits the configuration changes made on the network device.
CLI Example:
.. code-block:: bash
salt '*' net.commit
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'commit_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def discard_config(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
"""
Discards the changes applied.
CLI Example:
.. code-block:: bash
salt '*' net.discard_config
"""
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'discard_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def compare_config(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Returns the difference between the running config and the candidate config.
CLI Example:
.. code-block:: bash
salt '*' net.compare_config
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'compare_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def rollback(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Rollbacks the configuration.
CLI Example:
.. code-block:: bash
salt '*' net.rollback
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'rollback',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def config_changed(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Will prompt if the configuration has been changed.
:return: A tuple with a boolean that specifies if the config was changed on the device.\
And a string that provides more details of the reason why the configuration was not changed.
CLI Example:
.. code-block:: bash
salt '*' net.config_changed
'''
is_config_changed = False
reason = ''
try_compare = compare_config(inherit_napalm_device=napalm_device) # pylint: disable=undefined-variable
if try_compare.get('result'):
if try_compare.get('out'):
is_config_changed = True
else:
reason = 'Configuration was not changed on the device.'
else:
reason = try_compare.get('comment')
return is_config_changed, reason
@salt.utils.napalm.proxy_napalm_wrap
def config_control(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Will check if the configuration was changed.
If differences found, will try to commit.
In case commit unsuccessful, will try to rollback.
:return: A tuple with a boolean that specifies if the config was changed/committed/rollbacked on the device.\
And a string that provides more details of the reason why the configuration was not committed properly.
CLI Example:
.. code-block:: bash
salt '*' net.config_control
'''
result = True
comment = ''
changed, not_changed_rsn = config_changed(inherit_napalm_device=napalm_device) # pylint: disable=undefined-variable
if not changed:
return (changed, not_changed_rsn)
# config changed, thus let's try to commit
try_commit = commit()
if not try_commit.get('result'):
result = False
comment = 'Unable to commit the changes: {reason}.\n\
Will try to rollback now!'.format(
reason=try_commit.get('comment')
)
try_rollback = rollback()
if not try_rollback.get('result'):
comment += '\nCannot rollback! {reason}'.format(
reason=try_rollback.get('comment')
)
return result, comment
def cancel_commit(jid):
'''
.. versionadded:: 2019.2.0
Cancel a commit scheduled to be executed via the ``commit_in`` and
``commit_at`` arguments from the
:py:func:`net.load_template <salt.modules.napalm_network.load_template>` or
:py:func:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit ID is displayed when the commit is scheduled
via the functions named above.
CLI Example:
.. code-block:: bash
salt '*' net.cancel_commit 20180726083540640360
'''
job_name = '__napalm_commit_{}'.format(jid)
removed = __salt__['schedule.delete'](job_name)
if removed['result']:
saved = __salt__['schedule.save']()
removed['comment'] = 'Commit #{jid} cancelled.'.format(jid=jid)
else:
removed['comment'] = 'Unable to find commit #{jid}.'.format(jid=jid)
return removed
def confirm_commit(jid):
'''
.. versionadded:: 2019.2.0
Confirm a commit scheduled to be reverted via the ``revert_in`` and
``revert_at`` arguments from the
:mod:`net.load_template <salt.modules.napalm_network.load_template>` or
:mod:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit ID is displayed when the commit confirmed
is scheduled via the functions named above.
CLI Example:
.. code-block:: bash
salt '*' net.confirm_commit 20180726083540640360
'''
if __grains__['os'] == 'junos':
# Confirm the commit, by committing (i.e., invoking the RPC call)
confirmed = __salt__['napalm.junos_commit']()
confirmed['result'] = confirmed.pop('out')
confirmed['comment'] = confirmed.pop('message')
else:
confirmed = cancel_commit(jid)
if confirmed['result']:
confirmed['comment'] = 'Commit #{jid} confirmed.'.format(jid=jid)
return confirmed
def save_config(source=None,
path=None):
'''
.. versionadded:: 2019.2.0
Save the configuration to a file on the local file system.
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``,
``startup``. Default: ``running``.
path
Absolute path to file where to save the configuration.
To push the files to the Master, use
:mod:`cp.push <salt.modules.cp.push>` Execution function.
CLI Example:
.. code-block:: bash
salt '*' net.save_config source=running
'''
if not source:
source = 'running'
if not path:
path = salt.utils.files.mkstemp()
running_config = __salt__['net.config'](source=source)
if not running_config or not running_config['result']:
log.error('Unable to retrieve the config')
return running_config
with salt.utils.files.fopen(path, 'w') as fh_:
fh_.write(running_config['out'][source])
return {
'result': True,
'out': path,
'comment': '{source} config saved to {path}'.format(source=source, path=path)
}
def replace_pattern(pattern,
repl,
count=0,
flags=8,
bufsize=1,
append_if_not_found=False,
prepend_if_not_found=False,
not_found_content=None,
search_only=False,
show_changes=True,
backslash_literal=False,
source=None,
path=None,
test=False,
replace=True,
debug=False,
commit=True):
'''
.. versionadded:: 2019.2.0
Replace occurrences of a pattern in the configuration source. If
``show_changes`` is ``True``, then a diff of what changed will be returned,
otherwise a ``True`` will be returned when changes are made, and ``False``
when no changes are made.
This is a pure Python implementation that wraps Python's :py:func:`~re.sub`.
pattern
A regular expression, to be matched using Python's
:py:func:`~re.search`.
repl
The replacement text.
count: ``0``
Maximum number of pattern occurrences to be replaced. If count is a
positive integer ``n``, only ``n`` occurrences will be replaced,
otherwise all occurrences will be replaced.
flags (list or int): ``8``
A list of flags defined in the ``re`` module documentation from the
Python standard library. Each list item should be a string that will
correlate to the human-friendly flag name. E.g., ``['IGNORECASE',
'MULTILINE']``. Optionally, ``flags`` may be an int, with a value
corresponding to the XOR (``|``) of all the desired flags. Defaults to
8 (which supports 'MULTILINE').
bufsize (int or str): ``1``
How much of the configuration to buffer into memory at once. The
default value ``1`` processes one line at a time. The special value
``file`` may be specified which will read the entire file into memory
before processing.
append_if_not_found: ``False``
If set to ``True``, and pattern is not found, then the content will be
appended to the file.
prepend_if_not_found: ``False``
If set to ``True`` and pattern is not found, then the content will be
prepended to the file.
not_found_content
Content to use for append/prepend if not found. If None (default), uses
``repl``. Useful when ``repl`` uses references to group in pattern.
search_only: ``False``
If set to true, this no changes will be performed on the file, and this
function will simply return ``True`` if the pattern was matched, and
``False`` if not.
show_changes: ``True``
If ``True``, return a diff of changes made. Otherwise, return ``True``
if changes were made, and ``False`` if not.
backslash_literal: ``False``
Interpret backslashes as literal backslashes for the repl and not
escape characters. This will help when using append/prepend so that
the backslashes are not interpreted for the repl on the second run of
the state.
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path
Save the temporary configuration to a specific path, then read from
there.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' net.replace_pattern "bind-address\\s*=" "bind-address:"
CLI Example:
.. code-block:: bash
salt '*' net.replace_pattern PREFIX-LIST_NAME new-prefix-list-name
salt '*' net.replace_pattern bgp-group-name new-bgp-group-name count=1
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
replace_pattern = __salt__['file.replace'](path,
pattern,
repl,
count=count,
flags=flags,
bufsize=bufsize,
append_if_not_found=append_if_not_found,
prepend_if_not_found=prepend_if_not_found,
not_found_content=not_found_content,
search_only=search_only,
show_changes=show_changes,
backslash_literal=backslash_literal)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
def blockreplace(marker_start,
marker_end,
content='',
append_if_not_found=False,
prepend_if_not_found=False,
show_changes=True,
append_newline=False,
source='running',
path=None,
test=False,
commit=True,
debug=False,
replace=True):
'''
.. versionadded:: 2019.2.0
Replace content of the configuration source, delimited by the line markers.
A block of content delimited by comments can help you manage several lines
without worrying about old entries removal.
marker_start
The line content identifying a line as the start of the content block.
Note that the whole line containing this marker will be considered,
so whitespace or extra content before or after the marker is included
in final output.
marker_end
The line content identifying a line as the end of the content block.
Note that the whole line containing this marker will be considered,
so whitespace or extra content before or after the marker is included
in final output.
content
The content to be used between the two lines identified by
``marker_start`` and ``marker_stop``.
append_if_not_found: ``False``
If markers are not found and set to True then, the markers and content
will be appended to the file.
prepend_if_not_found: ``False``
If markers are not found and set to True then, the markers and content
will be prepended to the file.
append_newline: ``False``
Controls whether or not a newline is appended to the content block.
If the value of this argument is ``True`` then a newline will be added
to the content block. If it is ``False``, then a newline will not be
added to the content block. If it is ``None`` then a newline will only
be added to the content block if it does not already end in a newline.
show_changes: ``True``
Controls how changes are presented. If ``True``, this function will
return the of the changes made.
If ``False``, then it will return a boolean (``True`` if any changes
were made, otherwise False).
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path: ``None``
Save the temporary configuration to a specific path, then read from
there. This argument is optional, can be used when you prefers a
particular location of the temporary file.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
CLI Example:
.. code-block:: bash
salt '*' net.blockreplace 'ntp' 'interface' ''
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
replace_pattern = __salt__['file.blockreplace'](path,
marker_start=marker_start,
marker_end=marker_end,
content=content,
append_if_not_found=append_if_not_found,
prepend_if_not_found=prepend_if_not_found,
show_changes=show_changes,
append_newline=append_newline)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
def patch(patchfile,
options='',
saltenv='base',
source_hash=None,
show_changes=True,
source='running',
path=None,
test=False,
commit=True,
debug=False,
replace=True):
'''
.. versionadded:: 2019.2.0
Apply a patch to the configuration source, and load the result into the
running config of the device.
patchfile
A patch file to apply to the configuration source.
options
Options to pass to patch.
source_hash
If the patch file (specified via the ``patchfile`` argument) is an
HTTP(S) or FTP URL and the file exists in the minion's file cache, this
option can be passed to keep the minion from re-downloading the file if
the cached copy matches the specified hash.
show_changes: ``True``
Controls how changes are presented. If ``True``, this function will
return the of the changes made.
If ``False``, then it will return a boolean (``True`` if any changes
were made, otherwise False).
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path: ``None``
Save the temporary configuration to a specific path, then read from
there. This argument is optional, can the user prefers a particular
location of the temporary file.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
CLI Example:
.. code-block:: bash
salt '*' net.patch https://example.com/running_config.patch
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
patchfile_cache = __salt__['cp.cache_file'](patchfile)
if patchfile_cache is False:
return {
'out': None,
'result': False,
'comment': 'The file "{}" does not exist.'.format(patchfile)
}
replace_pattern = __salt__['file.patch'](path,
patchfile_cache,
options=options)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
# <---- Configuration specific functions -------------------------------------------------------------------------------
|
saltstack/salt
|
salt/modules/napalm_network.py
|
load_template
|
python
|
def load_template(template_name=None,
template_source=None,
context=None,
defaults=None,
template_engine='jinja',
saltenv='base',
template_hash=None,
template_hash_name=None,
skip_verify=False,
test=False,
commit=True,
debug=False,
replace=False,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
inherit_napalm_device=None, # pylint: disable=unused-argument
**template_vars):
'''
Renders a configuration template (default: Jinja) and loads the result on the device.
By default this function will commit the changes. If there are no changes,
it does not commit, discards he config and the flag ``already_configured``
will be set as ``True`` to point this out.
To avoid committing the configuration, set the argument ``test`` to ``True``
and will discard (dry run).
To preserve the changes, set ``commit`` to ``False``.
However, this is recommended to be used only in exceptional cases
when there are applied few consecutive states
and/or configuration changes.
Otherwise the user might forget that the config DB is locked
and the candidate config buffer is not cleared/merged in the running config.
To replace the config, set ``replace`` to ``True``.
template_name
Identifies path to the template source.
The template can be either stored on the local machine, either remotely.
The recommended location is under the ``file_roots``
as specified in the master config file.
For example, let's suppose the ``file_roots`` is configured as:
.. code-block:: yaml
file_roots:
base:
- /etc/salt/states
Placing the template under ``/etc/salt/states/templates/example.jinja``,
it can be used as ``salt://templates/example.jinja``.
Alternatively, for local files, the user can specify the absolute path.
If remotely, the source can be retrieved via ``http``, ``https`` or ``ftp``.
Examples:
- ``salt://my_template.jinja``
- ``/absolute/path/to/my_template.jinja``
- ``http://example.com/template.cheetah``
- ``https:/example.com/template.mako``
- ``ftp://example.com/template.py``
.. versionchanged:: 2019.2.0
This argument can now support a list of templates to be rendered.
The resulting configuration text is loaded at once, as a single
configuration chunk.
template_source: None
Inline config template to be rendered and loaded on the device.
template_hash: None
Hash of the template file. Format: ``{hash_type: 'md5', 'hsum': <md5sum>}``
.. versionadded:: 2016.11.2
context: None
Overrides default context variables passed to the template.
.. versionadded:: 2019.2.0
template_hash_name: None
When ``template_hash`` refers to a remote file,
this specifies the filename to look for in that file.
.. versionadded:: 2016.11.2
saltenv: ``base``
Specifies the template environment.
This will influence the relative imports inside the templates.
.. versionadded:: 2016.11.2
template_engine: jinja
The following templates engines are supported:
- :mod:`cheetah<salt.renderers.cheetah>`
- :mod:`genshi<salt.renderers.genshi>`
- :mod:`jinja<salt.renderers.jinja>`
- :mod:`mako<salt.renderers.mako>`
- :mod:`py<salt.renderers.py>`
- :mod:`wempy<salt.renderers.wempy>`
.. versionadded:: 2016.11.2
skip_verify: True
If ``True``, hash verification of remote file sources
(``http://``, ``https://``, ``ftp://``) will be skipped,
and the ``source_hash`` argument will be ignored.
.. versionadded:: 2016.11.2
test: False
Dry run? If set to ``True``, will apply the config,
discard and return the changes.
Default: ``False`` and will commit the changes on the device.
commit: True
Commit? (default: ``True``)
debug: False
Debug mode. Will insert a new key under the output dictionary,
as ``loaded_config`` containing the raw result after the template was rendered.
.. versionadded:: 2016.11.2
replace: False
Load and replace the configuration.
.. versionadded:: 2016.11.2
commit_in: ``None``
Commit the changes in a specific number of minutes / hours. Example of
accepted formats: ``5`` (commit in 5 minutes), ``2m`` (commit in 2
minutes), ``1h`` (commit the changes in 1 hour)`, ``5h30m`` (commit
the changes in 5 hours and 30 minutes).
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
commit_at: ``None``
Commit the changes at a specific time. Example of accepted formats:
``1am`` (will commit the changes at the next 1AM), ``13:20`` (will
commit at 13:20), ``1:20am``, etc.
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
revert_in: ``None``
Commit and revert the changes in a specific number of minutes / hours.
Example of accepted formats: ``5`` (revert in 5 minutes), ``2m`` (revert
in 2 minutes), ``1h`` (revert the changes in 1 hour)`, ``5h30m`` (revert
the changes in 5 hours and 30 minutes).
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
revert_at: ``None``
Commit and revert the changes at a specific time. Example of accepted
formats: ``1am`` (will commit and revert the changes at the next 1AM),
``13:20`` (will commit and revert at 13:20), ``1:20am``, etc.
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
defaults: None
Default variables/context passed to the template.
.. versionadded:: 2016.11.2
template_vars
Dictionary with the arguments/context to be used when the template is rendered.
.. note::
Do not explicitly specify this argument. This represents any other
variable that will be sent to the template rendering system.
Please see the examples below!
.. note::
It is more recommended to use the ``context`` argument to avoid
conflicts between CLI arguments and template variables.
:return: a dictionary having the following keys:
- result (bool): if the config was applied successfully. It is ``False``
only in case of failure. In case there are no changes to be applied and
successfully performs all operations it is still ``True`` and so will be
the ``already_configured`` flag (example below)
- comment (str): a message for the user
- already_configured (bool): flag to check if there were no changes applied
- loaded_config (str): the configuration loaded on the device, after
rendering the template. Requires ``debug`` to be set as ``True``
- diff (str): returns the config changes applied
The template can use variables from the ``grains``, ``pillar`` or ``opts``, for example:
.. code-block:: jinja
{% set router_model = grains.get('model') -%}
{% set router_vendor = grains.get('vendor') -%}
{% set os_version = grains.get('version') -%}
{% set hostname = pillar.get('proxy', {}).get('host') -%}
{% if router_vendor|lower == 'juniper' %}
system {
host-name {{hostname}};
}
{% elif router_vendor|lower == 'cisco' %}
hostname {{hostname}}
{% endif %}
CLI Examples:
.. code-block:: bash
salt '*' net.load_template set_ntp_peers peers=[192.168.0.1] # uses NAPALM default templates
# inline template:
salt -G 'os:junos' net.load_template template_source='system { host-name {{host_name}}; }' \
host_name='MX480.lab'
# inline template using grains info:
salt -G 'os:junos' net.load_template \
template_source='system { host-name {{grains.model}}.lab; }'
# if the device is a MX480, the command above will set the hostname as: MX480.lab
# inline template using pillar data:
salt -G 'os:junos' net.load_template template_source='system { host-name {{pillar.proxy.host}}; }'
salt '*' net.load_template https://bit.ly/2OhSgqP hostname=example # will commit
salt '*' net.load_template https://bit.ly/2OhSgqP hostname=example test=True # dry run
salt '*' net.load_template salt://templates/example.jinja debug=True # Using the salt:// URI
# render a mako template:
salt '*' net.load_template salt://templates/example.mako template_engine=mako debug=True
# render remote template
salt -G 'os:junos' net.load_template http://bit.ly/2fReJg7 test=True debug=True peers=['192.168.0.1']
salt -G 'os:ios' net.load_template http://bit.ly/2gKOj20 test=True debug=True peers=['192.168.0.1']
# render multiple templates at once
salt '*' net.load_template "['https://bit.ly/2OhSgqP', 'salt://templates/example.jinja']" context="{'hostname': 'example'}"
Example output:
.. code-block:: python
{
'comment': '',
'already_configured': False,
'result': True,
'diff': '[edit system]+ host-name edge01.bjm01',
'loaded_config': 'system { host-name edge01.bjm01; }''
}
'''
_rendered = ''
_loaded = {
'result': True,
'comment': '',
'out': None
}
loaded_config = None
# prechecks
deprecated_args = ('template_user', 'template_attrs', 'template_group', 'template_mode')
for deprecated_arg in deprecated_args:
if template_vars.get(deprecated_arg):
del template_vars[deprecated_arg]
salt.utils.versions.warn_until(
'Sodium',
('The \'{arg}\' argument to \'net.load_template\' is deprecated '
'and has been ignored').format(arg=deprecated_arg)
)
if template_engine not in salt.utils.templates.TEMPLATE_REGISTRY:
_loaded.update({
'result': False,
'comment': 'Invalid templating engine! Choose between: {tpl_eng_opts}'.format(
tpl_eng_opts=', '.join(list(salt.utils.templates.TEMPLATE_REGISTRY.keys()))
)
})
return _loaded # exit
# to check if will be rendered by salt or NAPALM
salt_render_prefixes = ('salt://', 'http://', 'https://', 'ftp://')
salt_render = False
file_exists = False
if not isinstance(template_name, (tuple, list)):
for salt_render_prefix in salt_render_prefixes:
if not salt_render:
salt_render = salt_render or template_name.startswith(salt_render_prefix)
file_exists = __salt__['file.file_exists'](template_name)
if template_source or file_exists or salt_render or isinstance(template_name, (tuple, list)):
# either inline template
# either template in a custom path
# either abs path send
# either starts with salt:// and
# then use Salt render system
if context is None:
context = {}
context.update(template_vars)
# if needed to render the template send as inline arg
if template_source:
# render the content
_rendered = __salt__['file.apply_template_on_contents'](
contents=template_source,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv
)
if not isinstance(_rendered, six.string_types):
if 'result' in _rendered:
_loaded['result'] = _rendered['result']
else:
_loaded['result'] = False
if 'comment' in _rendered:
_loaded['comment'] = _rendered['comment']
else:
_loaded['comment'] = 'Error while rendering the template.'
return _loaded
else:
# render the file - either local, either remote
if not isinstance(template_name, (list, tuple)):
template_name = [template_name]
if template_hash_name and not isinstance(template_hash_name, (list, tuple)):
template_hash_name = [template_hash_name]
elif not template_hash_name:
template_hash_name = [None] * len(template_name)
if template_hash and isinstance(template_hash, six.string_types) and not\
(template_hash.startswith('salt://') or template_hash.startswith('file://')):
# If the template hash is passed as string, and it's not a file
# (starts with the salt:// or file:// URI), then make it a list
# of 1 element (for the iteration below)
template_hash = [template_hash]
elif template_hash and isinstance(template_hash, six.string_types) and\
(template_hash.startswith('salt://') or template_hash.startswith('file://')):
# If the template hash is a file URI, then provide the same value
# for each of the templates in the list, as probably they all
# share the same hash file, otherwise the user should provide
# this as a list
template_hash = [template_hash] * len(template_name)
elif not template_hash:
template_hash = [None] * len(template_name)
for tpl_index, tpl_name in enumerate(template_name):
tpl_hash = template_hash[tpl_index]
tpl_hash_name = template_hash_name[tpl_index]
_rand_filename = __salt__['random.hash'](tpl_name, 'md5')
_temp_file = __salt__['file.join']('/tmp', _rand_filename)
_managed = __salt__['file.get_managed'](name=_temp_file,
source=tpl_name,
source_hash=tpl_hash,
source_hash_name=tpl_hash_name,
user=None,
group=None,
mode=None,
attrs=None,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv,
skip_verify=skip_verify)
if not isinstance(_managed, (list, tuple)) and isinstance(_managed, six.string_types):
_loaded['comment'] += _managed
_loaded['result'] = False
elif isinstance(_managed, (list, tuple)) and not _managed:
_loaded['result'] = False
_loaded['comment'] += 'Error while rendering the template.'
elif isinstance(_managed, (list, tuple)) and not _managed[0]:
_loaded['result'] = False
_loaded['comment'] += _managed[-1] # contains the error message
if _loaded['result']: # all good
_temp_tpl_file = _managed[0]
_temp_tpl_file_exists = __salt__['file.file_exists'](_temp_tpl_file)
if not _temp_tpl_file_exists:
_loaded['result'] = False
_loaded['comment'] += 'Error while rendering the template.'
return _loaded
_rendered += __salt__['file.read'](_temp_tpl_file)
__salt__['file.remove'](_temp_tpl_file)
else:
return _loaded # exit
loaded_config = _rendered
if _loaded['result']: # all good
fun = 'load_merge_candidate'
if replace: # replace requested
fun = 'load_replace_candidate'
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
fun,
**{
'config': _rendered
}
)
else:
salt.utils.versions.warn_until(
'Sodium',
'Native NAPALM templates support will be removed in the Sodium '
'release. Please consider using the Salt rendering pipeline instead.'
'If you are using the \'netntp\', \'netsnmp\', or \'netusers\' Salt '
'State modules, you can ignore this message'
)
# otherwise, use NAPALM render system, injecting pillar/grains/opts vars
load_templates_params = defaults if defaults else {}
load_templates_params.update(template_vars)
load_templates_params.update(
{
'template_name': template_name,
'template_source': template_source, # inline template
'pillar': __pillar__, # inject pillar content
'grains': __grains__, # inject grains content
'opts': __opts__ # inject opts content
}
)
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
# so we'll set the CLOSE global explicitly as False
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'load_template',
**load_templates_params
)
return _config_logic(napalm_device, # pylint: disable=undefined-variable
_loaded,
test=test,
debug=debug,
replace=replace,
commit_config=commit,
loaded_config=loaded_config,
commit_at=commit_at,
commit_in=commit_in,
revert_in=revert_in,
revert_at=revert_at,
**template_vars)
|
Renders a configuration template (default: Jinja) and loads the result on the device.
By default this function will commit the changes. If there are no changes,
it does not commit, discards he config and the flag ``already_configured``
will be set as ``True`` to point this out.
To avoid committing the configuration, set the argument ``test`` to ``True``
and will discard (dry run).
To preserve the changes, set ``commit`` to ``False``.
However, this is recommended to be used only in exceptional cases
when there are applied few consecutive states
and/or configuration changes.
Otherwise the user might forget that the config DB is locked
and the candidate config buffer is not cleared/merged in the running config.
To replace the config, set ``replace`` to ``True``.
template_name
Identifies path to the template source.
The template can be either stored on the local machine, either remotely.
The recommended location is under the ``file_roots``
as specified in the master config file.
For example, let's suppose the ``file_roots`` is configured as:
.. code-block:: yaml
file_roots:
base:
- /etc/salt/states
Placing the template under ``/etc/salt/states/templates/example.jinja``,
it can be used as ``salt://templates/example.jinja``.
Alternatively, for local files, the user can specify the absolute path.
If remotely, the source can be retrieved via ``http``, ``https`` or ``ftp``.
Examples:
- ``salt://my_template.jinja``
- ``/absolute/path/to/my_template.jinja``
- ``http://example.com/template.cheetah``
- ``https:/example.com/template.mako``
- ``ftp://example.com/template.py``
.. versionchanged:: 2019.2.0
This argument can now support a list of templates to be rendered.
The resulting configuration text is loaded at once, as a single
configuration chunk.
template_source: None
Inline config template to be rendered and loaded on the device.
template_hash: None
Hash of the template file. Format: ``{hash_type: 'md5', 'hsum': <md5sum>}``
.. versionadded:: 2016.11.2
context: None
Overrides default context variables passed to the template.
.. versionadded:: 2019.2.0
template_hash_name: None
When ``template_hash`` refers to a remote file,
this specifies the filename to look for in that file.
.. versionadded:: 2016.11.2
saltenv: ``base``
Specifies the template environment.
This will influence the relative imports inside the templates.
.. versionadded:: 2016.11.2
template_engine: jinja
The following templates engines are supported:
- :mod:`cheetah<salt.renderers.cheetah>`
- :mod:`genshi<salt.renderers.genshi>`
- :mod:`jinja<salt.renderers.jinja>`
- :mod:`mako<salt.renderers.mako>`
- :mod:`py<salt.renderers.py>`
- :mod:`wempy<salt.renderers.wempy>`
.. versionadded:: 2016.11.2
skip_verify: True
If ``True``, hash verification of remote file sources
(``http://``, ``https://``, ``ftp://``) will be skipped,
and the ``source_hash`` argument will be ignored.
.. versionadded:: 2016.11.2
test: False
Dry run? If set to ``True``, will apply the config,
discard and return the changes.
Default: ``False`` and will commit the changes on the device.
commit: True
Commit? (default: ``True``)
debug: False
Debug mode. Will insert a new key under the output dictionary,
as ``loaded_config`` containing the raw result after the template was rendered.
.. versionadded:: 2016.11.2
replace: False
Load and replace the configuration.
.. versionadded:: 2016.11.2
commit_in: ``None``
Commit the changes in a specific number of minutes / hours. Example of
accepted formats: ``5`` (commit in 5 minutes), ``2m`` (commit in 2
minutes), ``1h`` (commit the changes in 1 hour)`, ``5h30m`` (commit
the changes in 5 hours and 30 minutes).
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
commit_at: ``None``
Commit the changes at a specific time. Example of accepted formats:
``1am`` (will commit the changes at the next 1AM), ``13:20`` (will
commit at 13:20), ``1:20am``, etc.
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
revert_in: ``None``
Commit and revert the changes in a specific number of minutes / hours.
Example of accepted formats: ``5`` (revert in 5 minutes), ``2m`` (revert
in 2 minutes), ``1h`` (revert the changes in 1 hour)`, ``5h30m`` (revert
the changes in 5 hours and 30 minutes).
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
revert_at: ``None``
Commit and revert the changes at a specific time. Example of accepted
formats: ``1am`` (will commit and revert the changes at the next 1AM),
``13:20`` (will commit and revert at 13:20), ``1:20am``, etc.
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
defaults: None
Default variables/context passed to the template.
.. versionadded:: 2016.11.2
template_vars
Dictionary with the arguments/context to be used when the template is rendered.
.. note::
Do not explicitly specify this argument. This represents any other
variable that will be sent to the template rendering system.
Please see the examples below!
.. note::
It is more recommended to use the ``context`` argument to avoid
conflicts between CLI arguments and template variables.
:return: a dictionary having the following keys:
- result (bool): if the config was applied successfully. It is ``False``
only in case of failure. In case there are no changes to be applied and
successfully performs all operations it is still ``True`` and so will be
the ``already_configured`` flag (example below)
- comment (str): a message for the user
- already_configured (bool): flag to check if there were no changes applied
- loaded_config (str): the configuration loaded on the device, after
rendering the template. Requires ``debug`` to be set as ``True``
- diff (str): returns the config changes applied
The template can use variables from the ``grains``, ``pillar`` or ``opts``, for example:
.. code-block:: jinja
{% set router_model = grains.get('model') -%}
{% set router_vendor = grains.get('vendor') -%}
{% set os_version = grains.get('version') -%}
{% set hostname = pillar.get('proxy', {}).get('host') -%}
{% if router_vendor|lower == 'juniper' %}
system {
host-name {{hostname}};
}
{% elif router_vendor|lower == 'cisco' %}
hostname {{hostname}}
{% endif %}
CLI Examples:
.. code-block:: bash
salt '*' net.load_template set_ntp_peers peers=[192.168.0.1] # uses NAPALM default templates
# inline template:
salt -G 'os:junos' net.load_template template_source='system { host-name {{host_name}}; }' \
host_name='MX480.lab'
# inline template using grains info:
salt -G 'os:junos' net.load_template \
template_source='system { host-name {{grains.model}}.lab; }'
# if the device is a MX480, the command above will set the hostname as: MX480.lab
# inline template using pillar data:
salt -G 'os:junos' net.load_template template_source='system { host-name {{pillar.proxy.host}}; }'
salt '*' net.load_template https://bit.ly/2OhSgqP hostname=example # will commit
salt '*' net.load_template https://bit.ly/2OhSgqP hostname=example test=True # dry run
salt '*' net.load_template salt://templates/example.jinja debug=True # Using the salt:// URI
# render a mako template:
salt '*' net.load_template salt://templates/example.mako template_engine=mako debug=True
# render remote template
salt -G 'os:junos' net.load_template http://bit.ly/2fReJg7 test=True debug=True peers=['192.168.0.1']
salt -G 'os:ios' net.load_template http://bit.ly/2gKOj20 test=True debug=True peers=['192.168.0.1']
# render multiple templates at once
salt '*' net.load_template "['https://bit.ly/2OhSgqP', 'salt://templates/example.jinja']" context="{'hostname': 'example'}"
Example output:
.. code-block:: python
{
'comment': '',
'already_configured': False,
'result': True,
'diff': '[edit system]+ host-name edge01.bjm01',
'loaded_config': 'system { host-name edge01.bjm01; }''
}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_network.py#L1555-L2082
|
[
"def call(napalm_device, method, *args, **kwargs):\n '''\n Calls arbitrary methods from the network driver instance.\n Please check the readthedocs_ page for the updated list of getters.\n\n .. _readthedocs: http://napalm.readthedocs.org/en/latest/support/index.html#getters-support-matrix\n\n method\n Specifies the name of the method to be called.\n\n *args\n Arguments.\n\n **kwargs\n More arguments.\n\n :return: A dictionary with three keys:\n\n * result (True/False): if the operation succeeded\n * out (object): returns the object as-is from the call\n * comment (string): provides more details in case the call failed\n * traceback (string): complete traceback in case of exception. \\\n Please submit an issue including this traceback \\\n on the `correct driver repo`_ and make sure to read the FAQ_\n\n .. _`correct driver repo`: https://github.com/napalm-automation/napalm/issues/new\n .. FAQ_: https://github.com/napalm-automation/napalm#faq\n\n Example:\n\n .. code-block:: python\n\n salt.utils.napalm.call(\n napalm_object,\n 'cli',\n [\n 'show version',\n 'show chassis fan'\n ]\n )\n '''\n result = False\n out = None\n opts = napalm_device.get('__opts__', {})\n retry = kwargs.pop('__retry', True) # retry executing the task?\n force_reconnect = kwargs.get('force_reconnect', False)\n if force_reconnect:\n log.debug('Forced reconnection initiated')\n log.debug('The current opts (under the proxy key):')\n log.debug(opts['proxy'])\n opts['proxy'].update(**kwargs)\n log.debug('Updated to:')\n log.debug(opts['proxy'])\n napalm_device = get_device(opts)\n try:\n if not napalm_device.get('UP', False):\n raise Exception('not connected')\n # if connected will try to execute desired command\n kwargs_copy = {}\n kwargs_copy.update(kwargs)\n for karg, warg in six.iteritems(kwargs_copy):\n # lets clear None arguments\n # to not be sent to NAPALM methods\n if warg is None:\n kwargs.pop(karg)\n out = getattr(napalm_device.get('DRIVER'), method)(*args, **kwargs)\n # calls the method with the specified parameters\n result = True\n except Exception as error:\n # either not connected\n # either unable to execute the command\n hostname = napalm_device.get('HOSTNAME', '[unspecified hostname]')\n err_tb = traceback.format_exc() # let's get the full traceback and display for debugging reasons.\n if isinstance(error, NotImplementedError):\n comment = '{method} is not implemented for the NAPALM {driver} driver!'.format(\n method=method,\n driver=napalm_device.get('DRIVER_NAME')\n )\n elif retry and HAS_CONN_CLOSED_EXC_CLASS and isinstance(error, ConnectionClosedException):\n # Received disconection whilst executing the operation.\n # Instructed to retry (default behaviour)\n # thus trying to re-establish the connection\n # and re-execute the command\n # if any of the operations (close, open, call) will rise again ConnectionClosedException\n # it will fail loudly.\n kwargs['__retry'] = False # do not attempt re-executing\n comment = 'Disconnected from {device}. Trying to reconnect.'.format(device=hostname)\n log.error(err_tb)\n log.error(comment)\n log.debug('Clearing the connection with %s', hostname)\n call(napalm_device, 'close', __retry=False) # safely close the connection\n # Make sure we don't leave any TCP connection open behind\n # if we fail to close properly, we might not be able to access the\n log.debug('Re-opening the connection with %s', hostname)\n call(napalm_device, 'open', __retry=False)\n log.debug('Connection re-opened with %s', hostname)\n log.debug('Re-executing %s', method)\n return call(napalm_device, method, *args, **kwargs)\n # If still not able to reconnect and execute the task,\n # the proxy keepalive feature (if enabled) will attempt\n # to reconnect.\n # If the device is using a SSH-based connection, the failure\n # will also notify the paramiko transport and the `is_alive` flag\n # is going to be set correctly.\n # More background: the network device may decide to disconnect,\n # although the SSH session itself is alive and usable, the reason\n # being the lack of activity on the CLI.\n # Paramiko's keepalive doesn't help in this case, as the ServerAliveInterval\n # are targeting the transport layer, whilst the device takes the decision\n # when there isn't any activity on the CLI, thus at the application layer.\n # Moreover, the disconnect is silent and paramiko's is_alive flag will\n # continue to return True, although the connection is already unusable.\n # For more info, see https://github.com/paramiko/paramiko/issues/813.\n # But after a command fails, the `is_alive` flag becomes aware of these\n # changes and will return False from there on. And this is how the\n # Salt proxy keepalive helps: immediately after the first failure, it\n # will know the state of the connection and will try reconnecting.\n else:\n comment = 'Cannot execute \"{method}\" on {device}{port} as {user}. Reason: {error}!'.format(\n device=napalm_device.get('HOSTNAME', '[unspecified hostname]'),\n port=(':{port}'.format(port=napalm_device.get('OPTIONAL_ARGS', {}).get('port'))\n if napalm_device.get('OPTIONAL_ARGS', {}).get('port') else ''),\n user=napalm_device.get('USERNAME', ''),\n method=method,\n error=error\n )\n log.error(comment)\n log.error(err_tb)\n return {\n 'out': {},\n 'result': False,\n 'comment': comment,\n 'traceback': err_tb\n }\n finally:\n if opts and not_always_alive(opts) and napalm_device.get('CLOSE', True):\n # either running in a not-always-alive proxy\n # either running in a regular minion\n # close the connection when the call is over\n # unless the CLOSE is explicitly set as False\n napalm_device['DRIVER'].close()\n return {\n 'out': out,\n 'result': result,\n 'comment': ''\n }\n",
"def warn_until(version,\n message,\n category=DeprecationWarning,\n stacklevel=None,\n _version_info_=None,\n _dont_call_warnings=False):\n '''\n Helper function to raise a warning, by default, a ``DeprecationWarning``,\n until the provided ``version``, after which, a ``RuntimeError`` will\n be raised to remind the developers to remove the warning because the\n target version has been reached.\n\n :param version: The version info or name after which the warning becomes a\n ``RuntimeError``. For example ``(0, 17)`` or ``Hydrogen``\n or an instance of :class:`salt.version.SaltStackVersion`.\n :param message: The warning message to be displayed.\n :param category: The warning class to be thrown, by default\n ``DeprecationWarning``\n :param stacklevel: There should be no need to set the value of\n ``stacklevel``. Salt should be able to do the right thing.\n :param _version_info_: In order to reuse this function for other SaltStack\n projects, they need to be able to provide the\n version info to compare to.\n :param _dont_call_warnings: This parameter is used just to get the\n functionality until the actual error is to be\n issued. When we're only after the salt version\n checks to raise a ``RuntimeError``.\n '''\n if not isinstance(version, (tuple,\n six.string_types,\n salt.version.SaltStackVersion)):\n raise RuntimeError(\n 'The \\'version\\' argument should be passed as a tuple, string or '\n 'an instance of \\'salt.version.SaltStackVersion\\'.'\n )\n elif isinstance(version, tuple):\n version = salt.version.SaltStackVersion(*version)\n elif isinstance(version, six.string_types):\n version = salt.version.SaltStackVersion.from_name(version)\n\n if stacklevel is None:\n # Attribute the warning to the calling function, not to warn_until()\n stacklevel = 2\n\n if _version_info_ is None:\n _version_info_ = salt.version.__version_info__\n\n _version_ = salt.version.SaltStackVersion(*_version_info_)\n\n if _version_ >= version:\n import inspect\n caller = inspect.getframeinfo(sys._getframe(stacklevel - 1))\n raise RuntimeError(\n 'The warning triggered on filename \\'{filename}\\', line number '\n '{lineno}, is supposed to be shown until version '\n '{until_version} is released. Current version is now '\n '{salt_version}. Please remove the warning.'.format(\n filename=caller.filename,\n lineno=caller.lineno,\n until_version=version.formatted_version,\n salt_version=_version_.formatted_version\n ),\n )\n\n if _dont_call_warnings is False:\n def _formatwarning(message,\n category,\n filename,\n lineno,\n line=None): # pylint: disable=W0613\n '''\n Replacement for warnings.formatwarning that disables the echoing of\n the 'line' parameter.\n '''\n return '{0}:{1}: {2}: {3}\\n'.format(\n filename, lineno, category.__name__, message\n )\n saved = warnings.formatwarning\n warnings.formatwarning = _formatwarning\n warnings.warn(\n message.format(version=version.formatted_version),\n category,\n stacklevel=stacklevel\n )\n warnings.formatwarning = saved\n",
"def not_always_alive(opts):\n '''\n Should this proxy be always alive?\n '''\n return (is_proxy(opts) and not is_always_alive(opts)) or is_minion(opts)\n",
"def _config_logic(napalm_device,\n loaded_result,\n test=False,\n debug=False,\n replace=False,\n commit_config=True,\n loaded_config=None,\n commit_in=None,\n commit_at=None,\n revert_in=None,\n revert_at=None,\n commit_jid=None,\n **kwargs):\n '''\n Builds the config logic for `load_config` and `load_template` functions.\n '''\n # As the Salt logic is built around independent events\n # when it comes to configuration changes in the\n # candidate DB on the network devices, we need to\n # make sure we're using the same session.\n # Hence, we need to pass the same object around.\n # the napalm_device object is inherited from\n # the load_config or load_template functions\n # and forwarded to compare, discard, commit etc.\n # then the decorator will make sure that\n # if not proxy (when the connection is always alive)\n # and the `inherit_napalm_device` is set,\n # `napalm_device` will be overridden.\n # See `salt.utils.napalm.proxy_napalm_wrap` decorator.\n\n current_jid = kwargs.get('__pub_jid')\n if not current_jid:\n current_jid = '{0:%Y%m%d%H%M%S%f}'.format(datetime.datetime.now())\n\n loaded_result['already_configured'] = False\n\n loaded_result['loaded_config'] = ''\n if debug:\n loaded_result['loaded_config'] = loaded_config\n\n _compare = compare_config(inherit_napalm_device=napalm_device)\n if _compare.get('result', False):\n loaded_result['diff'] = _compare.get('out')\n loaded_result.pop('out', '') # not needed\n else:\n loaded_result['diff'] = None\n loaded_result['result'] = False\n loaded_result['comment'] = _compare.get('comment')\n __context__['retcode'] = 1\n return loaded_result\n\n _loaded_res = loaded_result.get('result', False)\n if not _loaded_res or test:\n # if unable to load the config (errors / warnings)\n # or in testing mode,\n # will discard the config\n if loaded_result['comment']:\n loaded_result['comment'] += '\\n'\n if not loaded_result.get('diff', ''):\n loaded_result['already_configured'] = True\n discarded = _safe_dicard_config(loaded_result, napalm_device)\n if not discarded['result']:\n return loaded_result\n loaded_result['comment'] += 'Configuration discarded.'\n # loaded_result['result'] = False not necessary\n # as the result can be true when test=True\n _explicit_close(napalm_device)\n if not loaded_result['result']:\n __context__['retcode'] = 1\n return loaded_result\n\n if not test and commit_config:\n # if not in testing mode and trying to commit\n if commit_jid:\n log.info('Committing the JID: %s', str(commit_jid))\n removed = cancel_commit(commit_jid)\n log.debug('Cleaned up the commit from the schedule')\n log.debug(removed['comment'])\n if loaded_result.get('diff', ''):\n # if not testing mode\n # and also the user wants to commit (default)\n # and there are changes to commit\n if commit_in or commit_at:\n commit_time = __utils__['timeutil.get_time_at'](time_in=commit_in,\n time_at=commit_in)\n # schedule job\n scheduled_job_name = '__napalm_commit_{}'.format(current_jid)\n temp_file = salt.utils.files.mkstemp()\n with salt.utils.files.fopen(temp_file, 'w') as fp_:\n fp_.write(loaded_config)\n scheduled = __salt__['schedule.add'](scheduled_job_name,\n function='net.load_config',\n job_kwargs={\n 'filename': temp_file,\n 'commit_jid': current_jid,\n 'replace': replace\n },\n once=commit_time)\n log.debug('Scheduling job')\n log.debug(scheduled)\n saved = __salt__['schedule.save']() # ensure the schedule is\n # persistent cross Minion restart\n discarded = _safe_dicard_config(loaded_result, napalm_device)\n # discard the changes\n if not discarded['result']:\n discarded['comment'] += ('Scheduled the job to be executed at {schedule_ts}, '\n 'but was unable to discard the config: \\n').format(schedule_ts=commit_time)\n return discarded\n loaded_result['comment'] = ('Changes discarded for now, and scheduled commit at: {schedule_ts}.\\n'\n 'The commit ID is: {current_jid}.\\n'\n 'To discard this commit, you can execute: \\n\\n'\n 'salt {min_id} net.cancel_commit {current_jid}').format(schedule_ts=commit_time,\n min_id=__opts__['id'],\n current_jid=current_jid)\n loaded_result['commit_id'] = current_jid\n return loaded_result\n log.debug('About to commit:')\n log.debug(loaded_result['diff'])\n if revert_in or revert_at:\n revert_time = __utils__['timeutil.get_time_at'](time_in=revert_in,\n time_at=revert_at)\n if __grains__['os'] == 'junos':\n if not HAS_JXMLEASE:\n loaded_result['comment'] = ('This feature requires the library jxmlease to be installed.\\n'\n 'To install, please execute: ``pip install jxmlease``.')\n loaded_result['result'] = False\n return loaded_result\n timestamp_at = __utils__['timeutil.get_timestamp_at'](time_in=revert_in,\n time_at=revert_at)\n minutes = int((timestamp_at - time.time())/60)\n _comm = __salt__['napalm.junos_commit'](confirm=minutes)\n if not _comm['out']:\n # If unable to commit confirm, should try to bail out\n loaded_result['comment'] = 'Unable to commit confirm: {}'.format(_comm['message'])\n loaded_result['result'] = False\n # But before exiting, we must gracefully discard the config\n discarded = _safe_dicard_config(loaded_result, napalm_device)\n if not discarded['result']:\n return loaded_result\n else:\n temp_file = salt.utils.files.mkstemp()\n running_config = __salt__['net.config'](source='running')['out']['running']\n with salt.utils.files.fopen(temp_file, 'w') as fp_:\n fp_.write(running_config)\n committed = _safe_commit_config(loaded_result, napalm_device)\n if not committed['result']:\n # If unable to commit, dicard the config (which is\n # already done by the _safe_commit_config function), and\n # return with the command and other details.\n return loaded_result\n scheduled_job_name = '__napalm_commit_{}'.format(current_jid)\n scheduled = __salt__['schedule.add'](scheduled_job_name,\n function='net.load_config',\n job_kwargs={\n 'filename': temp_file,\n 'commit_jid': current_jid,\n 'replace': True\n },\n once=revert_time)\n log.debug('Scheduling commit confirmed')\n log.debug(scheduled)\n saved = __salt__['schedule.save']()\n loaded_result['comment'] = ('The commit ID is: {current_jid}.\\n'\n 'This commit will be reverted at: {schedule_ts}, unless confirmed.\\n'\n 'To confirm the commit and avoid reverting, you can execute:\\n\\n'\n 'salt {min_id} net.confirm_commit {current_jid}').format(schedule_ts=revert_time,\n min_id=__opts__['id'],\n current_jid=current_jid)\n loaded_result['commit_id'] = current_jid\n return loaded_result\n committed = _safe_commit_config(loaded_result, napalm_device)\n if not committed['result']:\n return loaded_result\n else:\n # would like to commit, but there's no change\n # need to call discard_config() to release the config DB\n discarded = _safe_dicard_config(loaded_result, napalm_device)\n if not discarded['result']:\n return loaded_result\n loaded_result['already_configured'] = True\n loaded_result['comment'] = 'Already configured.'\n _explicit_close(napalm_device)\n if not loaded_result['result']:\n __context__['retcode'] = 1\n return loaded_result\n"
] |
# -*- coding: utf-8 -*-
'''
NAPALM Network
==============
Basic methods for interaction with the network device through the virtual proxy 'napalm'.
:codeauthor: Mircea Ulinic <mircea@cloudflare.com> & Jerome Fleury <jf@cloudflare.com>
:maturity: new
:depends: napalm
:platform: unix
Dependencies
------------
- :mod:`napalm proxy minion <salt.proxy.napalm>`
.. versionadded:: 2016.11.0
.. versionchanged:: 2017.7.0
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import time
import logging
import datetime
log = logging.getLogger(__name__)
# Import Salt libs
from salt.ext import six
import salt.utils.files
import salt.utils.napalm
import salt.utils.versions
import salt.utils.templates
# Import 3rd-party libs
try:
import jxmlease # pylint: disable=unused-import
HAS_JXMLEASE = True
except ImportError:
HAS_JXMLEASE = False
# ----------------------------------------------------------------------------------------------------------------------
# module properties
# ----------------------------------------------------------------------------------------------------------------------
__virtualname__ = 'net'
__proxyenabled__ = ['*']
__virtual_aliases__ = ('napalm_net',)
# uses NAPALM-based proxy to interact with network devices
# ----------------------------------------------------------------------------------------------------------------------
# property functions
# ----------------------------------------------------------------------------------------------------------------------
def __virtual__():
'''
NAPALM library must be installed for this module to work and run in a (proxy) minion.
'''
return salt.utils.napalm.virtual(__opts__, __virtualname__, __file__)
# ----------------------------------------------------------------------------------------------------------------------
# helper functions -- will not be exported
# ----------------------------------------------------------------------------------------------------------------------
def _filter_list(input_list, search_key, search_value):
'''
Filters a list of dictionary by a set of key-value pair.
:param input_list: is a list of dictionaries
:param search_key: is the key we are looking for
:param search_value: is the value we are looking for the key specified in search_key
:return: filered list of dictionaries
'''
output_list = list()
for dictionary in input_list:
if dictionary.get(search_key) == search_value:
output_list.append(dictionary)
return output_list
def _filter_dict(input_dict, search_key, search_value):
'''
Filters a dictionary of dictionaries by a key-value pair.
:param input_dict: is a dictionary whose values are lists of dictionaries
:param search_key: is the key in the leaf dictionaries
:param search_values: is the value in the leaf dictionaries
:return: filtered dictionary
'''
output_dict = dict()
for key, key_list in six.iteritems(input_dict):
key_list_filtered = _filter_list(key_list, search_key, search_value)
if key_list_filtered:
output_dict[key] = key_list_filtered
return output_dict
def _safe_commit_config(loaded_result, napalm_device):
_commit = commit(inherit_napalm_device=napalm_device) # calls the function commit, defined below
if not _commit.get('result', False):
# if unable to commit
loaded_result['comment'] += _commit['comment'] if _commit.get('comment') else 'Unable to commit.'
loaded_result['result'] = False
# unable to commit, something went wrong
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
return _commit
def _safe_dicard_config(loaded_result, napalm_device):
'''
'''
log.debug('Discarding the config')
log.debug(loaded_result)
_discarded = discard_config(inherit_napalm_device=napalm_device)
if not _discarded.get('result', False):
loaded_result['comment'] += _discarded['comment'] if _discarded.get('comment') \
else 'Unable to discard config.'
loaded_result['result'] = False
# make sure it notifies
# that something went wrong
_explicit_close(napalm_device)
__context__['retcode'] = 1
return loaded_result
return _discarded
def _explicit_close(napalm_device):
'''
Will explicily close the config session with the network device,
when running in a now-always-alive proxy minion or regular minion.
This helper must be used in configuration-related functions,
as the session is preserved and not closed before making any changes.
'''
if salt.utils.napalm.not_always_alive(__opts__):
# force closing the configuration session
# when running in a non-always-alive proxy
# or regular minion
try:
napalm_device['DRIVER'].close()
except Exception as err:
log.error('Unable to close the temp connection with the device:')
log.error(err)
log.error('Please report.')
def _config_logic(napalm_device,
loaded_result,
test=False,
debug=False,
replace=False,
commit_config=True,
loaded_config=None,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
commit_jid=None,
**kwargs):
'''
Builds the config logic for `load_config` and `load_template` functions.
'''
# As the Salt logic is built around independent events
# when it comes to configuration changes in the
# candidate DB on the network devices, we need to
# make sure we're using the same session.
# Hence, we need to pass the same object around.
# the napalm_device object is inherited from
# the load_config or load_template functions
# and forwarded to compare, discard, commit etc.
# then the decorator will make sure that
# if not proxy (when the connection is always alive)
# and the `inherit_napalm_device` is set,
# `napalm_device` will be overridden.
# See `salt.utils.napalm.proxy_napalm_wrap` decorator.
current_jid = kwargs.get('__pub_jid')
if not current_jid:
current_jid = '{0:%Y%m%d%H%M%S%f}'.format(datetime.datetime.now())
loaded_result['already_configured'] = False
loaded_result['loaded_config'] = ''
if debug:
loaded_result['loaded_config'] = loaded_config
_compare = compare_config(inherit_napalm_device=napalm_device)
if _compare.get('result', False):
loaded_result['diff'] = _compare.get('out')
loaded_result.pop('out', '') # not needed
else:
loaded_result['diff'] = None
loaded_result['result'] = False
loaded_result['comment'] = _compare.get('comment')
__context__['retcode'] = 1
return loaded_result
_loaded_res = loaded_result.get('result', False)
if not _loaded_res or test:
# if unable to load the config (errors / warnings)
# or in testing mode,
# will discard the config
if loaded_result['comment']:
loaded_result['comment'] += '\n'
if not loaded_result.get('diff', ''):
loaded_result['already_configured'] = True
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
loaded_result['comment'] += 'Configuration discarded.'
# loaded_result['result'] = False not necessary
# as the result can be true when test=True
_explicit_close(napalm_device)
if not loaded_result['result']:
__context__['retcode'] = 1
return loaded_result
if not test and commit_config:
# if not in testing mode and trying to commit
if commit_jid:
log.info('Committing the JID: %s', str(commit_jid))
removed = cancel_commit(commit_jid)
log.debug('Cleaned up the commit from the schedule')
log.debug(removed['comment'])
if loaded_result.get('diff', ''):
# if not testing mode
# and also the user wants to commit (default)
# and there are changes to commit
if commit_in or commit_at:
commit_time = __utils__['timeutil.get_time_at'](time_in=commit_in,
time_at=commit_in)
# schedule job
scheduled_job_name = '__napalm_commit_{}'.format(current_jid)
temp_file = salt.utils.files.mkstemp()
with salt.utils.files.fopen(temp_file, 'w') as fp_:
fp_.write(loaded_config)
scheduled = __salt__['schedule.add'](scheduled_job_name,
function='net.load_config',
job_kwargs={
'filename': temp_file,
'commit_jid': current_jid,
'replace': replace
},
once=commit_time)
log.debug('Scheduling job')
log.debug(scheduled)
saved = __salt__['schedule.save']() # ensure the schedule is
# persistent cross Minion restart
discarded = _safe_dicard_config(loaded_result, napalm_device)
# discard the changes
if not discarded['result']:
discarded['comment'] += ('Scheduled the job to be executed at {schedule_ts}, '
'but was unable to discard the config: \n').format(schedule_ts=commit_time)
return discarded
loaded_result['comment'] = ('Changes discarded for now, and scheduled commit at: {schedule_ts}.\n'
'The commit ID is: {current_jid}.\n'
'To discard this commit, you can execute: \n\n'
'salt {min_id} net.cancel_commit {current_jid}').format(schedule_ts=commit_time,
min_id=__opts__['id'],
current_jid=current_jid)
loaded_result['commit_id'] = current_jid
return loaded_result
log.debug('About to commit:')
log.debug(loaded_result['diff'])
if revert_in or revert_at:
revert_time = __utils__['timeutil.get_time_at'](time_in=revert_in,
time_at=revert_at)
if __grains__['os'] == 'junos':
if not HAS_JXMLEASE:
loaded_result['comment'] = ('This feature requires the library jxmlease to be installed.\n'
'To install, please execute: ``pip install jxmlease``.')
loaded_result['result'] = False
return loaded_result
timestamp_at = __utils__['timeutil.get_timestamp_at'](time_in=revert_in,
time_at=revert_at)
minutes = int((timestamp_at - time.time())/60)
_comm = __salt__['napalm.junos_commit'](confirm=minutes)
if not _comm['out']:
# If unable to commit confirm, should try to bail out
loaded_result['comment'] = 'Unable to commit confirm: {}'.format(_comm['message'])
loaded_result['result'] = False
# But before exiting, we must gracefully discard the config
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
else:
temp_file = salt.utils.files.mkstemp()
running_config = __salt__['net.config'](source='running')['out']['running']
with salt.utils.files.fopen(temp_file, 'w') as fp_:
fp_.write(running_config)
committed = _safe_commit_config(loaded_result, napalm_device)
if not committed['result']:
# If unable to commit, dicard the config (which is
# already done by the _safe_commit_config function), and
# return with the command and other details.
return loaded_result
scheduled_job_name = '__napalm_commit_{}'.format(current_jid)
scheduled = __salt__['schedule.add'](scheduled_job_name,
function='net.load_config',
job_kwargs={
'filename': temp_file,
'commit_jid': current_jid,
'replace': True
},
once=revert_time)
log.debug('Scheduling commit confirmed')
log.debug(scheduled)
saved = __salt__['schedule.save']()
loaded_result['comment'] = ('The commit ID is: {current_jid}.\n'
'This commit will be reverted at: {schedule_ts}, unless confirmed.\n'
'To confirm the commit and avoid reverting, you can execute:\n\n'
'salt {min_id} net.confirm_commit {current_jid}').format(schedule_ts=revert_time,
min_id=__opts__['id'],
current_jid=current_jid)
loaded_result['commit_id'] = current_jid
return loaded_result
committed = _safe_commit_config(loaded_result, napalm_device)
if not committed['result']:
return loaded_result
else:
# would like to commit, but there's no change
# need to call discard_config() to release the config DB
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
loaded_result['already_configured'] = True
loaded_result['comment'] = 'Already configured.'
_explicit_close(napalm_device)
if not loaded_result['result']:
__context__['retcode'] = 1
return loaded_result
# ----------------------------------------------------------------------------------------------------------------------
# callable functions
# ----------------------------------------------------------------------------------------------------------------------
@salt.utils.napalm.proxy_napalm_wrap
def connected(**kwargs): # pylint: disable=unused-argument
'''
Specifies if the connection to the device succeeded.
CLI Example:
.. code-block:: bash
salt '*' net.connected
'''
return {
'out': napalm_device.get('UP', False) # pylint: disable=undefined-variable
}
@salt.utils.napalm.proxy_napalm_wrap
def facts(**kwargs): # pylint: disable=unused-argument
'''
Returns characteristics of the network device.
:return: a dictionary with the following keys:
* uptime - Uptime of the device in seconds.
* vendor - Manufacturer of the device.
* model - Device model.
* hostname - Hostname of the device
* fqdn - Fqdn of the device
* os_version - String with the OS version running on the device.
* serial_number - Serial number of the device
* interface_list - List of the interfaces of the device
CLI Example:
.. code-block:: bash
salt '*' net.facts
Example output:
.. code-block:: python
{
'os_version': '13.3R6.5',
'uptime': 10117140,
'interface_list': [
'lc-0/0/0',
'pfe-0/0/0',
'pfh-0/0/0',
'xe-0/0/0',
'xe-0/0/1',
'xe-0/0/2',
'xe-0/0/3',
'gr-0/0/10',
'ip-0/0/10'
],
'vendor': 'Juniper',
'serial_number': 'JN131356FBFA',
'model': 'MX480',
'hostname': 're0.edge05.syd01',
'fqdn': 're0.edge05.syd01'
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_facts',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def environment(**kwargs): # pylint: disable=unused-argument
'''
Returns the environment of the device.
CLI Example:
.. code-block:: bash
salt '*' net.environment
Example output:
.. code-block:: python
{
'fans': {
'Bottom Rear Fan': {
'status': True
},
'Bottom Middle Fan': {
'status': True
},
'Top Middle Fan': {
'status': True
},
'Bottom Front Fan': {
'status': True
},
'Top Front Fan': {
'status': True
},
'Top Rear Fan': {
'status': True
}
},
'memory': {
'available_ram': 16349,
'used_ram': 4934
},
'temperature': {
'FPC 0 Exhaust A': {
'is_alert': False,
'temperature': 35.0,
'is_critical': False
}
},
'cpu': {
'1': {
'%usage': 19.0
},
'0': {
'%usage': 35.0
}
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_environment',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def cli(*commands, **kwargs): # pylint: disable=unused-argument
'''
Returns a dictionary with the raw output of all commands passed as arguments.
commands
List of commands to be executed on the device.
textfsm_parse: ``False``
Try parsing the outputs using the TextFSM templates.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``napalm_cli_textfsm_parse``.
textfsm_path
The path where the TextFSM templates can be found. This option implies
the usage of the TextFSM index file.
``textfsm_path`` can be either absolute path on the server,
either specified using the following URL mschemes: ``file://``,
``salt://``, ``http://``, ``https://``, ``ftp://``,
``s3://``, ``swift://``.
.. versionadded:: 2018.3.0
.. note::
This needs to be a directory with a flat structure, having an
index file (whose name can be specified using the ``index_file`` option)
and a number of TextFSM templates.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_path``.
textfsm_template
The path to a certain the TextFSM template.
This can be specified using the absolute path
to the file, or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
.. versionadded:: 2018.3.0
textfsm_template_dict
A dictionary with the mapping between a command
and the corresponding TextFSM path to use to extract the data.
The TextFSM paths can be specified as in ``textfsm_template``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``napalm_cli_textfsm_template_dict``.
platform_grain_name: ``os``
The name of the grain used to identify the platform name
in the TextFSM index file. Default: ``os``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_grain``.
platform_column_name: ``Platform``
The column name used to identify the platform,
exactly as specified in the TextFSM index file.
Default: ``Platform``.
.. versionadded:: 2018.3.0
.. note::
This is field is case sensitive, make sure
to assign the correct value to this option,
exactly as defined in the index file.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_column_name``.
index_file: ``index``
The name of the TextFSM index file, under the ``textfsm_path``. Default: ``index``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_index_file``.
saltenv: ``base``
Salt fileserver envrionment from which to retrieve the file.
Ignored if ``textfsm_path`` is not a ``salt://`` URL.
.. versionadded:: 2018.3.0
include_empty: ``False``
Include empty files under the ``textfsm_path``.
.. versionadded:: 2018.3.0
include_pat
Glob or regex to narrow down the files cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. versionadded:: 2018.3.0
exclude_pat
Glob or regex to exclude certain files from being cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. versionadded:: 2018.3.0
.. note::
If used with ``include_pat``, files matching this pattern will be
excluded from the subset of files defined by ``include_pat``.
CLI Example:
.. code-block:: bash
salt '*' net.cli "show version" "show chassis fan"
CLI Example with TextFSM template:
.. code-block:: bash
salt '*' net.cli textfsm_parse=True textfsm_path=salt://textfsm/
Example output:
.. code-block:: python
{
'show version and haiku': 'Hostname: re0.edge01.arn01
Model: mx480
Junos: 13.3R6.5
Help me, Obi-Wan
I just saw Episode Two
You're my only hope
',
'show chassis fan' : 'Item Status RPM Measurement
Top Rear Fan OK 3840 Spinning at intermediate-speed
Bottom Rear Fan OK 3840 Spinning at intermediate-speed
Top Middle Fan OK 3900 Spinning at intermediate-speed
Bottom Middle Fan OK 3840 Spinning at intermediate-speed
Top Front Fan OK 3810 Spinning at intermediate-speed
Bottom Front Fan OK 3840 Spinning at intermediate-speed
'
}
Example output with TextFSM parsing:
.. code-block:: json
{
"comment": "",
"result": true,
"out": {
"sh ver": [
{
"kernel": "9.1S3.5",
"documentation": "9.1S3.5",
"boot": "9.1S3.5",
"crypto": "9.1S3.5",
"chassis": "",
"routing": "9.1S3.5",
"base": "9.1S3.5",
"model": "mx960"
}
]
}
}
'''
raw_cli_outputs = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'cli',
**{
'commands': list(commands)
}
)
# thus we can display the output as is
# in case of errors, they'll be catched in the proxy
if not raw_cli_outputs['result']:
# Error -> dispaly the output as-is.
return raw_cli_outputs
textfsm_parse = kwargs.get('textfsm_parse') or __opts__.get('napalm_cli_textfsm_parse') or\
__pillar__.get('napalm_cli_textfsm_parse', False)
if not textfsm_parse:
# No TextFSM parsing required, return raw commands.
log.debug('No TextFSM parsing requested.')
return raw_cli_outputs
if 'textfsm.extract' not in __salt__ or 'textfsm.index' not in __salt__:
raw_cli_outputs['comment'] += 'Unable to process: is TextFSM installed?'
log.error(raw_cli_outputs['comment'])
return raw_cli_outputs
textfsm_template = kwargs.get('textfsm_template')
log.debug('textfsm_template: %s', textfsm_template)
textfsm_path = kwargs.get('textfsm_path') or __opts__.get('textfsm_path') or\
__pillar__.get('textfsm_path')
log.debug('textfsm_path: %s', textfsm_path)
textfsm_template_dict = kwargs.get('textfsm_template_dict') or __opts__.get('napalm_cli_textfsm_template_dict') or\
__pillar__.get('napalm_cli_textfsm_template_dict', {})
log.debug('TextFSM command-template mapping: %s', textfsm_template_dict)
index_file = kwargs.get('index_file') or __opts__.get('textfsm_index_file') or\
__pillar__.get('textfsm_index_file')
log.debug('index_file: %s', index_file)
platform_grain_name = kwargs.get('platform_grain_name') or __opts__.get('textfsm_platform_grain') or\
__pillar__.get('textfsm_platform_grain', 'os')
log.debug('platform_grain_name: %s', platform_grain_name)
platform_column_name = kwargs.get('platform_column_name') or __opts__.get('textfsm_platform_column_name') or\
__pillar__.get('textfsm_platform_column_name', 'Platform')
log.debug('platform_column_name: %s', platform_column_name)
saltenv = kwargs.get('saltenv', 'base')
include_empty = kwargs.get('include_empty', False)
include_pat = kwargs.get('include_pat')
exclude_pat = kwargs.get('exclude_pat')
processed_cli_outputs = {
'comment': raw_cli_outputs.get('comment', ''),
'result': raw_cli_outputs['result'],
'out': {}
}
log.debug('Starting to analyse the raw outputs')
for command in list(commands):
command_output = raw_cli_outputs['out'][command]
log.debug('Output from command: %s', command)
log.debug(command_output)
processed_command_output = None
if textfsm_path:
log.debug('Using the templates under %s', textfsm_path)
processed_cli_output = __salt__['textfsm.index'](command,
platform_grain_name=platform_grain_name,
platform_column_name=platform_column_name,
output=command_output.strip(),
textfsm_path=textfsm_path,
saltenv=saltenv,
include_empty=include_empty,
include_pat=include_pat,
exclude_pat=exclude_pat)
log.debug('Processed CLI output:')
log.debug(processed_cli_output)
if not processed_cli_output['result']:
log.debug('Apparently this didnt work, returnin the raw output')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {0}: {1}.'.format(command,
processed_cli_output['comment'])
log.error(processed_cli_outputs['comment'])
elif processed_cli_output['out']:
log.debug('All good, %s has a nice output!', command)
processed_command_output = processed_cli_output['out']
else:
comment = '''\nProcessing "{}" didn't fail, but didn't return anything either. Dumping raw.'''.format(
command)
processed_cli_outputs['comment'] += comment
log.error(comment)
processed_command_output = command_output
elif textfsm_template or command in textfsm_template_dict:
if command in textfsm_template_dict:
textfsm_template = textfsm_template_dict[command]
log.debug('Using %s to process the command: %s', textfsm_template, command)
processed_cli_output = __salt__['textfsm.extract'](textfsm_template,
raw_text=command_output,
saltenv=saltenv)
log.debug('Processed CLI output:')
log.debug(processed_cli_output)
if not processed_cli_output['result']:
log.debug('Apparently this didnt work, returning '
'the raw output')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {0}: {1}'.format(command,
processed_cli_output['comment'])
log.error(processed_cli_outputs['comment'])
elif processed_cli_output['out']:
log.debug('All good, %s has a nice output!', command)
processed_command_output = processed_cli_output['out']
else:
log.debug('Processing %s didnt fail, but didnt return'
' anything either. Dumping raw.', command)
processed_command_output = command_output
else:
log.error('No TextFSM template specified, or no TextFSM path defined')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {}.'.format(command)
processed_cli_outputs['out'][command] = processed_command_output
processed_cli_outputs['comment'] = processed_cli_outputs['comment'].strip()
return processed_cli_outputs
@salt.utils.napalm.proxy_napalm_wrap
def traceroute(destination, source=None, ttl=None, timeout=None, vrf=None, **kwargs): # pylint: disable=unused-argument
'''
Calls the method traceroute from the NAPALM driver object and returns a dictionary with the result of the traceroute
command executed on the device.
destination
Hostname or address of remote host
source
Source address to use in outgoing traceroute packets
ttl
IP maximum time-to-live value (or IPv6 maximum hop-limit value)
timeout
Number of seconds to wait for response (seconds)
vrf
VRF (routing instance) for traceroute attempt
.. versionadded:: 2016.11.4
CLI Example:
.. code-block:: bash
salt '*' net.traceroute 8.8.8.8
salt '*' net.traceroute 8.8.8.8 source=127.0.0.1 ttl=5 timeout=1
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'traceroute',
**{
'destination': destination,
'source': source,
'ttl': ttl,
'timeout': timeout,
'vrf': vrf
}
)
@salt.utils.napalm.proxy_napalm_wrap
def ping(destination, source=None, ttl=None, timeout=None, size=None, count=None, vrf=None, **kwargs): # pylint: disable=unused-argument
'''
Executes a ping on the network device and returns a dictionary as a result.
destination
Hostname or IP address of remote host
source
Source address of echo request
ttl
IP time-to-live value (IPv6 hop-limit value) (1..255 hops)
timeout
Maximum wait time after sending final packet (seconds)
size
Size of request packets (0..65468 bytes)
count
Number of ping requests to send (1..2000000000 packets)
vrf
VRF (routing instance) for ping attempt
.. versionadded:: 2016.11.4
CLI Example:
.. code-block:: bash
salt '*' net.ping 8.8.8.8
salt '*' net.ping 8.8.8.8 ttl=3 size=65468
salt '*' net.ping 8.8.8.8 source=127.0.0.1 timeout=1 count=100
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'ping',
**{
'destination': destination,
'source': source,
'ttl': ttl,
'timeout': timeout,
'size': size,
'count': count,
'vrf': vrf
}
)
@salt.utils.napalm.proxy_napalm_wrap
def arp(interface='', ipaddr='', macaddr='', **kwargs): # pylint: disable=unused-argument
'''
NAPALM returns a list of dictionaries with details of the ARP entries.
:param interface: interface name to filter on
:param ipaddr: IP address to filter on
:param macaddr: MAC address to filter on
:return: List of the entries in the ARP table
CLI Example:
.. code-block:: bash
salt '*' net.arp
salt '*' net.arp macaddr='5c:5e:ab:da:3c:f0'
Example output:
.. code-block:: python
[
{
'interface' : 'MgmtEth0/RSP0/CPU0/0',
'mac' : '5c:5e:ab:da:3c:f0',
'ip' : '172.17.17.1',
'age' : 1454496274.84
},
{
'interface': 'MgmtEth0/RSP0/CPU0/0',
'mac' : '66:0e:94:96:e0:ff',
'ip' : '172.17.17.2',
'age' : 1435641582.49
}
]
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_arp_table',
**{
}
)
if not proxy_output.get('result'):
return proxy_output
arp_table = proxy_output.get('out')
if interface:
arp_table = _filter_list(arp_table, 'interface', interface)
if ipaddr:
arp_table = _filter_list(arp_table, 'ip', ipaddr)
if macaddr:
arp_table = _filter_list(arp_table, 'mac', macaddr)
proxy_output.update({
'out': arp_table
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def ipaddrs(**kwargs): # pylint: disable=unused-argument
'''
Returns IP addresses configured on the device.
:return: A dictionary with the IPv4 and IPv6 addresses of the interfaces.
Returns all configured IP addresses on all interfaces as a dictionary
of dictionaries. Keys of the main dictionary represent the name of the
interface. Values of the main dictionary represent are dictionaries
that may consist of two keys 'ipv4' and 'ipv6' (one, both or none)
which are themselvs dictionaries with the IP addresses as keys.
CLI Example:
.. code-block:: bash
salt '*' net.ipaddrs
Example output:
.. code-block:: python
{
'FastEthernet8': {
'ipv4': {
'10.66.43.169': {
'prefix_length': 22
}
}
},
'Loopback555': {
'ipv4': {
'192.168.1.1': {
'prefix_length': 24
}
},
'ipv6': {
'1::1': {
'prefix_length': 64
},
'2001:DB8:1::1': {
'prefix_length': 64
},
'FE80::3': {
'prefix_length': 'N/A'
}
}
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_interfaces_ip',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def interfaces(**kwargs): # pylint: disable=unused-argument
'''
Returns details of the interfaces on the device.
:return: Returns a dictionary of dictionaries. The keys for the first
dictionary will be the interfaces in the devices.
CLI Example:
.. code-block:: bash
salt '*' net.interfaces
Example output:
.. code-block:: python
{
'Management1': {
'is_up': False,
'is_enabled': False,
'description': '',
'last_flapped': -1,
'speed': 1000,
'mac_address': 'dead:beef:dead',
},
'Ethernet1':{
'is_up': True,
'is_enabled': True,
'description': 'foo',
'last_flapped': 1429978575.1554043,
'speed': 1000,
'mac_address': 'beef:dead:beef',
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_interfaces',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def lldp(interface='', **kwargs): # pylint: disable=unused-argument
'''
Returns a detailed view of the LLDP neighbors.
:param interface: interface name to filter on
:return: A dictionary with the LLDL neighbors. The keys are the
interfaces with LLDP activated on.
CLI Example:
.. code-block:: bash
salt '*' net.lldp
salt '*' net.lldp interface='TenGigE0/0/0/8'
Example output:
.. code-block:: python
{
'TenGigE0/0/0/8': [
{
'parent_interface': 'Bundle-Ether8',
'interface_description': 'TenGigE0/0/0/8',
'remote_chassis_id': '8c60.4f69.e96c',
'remote_system_name': 'switch',
'remote_port': 'Eth2/2/1',
'remote_port_description': 'Ethernet2/2/1',
'remote_system_description': 'Cisco Nexus Operating System (NX-OS) Software 7.1(0)N1(1a)
TAC support: http://www.cisco.com/tac
Copyright (c) 2002-2015, Cisco Systems, Inc. All rights reserved.',
'remote_system_capab': 'B, R',
'remote_system_enable_capab': 'B'
}
]
}
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_lldp_neighbors_detail',
**{
}
)
if not proxy_output.get('result'):
return proxy_output
lldp_neighbors = proxy_output.get('out')
if interface:
lldp_neighbors = {interface: lldp_neighbors.get(interface)}
proxy_output.update({
'out': lldp_neighbors
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def mac(address='', interface='', vlan=0, **kwargs): # pylint: disable=unused-argument
'''
Returns the MAC Address Table on the device.
:param address: MAC address to filter on
:param interface: Interface name to filter on
:param vlan: VLAN identifier
:return: A list of dictionaries representing the entries in the MAC Address Table
CLI Example:
.. code-block:: bash
salt '*' net.mac
salt '*' net.mac vlan=10
Example output:
.. code-block:: python
[
{
'mac' : '00:1c:58:29:4a:71',
'interface' : 'xe-3/0/2',
'static' : False,
'active' : True,
'moves' : 1,
'vlan' : 10,
'last_move' : 1454417742.58
},
{
'mac' : '8c:60:4f:58:e1:c1',
'interface' : 'xe-1/0/1',
'static' : False,
'active' : True,
'moves' : 2,
'vlan' : 42,
'last_move' : 1453191948.11
}
]
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_mac_address_table',
**{
}
)
if not proxy_output.get('result'):
# if negative, leave the output unchanged
return proxy_output
mac_address_table = proxy_output.get('out')
if vlan and isinstance(vlan, int):
mac_address_table = _filter_list(mac_address_table, 'vlan', vlan)
if address:
mac_address_table = _filter_list(mac_address_table, 'mac', address)
if interface:
mac_address_table = _filter_list(mac_address_table, 'interface', interface)
proxy_output.update({
'out': mac_address_table
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def config(source=None, **kwargs): # pylint: disable=unused-argument
'''
.. versionadded:: 2017.7.0
Return the whole configuration of the network device. By default, it will
return all possible configuration sources supported by the network device.
At most, there will be:
- running config
- startup config
- candidate config
To return only one of the configurations, you can use the ``source``
argument.
source
Which configuration type you want to display, default is all of them.
Options:
- running
- candidate
- startup
:return:
The object returned is a dictionary with the following keys:
- running (string): Representation of the native running configuration.
- candidate (string): Representation of the native candidate configuration.
If the device doesn't differentiate between running and startup
configuration this will an empty string.
- startup (string): Representation of the native startup configuration.
If the device doesn't differentiate between running and startup
configuration this will an empty string.
CLI Example:
.. code-block:: bash
salt '*' net.config
salt '*' net.config source=candidate
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_config',
**{
'retrieve': source
}
)
@salt.utils.napalm.proxy_napalm_wrap
def optics(**kwargs): # pylint: disable=unused-argument
'''
.. versionadded:: 2017.7.0
Fetches the power usage on the various transceivers installed
on the network device (in dBm), and returns a view that conforms with the
OpenConfig model openconfig-platform-transceiver.yang.
:return:
Returns a dictionary where the keys are as listed below:
* intf_name (unicode)
* physical_channels
* channels (list of dicts)
* index (int)
* state
* input_power
* instant (float)
* avg (float)
* min (float)
* max (float)
* output_power
* instant (float)
* avg (float)
* min (float)
* max (float)
* laser_bias_current
* instant (float)
* avg (float)
* min (float)
* max (float)
CLI Example:
.. code-block:: bash
salt '*' net.optics
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_optics',
**{
}
)
# <---- Call NAPALM getters --------------------------------------------------------------------------------------------
# ----- Configuration specific functions ------------------------------------------------------------------------------>
@salt.utils.napalm.proxy_napalm_wrap
def load_config(filename=None,
text=None,
test=False,
commit=True,
debug=False,
replace=False,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
commit_jid=None,
inherit_napalm_device=None,
saltenv='base',
**kwargs): # pylint: disable=unused-argument
'''
Applies configuration changes on the device. It can be loaded from a file or from inline string.
If you send both a filename and a string containing the configuration, the file has higher precedence.
By default this function will commit the changes. If there are no changes, it does not commit and
the flag ``already_configured`` will be set as ``True`` to point this out.
To avoid committing the configuration, set the argument ``test`` to ``True`` and will discard (dry run).
To keep the changes but not commit, set ``commit`` to ``False``.
To replace the config, set ``replace`` to ``True``.
filename
Path to the file containing the desired configuration.
This can be specified using the absolute path to the file,
or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
.. versionchanged:: 2018.3.0
text
String containing the desired configuration.
This argument is ignored when ``filename`` is specified.
test: False
Dry run? If set as ``True``, will apply the config, discard and return the changes. Default: ``False``
and will commit the changes on the device.
commit: True
Commit? Default: ``True``.
debug: False
Debug mode. Will insert a new key under the output dictionary, as ``loaded_config`` containing the raw
configuration loaded on the device.
.. versionadded:: 2016.11.2
replace: False
Load and replace the configuration. Default: ``False``.
.. versionadded:: 2016.11.2
commit_in: ``None``
Commit the changes in a specific number of minutes / hours. Example of
accepted formats: ``5`` (commit in 5 minutes), ``2m`` (commit in 2
minutes), ``1h`` (commit the changes in 1 hour)`, ``5h30m`` (commit
the changes in 5 hours and 30 minutes).
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
commit_at: ``None``
Commit the changes at a specific time. Example of accepted formats:
``1am`` (will commit the changes at the next 1AM), ``13:20`` (will
commit at 13:20), ``1:20am``, etc.
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
revert_in: ``None``
Commit and revert the changes in a specific number of minutes / hours.
Example of accepted formats: ``5`` (revert in 5 minutes), ``2m`` (revert
in 2 minutes), ``1h`` (revert the changes in 1 hour)`, ``5h30m`` (revert
the changes in 5 hours and 30 minutes).
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
revert_at: ``None``
Commit and revert the changes at a specific time. Example of accepted
formats: ``1am`` (will commit and revert the changes at the next 1AM),
``13:20`` (will commit and revert at 13:20), ``1:20am``, etc.
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
saltenv: ``base``
Specifies the Salt environment name.
.. versionadded:: 2018.3.0
:return: a dictionary having the following keys:
* result (bool): if the config was applied successfully. It is ``False`` only in case of failure. In case \
there are no changes to be applied and successfully performs all operations it is still ``True`` and so will be \
the ``already_configured`` flag (example below)
* comment (str): a message for the user
* already_configured (bool): flag to check if there were no changes applied
* loaded_config (str): the configuration loaded on the device. Requires ``debug`` to be set as ``True``
* diff (str): returns the config changes applied
CLI Example:
.. code-block:: bash
salt '*' net.load_config text='ntp peer 192.168.0.1'
salt '*' net.load_config filename='/absolute/path/to/your/file'
salt '*' net.load_config filename='/absolute/path/to/your/file' test=True
salt '*' net.load_config filename='/absolute/path/to/your/file' commit=False
Example output:
.. code-block:: python
{
'comment': 'Configuration discarded.',
'already_configured': False,
'result': True,
'diff': '[edit interfaces xe-0/0/5]+ description "Adding a description";'
}
'''
fun = 'load_merge_candidate'
if replace:
fun = 'load_replace_candidate'
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
if filename:
text = __salt__['cp.get_file_str'](filename, saltenv=saltenv)
if text is False:
# When using salt:// or https://, if the resource is not available,
# it will either raise an exception, or return False.
ret = {
'result': False,
'out': None
}
ret['comment'] = 'Unable to read from {}. Please specify a valid file or text.'.format(filename)
log.error(ret['comment'])
return ret
if commit_jid:
# When the commit_jid argument is passed, it probably is a scheduled
# commit to be executed, and filename is a temporary file which
# can be removed after reading it.
salt.utils.files.safe_rm(filename)
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
fun,
**{
'config': text
}
)
return _config_logic(napalm_device, # pylint: disable=undefined-variable
_loaded,
test=test,
debug=debug,
replace=replace,
commit_config=commit,
loaded_config=text,
commit_at=commit_at,
commit_in=commit_in,
revert_in=revert_in,
revert_at=revert_at,
commit_jid=commit_jid,
**kwargs)
@salt.utils.napalm.proxy_napalm_wrap
@salt.utils.napalm.proxy_napalm_wrap
def commit(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Commits the configuration changes made on the network device.
CLI Example:
.. code-block:: bash
salt '*' net.commit
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'commit_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def discard_config(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
"""
Discards the changes applied.
CLI Example:
.. code-block:: bash
salt '*' net.discard_config
"""
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'discard_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def compare_config(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Returns the difference between the running config and the candidate config.
CLI Example:
.. code-block:: bash
salt '*' net.compare_config
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'compare_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def rollback(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Rollbacks the configuration.
CLI Example:
.. code-block:: bash
salt '*' net.rollback
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'rollback',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def config_changed(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Will prompt if the configuration has been changed.
:return: A tuple with a boolean that specifies if the config was changed on the device.\
And a string that provides more details of the reason why the configuration was not changed.
CLI Example:
.. code-block:: bash
salt '*' net.config_changed
'''
is_config_changed = False
reason = ''
try_compare = compare_config(inherit_napalm_device=napalm_device) # pylint: disable=undefined-variable
if try_compare.get('result'):
if try_compare.get('out'):
is_config_changed = True
else:
reason = 'Configuration was not changed on the device.'
else:
reason = try_compare.get('comment')
return is_config_changed, reason
@salt.utils.napalm.proxy_napalm_wrap
def config_control(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Will check if the configuration was changed.
If differences found, will try to commit.
In case commit unsuccessful, will try to rollback.
:return: A tuple with a boolean that specifies if the config was changed/committed/rollbacked on the device.\
And a string that provides more details of the reason why the configuration was not committed properly.
CLI Example:
.. code-block:: bash
salt '*' net.config_control
'''
result = True
comment = ''
changed, not_changed_rsn = config_changed(inherit_napalm_device=napalm_device) # pylint: disable=undefined-variable
if not changed:
return (changed, not_changed_rsn)
# config changed, thus let's try to commit
try_commit = commit()
if not try_commit.get('result'):
result = False
comment = 'Unable to commit the changes: {reason}.\n\
Will try to rollback now!'.format(
reason=try_commit.get('comment')
)
try_rollback = rollback()
if not try_rollback.get('result'):
comment += '\nCannot rollback! {reason}'.format(
reason=try_rollback.get('comment')
)
return result, comment
def cancel_commit(jid):
'''
.. versionadded:: 2019.2.0
Cancel a commit scheduled to be executed via the ``commit_in`` and
``commit_at`` arguments from the
:py:func:`net.load_template <salt.modules.napalm_network.load_template>` or
:py:func:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit ID is displayed when the commit is scheduled
via the functions named above.
CLI Example:
.. code-block:: bash
salt '*' net.cancel_commit 20180726083540640360
'''
job_name = '__napalm_commit_{}'.format(jid)
removed = __salt__['schedule.delete'](job_name)
if removed['result']:
saved = __salt__['schedule.save']()
removed['comment'] = 'Commit #{jid} cancelled.'.format(jid=jid)
else:
removed['comment'] = 'Unable to find commit #{jid}.'.format(jid=jid)
return removed
def confirm_commit(jid):
'''
.. versionadded:: 2019.2.0
Confirm a commit scheduled to be reverted via the ``revert_in`` and
``revert_at`` arguments from the
:mod:`net.load_template <salt.modules.napalm_network.load_template>` or
:mod:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit ID is displayed when the commit confirmed
is scheduled via the functions named above.
CLI Example:
.. code-block:: bash
salt '*' net.confirm_commit 20180726083540640360
'''
if __grains__['os'] == 'junos':
# Confirm the commit, by committing (i.e., invoking the RPC call)
confirmed = __salt__['napalm.junos_commit']()
confirmed['result'] = confirmed.pop('out')
confirmed['comment'] = confirmed.pop('message')
else:
confirmed = cancel_commit(jid)
if confirmed['result']:
confirmed['comment'] = 'Commit #{jid} confirmed.'.format(jid=jid)
return confirmed
def save_config(source=None,
path=None):
'''
.. versionadded:: 2019.2.0
Save the configuration to a file on the local file system.
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``,
``startup``. Default: ``running``.
path
Absolute path to file where to save the configuration.
To push the files to the Master, use
:mod:`cp.push <salt.modules.cp.push>` Execution function.
CLI Example:
.. code-block:: bash
salt '*' net.save_config source=running
'''
if not source:
source = 'running'
if not path:
path = salt.utils.files.mkstemp()
running_config = __salt__['net.config'](source=source)
if not running_config or not running_config['result']:
log.error('Unable to retrieve the config')
return running_config
with salt.utils.files.fopen(path, 'w') as fh_:
fh_.write(running_config['out'][source])
return {
'result': True,
'out': path,
'comment': '{source} config saved to {path}'.format(source=source, path=path)
}
def replace_pattern(pattern,
repl,
count=0,
flags=8,
bufsize=1,
append_if_not_found=False,
prepend_if_not_found=False,
not_found_content=None,
search_only=False,
show_changes=True,
backslash_literal=False,
source=None,
path=None,
test=False,
replace=True,
debug=False,
commit=True):
'''
.. versionadded:: 2019.2.0
Replace occurrences of a pattern in the configuration source. If
``show_changes`` is ``True``, then a diff of what changed will be returned,
otherwise a ``True`` will be returned when changes are made, and ``False``
when no changes are made.
This is a pure Python implementation that wraps Python's :py:func:`~re.sub`.
pattern
A regular expression, to be matched using Python's
:py:func:`~re.search`.
repl
The replacement text.
count: ``0``
Maximum number of pattern occurrences to be replaced. If count is a
positive integer ``n``, only ``n`` occurrences will be replaced,
otherwise all occurrences will be replaced.
flags (list or int): ``8``
A list of flags defined in the ``re`` module documentation from the
Python standard library. Each list item should be a string that will
correlate to the human-friendly flag name. E.g., ``['IGNORECASE',
'MULTILINE']``. Optionally, ``flags`` may be an int, with a value
corresponding to the XOR (``|``) of all the desired flags. Defaults to
8 (which supports 'MULTILINE').
bufsize (int or str): ``1``
How much of the configuration to buffer into memory at once. The
default value ``1`` processes one line at a time. The special value
``file`` may be specified which will read the entire file into memory
before processing.
append_if_not_found: ``False``
If set to ``True``, and pattern is not found, then the content will be
appended to the file.
prepend_if_not_found: ``False``
If set to ``True`` and pattern is not found, then the content will be
prepended to the file.
not_found_content
Content to use for append/prepend if not found. If None (default), uses
``repl``. Useful when ``repl`` uses references to group in pattern.
search_only: ``False``
If set to true, this no changes will be performed on the file, and this
function will simply return ``True`` if the pattern was matched, and
``False`` if not.
show_changes: ``True``
If ``True``, return a diff of changes made. Otherwise, return ``True``
if changes were made, and ``False`` if not.
backslash_literal: ``False``
Interpret backslashes as literal backslashes for the repl and not
escape characters. This will help when using append/prepend so that
the backslashes are not interpreted for the repl on the second run of
the state.
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path
Save the temporary configuration to a specific path, then read from
there.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' net.replace_pattern "bind-address\\s*=" "bind-address:"
CLI Example:
.. code-block:: bash
salt '*' net.replace_pattern PREFIX-LIST_NAME new-prefix-list-name
salt '*' net.replace_pattern bgp-group-name new-bgp-group-name count=1
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
replace_pattern = __salt__['file.replace'](path,
pattern,
repl,
count=count,
flags=flags,
bufsize=bufsize,
append_if_not_found=append_if_not_found,
prepend_if_not_found=prepend_if_not_found,
not_found_content=not_found_content,
search_only=search_only,
show_changes=show_changes,
backslash_literal=backslash_literal)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
def blockreplace(marker_start,
marker_end,
content='',
append_if_not_found=False,
prepend_if_not_found=False,
show_changes=True,
append_newline=False,
source='running',
path=None,
test=False,
commit=True,
debug=False,
replace=True):
'''
.. versionadded:: 2019.2.0
Replace content of the configuration source, delimited by the line markers.
A block of content delimited by comments can help you manage several lines
without worrying about old entries removal.
marker_start
The line content identifying a line as the start of the content block.
Note that the whole line containing this marker will be considered,
so whitespace or extra content before or after the marker is included
in final output.
marker_end
The line content identifying a line as the end of the content block.
Note that the whole line containing this marker will be considered,
so whitespace or extra content before or after the marker is included
in final output.
content
The content to be used between the two lines identified by
``marker_start`` and ``marker_stop``.
append_if_not_found: ``False``
If markers are not found and set to True then, the markers and content
will be appended to the file.
prepend_if_not_found: ``False``
If markers are not found and set to True then, the markers and content
will be prepended to the file.
append_newline: ``False``
Controls whether or not a newline is appended to the content block.
If the value of this argument is ``True`` then a newline will be added
to the content block. If it is ``False``, then a newline will not be
added to the content block. If it is ``None`` then a newline will only
be added to the content block if it does not already end in a newline.
show_changes: ``True``
Controls how changes are presented. If ``True``, this function will
return the of the changes made.
If ``False``, then it will return a boolean (``True`` if any changes
were made, otherwise False).
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path: ``None``
Save the temporary configuration to a specific path, then read from
there. This argument is optional, can be used when you prefers a
particular location of the temporary file.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
CLI Example:
.. code-block:: bash
salt '*' net.blockreplace 'ntp' 'interface' ''
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
replace_pattern = __salt__['file.blockreplace'](path,
marker_start=marker_start,
marker_end=marker_end,
content=content,
append_if_not_found=append_if_not_found,
prepend_if_not_found=prepend_if_not_found,
show_changes=show_changes,
append_newline=append_newline)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
def patch(patchfile,
options='',
saltenv='base',
source_hash=None,
show_changes=True,
source='running',
path=None,
test=False,
commit=True,
debug=False,
replace=True):
'''
.. versionadded:: 2019.2.0
Apply a patch to the configuration source, and load the result into the
running config of the device.
patchfile
A patch file to apply to the configuration source.
options
Options to pass to patch.
source_hash
If the patch file (specified via the ``patchfile`` argument) is an
HTTP(S) or FTP URL and the file exists in the minion's file cache, this
option can be passed to keep the minion from re-downloading the file if
the cached copy matches the specified hash.
show_changes: ``True``
Controls how changes are presented. If ``True``, this function will
return the of the changes made.
If ``False``, then it will return a boolean (``True`` if any changes
were made, otherwise False).
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path: ``None``
Save the temporary configuration to a specific path, then read from
there. This argument is optional, can the user prefers a particular
location of the temporary file.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
CLI Example:
.. code-block:: bash
salt '*' net.patch https://example.com/running_config.patch
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
patchfile_cache = __salt__['cp.cache_file'](patchfile)
if patchfile_cache is False:
return {
'out': None,
'result': False,
'comment': 'The file "{}" does not exist.'.format(patchfile)
}
replace_pattern = __salt__['file.patch'](path,
patchfile_cache,
options=options)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
# <---- Configuration specific functions -------------------------------------------------------------------------------
|
saltstack/salt
|
salt/modules/napalm_network.py
|
config_changed
|
python
|
def config_changed(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Will prompt if the configuration has been changed.
:return: A tuple with a boolean that specifies if the config was changed on the device.\
And a string that provides more details of the reason why the configuration was not changed.
CLI Example:
.. code-block:: bash
salt '*' net.config_changed
'''
is_config_changed = False
reason = ''
try_compare = compare_config(inherit_napalm_device=napalm_device) # pylint: disable=undefined-variable
if try_compare.get('result'):
if try_compare.get('out'):
is_config_changed = True
else:
reason = 'Configuration was not changed on the device.'
else:
reason = try_compare.get('comment')
return is_config_changed, reason
|
Will prompt if the configuration has been changed.
:return: A tuple with a boolean that specifies if the config was changed on the device.\
And a string that provides more details of the reason why the configuration was not changed.
CLI Example:
.. code-block:: bash
salt '*' net.config_changed
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_network.py#L2166-L2193
| null |
# -*- coding: utf-8 -*-
'''
NAPALM Network
==============
Basic methods for interaction with the network device through the virtual proxy 'napalm'.
:codeauthor: Mircea Ulinic <mircea@cloudflare.com> & Jerome Fleury <jf@cloudflare.com>
:maturity: new
:depends: napalm
:platform: unix
Dependencies
------------
- :mod:`napalm proxy minion <salt.proxy.napalm>`
.. versionadded:: 2016.11.0
.. versionchanged:: 2017.7.0
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import time
import logging
import datetime
log = logging.getLogger(__name__)
# Import Salt libs
from salt.ext import six
import salt.utils.files
import salt.utils.napalm
import salt.utils.versions
import salt.utils.templates
# Import 3rd-party libs
try:
import jxmlease # pylint: disable=unused-import
HAS_JXMLEASE = True
except ImportError:
HAS_JXMLEASE = False
# ----------------------------------------------------------------------------------------------------------------------
# module properties
# ----------------------------------------------------------------------------------------------------------------------
__virtualname__ = 'net'
__proxyenabled__ = ['*']
__virtual_aliases__ = ('napalm_net',)
# uses NAPALM-based proxy to interact with network devices
# ----------------------------------------------------------------------------------------------------------------------
# property functions
# ----------------------------------------------------------------------------------------------------------------------
def __virtual__():
'''
NAPALM library must be installed for this module to work and run in a (proxy) minion.
'''
return salt.utils.napalm.virtual(__opts__, __virtualname__, __file__)
# ----------------------------------------------------------------------------------------------------------------------
# helper functions -- will not be exported
# ----------------------------------------------------------------------------------------------------------------------
def _filter_list(input_list, search_key, search_value):
'''
Filters a list of dictionary by a set of key-value pair.
:param input_list: is a list of dictionaries
:param search_key: is the key we are looking for
:param search_value: is the value we are looking for the key specified in search_key
:return: filered list of dictionaries
'''
output_list = list()
for dictionary in input_list:
if dictionary.get(search_key) == search_value:
output_list.append(dictionary)
return output_list
def _filter_dict(input_dict, search_key, search_value):
'''
Filters a dictionary of dictionaries by a key-value pair.
:param input_dict: is a dictionary whose values are lists of dictionaries
:param search_key: is the key in the leaf dictionaries
:param search_values: is the value in the leaf dictionaries
:return: filtered dictionary
'''
output_dict = dict()
for key, key_list in six.iteritems(input_dict):
key_list_filtered = _filter_list(key_list, search_key, search_value)
if key_list_filtered:
output_dict[key] = key_list_filtered
return output_dict
def _safe_commit_config(loaded_result, napalm_device):
_commit = commit(inherit_napalm_device=napalm_device) # calls the function commit, defined below
if not _commit.get('result', False):
# if unable to commit
loaded_result['comment'] += _commit['comment'] if _commit.get('comment') else 'Unable to commit.'
loaded_result['result'] = False
# unable to commit, something went wrong
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
return _commit
def _safe_dicard_config(loaded_result, napalm_device):
'''
'''
log.debug('Discarding the config')
log.debug(loaded_result)
_discarded = discard_config(inherit_napalm_device=napalm_device)
if not _discarded.get('result', False):
loaded_result['comment'] += _discarded['comment'] if _discarded.get('comment') \
else 'Unable to discard config.'
loaded_result['result'] = False
# make sure it notifies
# that something went wrong
_explicit_close(napalm_device)
__context__['retcode'] = 1
return loaded_result
return _discarded
def _explicit_close(napalm_device):
'''
Will explicily close the config session with the network device,
when running in a now-always-alive proxy minion or regular minion.
This helper must be used in configuration-related functions,
as the session is preserved and not closed before making any changes.
'''
if salt.utils.napalm.not_always_alive(__opts__):
# force closing the configuration session
# when running in a non-always-alive proxy
# or regular minion
try:
napalm_device['DRIVER'].close()
except Exception as err:
log.error('Unable to close the temp connection with the device:')
log.error(err)
log.error('Please report.')
def _config_logic(napalm_device,
loaded_result,
test=False,
debug=False,
replace=False,
commit_config=True,
loaded_config=None,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
commit_jid=None,
**kwargs):
'''
Builds the config logic for `load_config` and `load_template` functions.
'''
# As the Salt logic is built around independent events
# when it comes to configuration changes in the
# candidate DB on the network devices, we need to
# make sure we're using the same session.
# Hence, we need to pass the same object around.
# the napalm_device object is inherited from
# the load_config or load_template functions
# and forwarded to compare, discard, commit etc.
# then the decorator will make sure that
# if not proxy (when the connection is always alive)
# and the `inherit_napalm_device` is set,
# `napalm_device` will be overridden.
# See `salt.utils.napalm.proxy_napalm_wrap` decorator.
current_jid = kwargs.get('__pub_jid')
if not current_jid:
current_jid = '{0:%Y%m%d%H%M%S%f}'.format(datetime.datetime.now())
loaded_result['already_configured'] = False
loaded_result['loaded_config'] = ''
if debug:
loaded_result['loaded_config'] = loaded_config
_compare = compare_config(inherit_napalm_device=napalm_device)
if _compare.get('result', False):
loaded_result['diff'] = _compare.get('out')
loaded_result.pop('out', '') # not needed
else:
loaded_result['diff'] = None
loaded_result['result'] = False
loaded_result['comment'] = _compare.get('comment')
__context__['retcode'] = 1
return loaded_result
_loaded_res = loaded_result.get('result', False)
if not _loaded_res or test:
# if unable to load the config (errors / warnings)
# or in testing mode,
# will discard the config
if loaded_result['comment']:
loaded_result['comment'] += '\n'
if not loaded_result.get('diff', ''):
loaded_result['already_configured'] = True
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
loaded_result['comment'] += 'Configuration discarded.'
# loaded_result['result'] = False not necessary
# as the result can be true when test=True
_explicit_close(napalm_device)
if not loaded_result['result']:
__context__['retcode'] = 1
return loaded_result
if not test and commit_config:
# if not in testing mode and trying to commit
if commit_jid:
log.info('Committing the JID: %s', str(commit_jid))
removed = cancel_commit(commit_jid)
log.debug('Cleaned up the commit from the schedule')
log.debug(removed['comment'])
if loaded_result.get('diff', ''):
# if not testing mode
# and also the user wants to commit (default)
# and there are changes to commit
if commit_in or commit_at:
commit_time = __utils__['timeutil.get_time_at'](time_in=commit_in,
time_at=commit_in)
# schedule job
scheduled_job_name = '__napalm_commit_{}'.format(current_jid)
temp_file = salt.utils.files.mkstemp()
with salt.utils.files.fopen(temp_file, 'w') as fp_:
fp_.write(loaded_config)
scheduled = __salt__['schedule.add'](scheduled_job_name,
function='net.load_config',
job_kwargs={
'filename': temp_file,
'commit_jid': current_jid,
'replace': replace
},
once=commit_time)
log.debug('Scheduling job')
log.debug(scheduled)
saved = __salt__['schedule.save']() # ensure the schedule is
# persistent cross Minion restart
discarded = _safe_dicard_config(loaded_result, napalm_device)
# discard the changes
if not discarded['result']:
discarded['comment'] += ('Scheduled the job to be executed at {schedule_ts}, '
'but was unable to discard the config: \n').format(schedule_ts=commit_time)
return discarded
loaded_result['comment'] = ('Changes discarded for now, and scheduled commit at: {schedule_ts}.\n'
'The commit ID is: {current_jid}.\n'
'To discard this commit, you can execute: \n\n'
'salt {min_id} net.cancel_commit {current_jid}').format(schedule_ts=commit_time,
min_id=__opts__['id'],
current_jid=current_jid)
loaded_result['commit_id'] = current_jid
return loaded_result
log.debug('About to commit:')
log.debug(loaded_result['diff'])
if revert_in or revert_at:
revert_time = __utils__['timeutil.get_time_at'](time_in=revert_in,
time_at=revert_at)
if __grains__['os'] == 'junos':
if not HAS_JXMLEASE:
loaded_result['comment'] = ('This feature requires the library jxmlease to be installed.\n'
'To install, please execute: ``pip install jxmlease``.')
loaded_result['result'] = False
return loaded_result
timestamp_at = __utils__['timeutil.get_timestamp_at'](time_in=revert_in,
time_at=revert_at)
minutes = int((timestamp_at - time.time())/60)
_comm = __salt__['napalm.junos_commit'](confirm=minutes)
if not _comm['out']:
# If unable to commit confirm, should try to bail out
loaded_result['comment'] = 'Unable to commit confirm: {}'.format(_comm['message'])
loaded_result['result'] = False
# But before exiting, we must gracefully discard the config
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
else:
temp_file = salt.utils.files.mkstemp()
running_config = __salt__['net.config'](source='running')['out']['running']
with salt.utils.files.fopen(temp_file, 'w') as fp_:
fp_.write(running_config)
committed = _safe_commit_config(loaded_result, napalm_device)
if not committed['result']:
# If unable to commit, dicard the config (which is
# already done by the _safe_commit_config function), and
# return with the command and other details.
return loaded_result
scheduled_job_name = '__napalm_commit_{}'.format(current_jid)
scheduled = __salt__['schedule.add'](scheduled_job_name,
function='net.load_config',
job_kwargs={
'filename': temp_file,
'commit_jid': current_jid,
'replace': True
},
once=revert_time)
log.debug('Scheduling commit confirmed')
log.debug(scheduled)
saved = __salt__['schedule.save']()
loaded_result['comment'] = ('The commit ID is: {current_jid}.\n'
'This commit will be reverted at: {schedule_ts}, unless confirmed.\n'
'To confirm the commit and avoid reverting, you can execute:\n\n'
'salt {min_id} net.confirm_commit {current_jid}').format(schedule_ts=revert_time,
min_id=__opts__['id'],
current_jid=current_jid)
loaded_result['commit_id'] = current_jid
return loaded_result
committed = _safe_commit_config(loaded_result, napalm_device)
if not committed['result']:
return loaded_result
else:
# would like to commit, but there's no change
# need to call discard_config() to release the config DB
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
loaded_result['already_configured'] = True
loaded_result['comment'] = 'Already configured.'
_explicit_close(napalm_device)
if not loaded_result['result']:
__context__['retcode'] = 1
return loaded_result
# ----------------------------------------------------------------------------------------------------------------------
# callable functions
# ----------------------------------------------------------------------------------------------------------------------
@salt.utils.napalm.proxy_napalm_wrap
def connected(**kwargs): # pylint: disable=unused-argument
'''
Specifies if the connection to the device succeeded.
CLI Example:
.. code-block:: bash
salt '*' net.connected
'''
return {
'out': napalm_device.get('UP', False) # pylint: disable=undefined-variable
}
@salt.utils.napalm.proxy_napalm_wrap
def facts(**kwargs): # pylint: disable=unused-argument
'''
Returns characteristics of the network device.
:return: a dictionary with the following keys:
* uptime - Uptime of the device in seconds.
* vendor - Manufacturer of the device.
* model - Device model.
* hostname - Hostname of the device
* fqdn - Fqdn of the device
* os_version - String with the OS version running on the device.
* serial_number - Serial number of the device
* interface_list - List of the interfaces of the device
CLI Example:
.. code-block:: bash
salt '*' net.facts
Example output:
.. code-block:: python
{
'os_version': '13.3R6.5',
'uptime': 10117140,
'interface_list': [
'lc-0/0/0',
'pfe-0/0/0',
'pfh-0/0/0',
'xe-0/0/0',
'xe-0/0/1',
'xe-0/0/2',
'xe-0/0/3',
'gr-0/0/10',
'ip-0/0/10'
],
'vendor': 'Juniper',
'serial_number': 'JN131356FBFA',
'model': 'MX480',
'hostname': 're0.edge05.syd01',
'fqdn': 're0.edge05.syd01'
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_facts',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def environment(**kwargs): # pylint: disable=unused-argument
'''
Returns the environment of the device.
CLI Example:
.. code-block:: bash
salt '*' net.environment
Example output:
.. code-block:: python
{
'fans': {
'Bottom Rear Fan': {
'status': True
},
'Bottom Middle Fan': {
'status': True
},
'Top Middle Fan': {
'status': True
},
'Bottom Front Fan': {
'status': True
},
'Top Front Fan': {
'status': True
},
'Top Rear Fan': {
'status': True
}
},
'memory': {
'available_ram': 16349,
'used_ram': 4934
},
'temperature': {
'FPC 0 Exhaust A': {
'is_alert': False,
'temperature': 35.0,
'is_critical': False
}
},
'cpu': {
'1': {
'%usage': 19.0
},
'0': {
'%usage': 35.0
}
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_environment',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def cli(*commands, **kwargs): # pylint: disable=unused-argument
'''
Returns a dictionary with the raw output of all commands passed as arguments.
commands
List of commands to be executed on the device.
textfsm_parse: ``False``
Try parsing the outputs using the TextFSM templates.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``napalm_cli_textfsm_parse``.
textfsm_path
The path where the TextFSM templates can be found. This option implies
the usage of the TextFSM index file.
``textfsm_path`` can be either absolute path on the server,
either specified using the following URL mschemes: ``file://``,
``salt://``, ``http://``, ``https://``, ``ftp://``,
``s3://``, ``swift://``.
.. versionadded:: 2018.3.0
.. note::
This needs to be a directory with a flat structure, having an
index file (whose name can be specified using the ``index_file`` option)
and a number of TextFSM templates.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_path``.
textfsm_template
The path to a certain the TextFSM template.
This can be specified using the absolute path
to the file, or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
.. versionadded:: 2018.3.0
textfsm_template_dict
A dictionary with the mapping between a command
and the corresponding TextFSM path to use to extract the data.
The TextFSM paths can be specified as in ``textfsm_template``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``napalm_cli_textfsm_template_dict``.
platform_grain_name: ``os``
The name of the grain used to identify the platform name
in the TextFSM index file. Default: ``os``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_grain``.
platform_column_name: ``Platform``
The column name used to identify the platform,
exactly as specified in the TextFSM index file.
Default: ``Platform``.
.. versionadded:: 2018.3.0
.. note::
This is field is case sensitive, make sure
to assign the correct value to this option,
exactly as defined in the index file.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_column_name``.
index_file: ``index``
The name of the TextFSM index file, under the ``textfsm_path``. Default: ``index``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_index_file``.
saltenv: ``base``
Salt fileserver envrionment from which to retrieve the file.
Ignored if ``textfsm_path`` is not a ``salt://`` URL.
.. versionadded:: 2018.3.0
include_empty: ``False``
Include empty files under the ``textfsm_path``.
.. versionadded:: 2018.3.0
include_pat
Glob or regex to narrow down the files cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. versionadded:: 2018.3.0
exclude_pat
Glob or regex to exclude certain files from being cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. versionadded:: 2018.3.0
.. note::
If used with ``include_pat``, files matching this pattern will be
excluded from the subset of files defined by ``include_pat``.
CLI Example:
.. code-block:: bash
salt '*' net.cli "show version" "show chassis fan"
CLI Example with TextFSM template:
.. code-block:: bash
salt '*' net.cli textfsm_parse=True textfsm_path=salt://textfsm/
Example output:
.. code-block:: python
{
'show version and haiku': 'Hostname: re0.edge01.arn01
Model: mx480
Junos: 13.3R6.5
Help me, Obi-Wan
I just saw Episode Two
You're my only hope
',
'show chassis fan' : 'Item Status RPM Measurement
Top Rear Fan OK 3840 Spinning at intermediate-speed
Bottom Rear Fan OK 3840 Spinning at intermediate-speed
Top Middle Fan OK 3900 Spinning at intermediate-speed
Bottom Middle Fan OK 3840 Spinning at intermediate-speed
Top Front Fan OK 3810 Spinning at intermediate-speed
Bottom Front Fan OK 3840 Spinning at intermediate-speed
'
}
Example output with TextFSM parsing:
.. code-block:: json
{
"comment": "",
"result": true,
"out": {
"sh ver": [
{
"kernel": "9.1S3.5",
"documentation": "9.1S3.5",
"boot": "9.1S3.5",
"crypto": "9.1S3.5",
"chassis": "",
"routing": "9.1S3.5",
"base": "9.1S3.5",
"model": "mx960"
}
]
}
}
'''
raw_cli_outputs = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'cli',
**{
'commands': list(commands)
}
)
# thus we can display the output as is
# in case of errors, they'll be catched in the proxy
if not raw_cli_outputs['result']:
# Error -> dispaly the output as-is.
return raw_cli_outputs
textfsm_parse = kwargs.get('textfsm_parse') or __opts__.get('napalm_cli_textfsm_parse') or\
__pillar__.get('napalm_cli_textfsm_parse', False)
if not textfsm_parse:
# No TextFSM parsing required, return raw commands.
log.debug('No TextFSM parsing requested.')
return raw_cli_outputs
if 'textfsm.extract' not in __salt__ or 'textfsm.index' not in __salt__:
raw_cli_outputs['comment'] += 'Unable to process: is TextFSM installed?'
log.error(raw_cli_outputs['comment'])
return raw_cli_outputs
textfsm_template = kwargs.get('textfsm_template')
log.debug('textfsm_template: %s', textfsm_template)
textfsm_path = kwargs.get('textfsm_path') or __opts__.get('textfsm_path') or\
__pillar__.get('textfsm_path')
log.debug('textfsm_path: %s', textfsm_path)
textfsm_template_dict = kwargs.get('textfsm_template_dict') or __opts__.get('napalm_cli_textfsm_template_dict') or\
__pillar__.get('napalm_cli_textfsm_template_dict', {})
log.debug('TextFSM command-template mapping: %s', textfsm_template_dict)
index_file = kwargs.get('index_file') or __opts__.get('textfsm_index_file') or\
__pillar__.get('textfsm_index_file')
log.debug('index_file: %s', index_file)
platform_grain_name = kwargs.get('platform_grain_name') or __opts__.get('textfsm_platform_grain') or\
__pillar__.get('textfsm_platform_grain', 'os')
log.debug('platform_grain_name: %s', platform_grain_name)
platform_column_name = kwargs.get('platform_column_name') or __opts__.get('textfsm_platform_column_name') or\
__pillar__.get('textfsm_platform_column_name', 'Platform')
log.debug('platform_column_name: %s', platform_column_name)
saltenv = kwargs.get('saltenv', 'base')
include_empty = kwargs.get('include_empty', False)
include_pat = kwargs.get('include_pat')
exclude_pat = kwargs.get('exclude_pat')
processed_cli_outputs = {
'comment': raw_cli_outputs.get('comment', ''),
'result': raw_cli_outputs['result'],
'out': {}
}
log.debug('Starting to analyse the raw outputs')
for command in list(commands):
command_output = raw_cli_outputs['out'][command]
log.debug('Output from command: %s', command)
log.debug(command_output)
processed_command_output = None
if textfsm_path:
log.debug('Using the templates under %s', textfsm_path)
processed_cli_output = __salt__['textfsm.index'](command,
platform_grain_name=platform_grain_name,
platform_column_name=platform_column_name,
output=command_output.strip(),
textfsm_path=textfsm_path,
saltenv=saltenv,
include_empty=include_empty,
include_pat=include_pat,
exclude_pat=exclude_pat)
log.debug('Processed CLI output:')
log.debug(processed_cli_output)
if not processed_cli_output['result']:
log.debug('Apparently this didnt work, returnin the raw output')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {0}: {1}.'.format(command,
processed_cli_output['comment'])
log.error(processed_cli_outputs['comment'])
elif processed_cli_output['out']:
log.debug('All good, %s has a nice output!', command)
processed_command_output = processed_cli_output['out']
else:
comment = '''\nProcessing "{}" didn't fail, but didn't return anything either. Dumping raw.'''.format(
command)
processed_cli_outputs['comment'] += comment
log.error(comment)
processed_command_output = command_output
elif textfsm_template or command in textfsm_template_dict:
if command in textfsm_template_dict:
textfsm_template = textfsm_template_dict[command]
log.debug('Using %s to process the command: %s', textfsm_template, command)
processed_cli_output = __salt__['textfsm.extract'](textfsm_template,
raw_text=command_output,
saltenv=saltenv)
log.debug('Processed CLI output:')
log.debug(processed_cli_output)
if not processed_cli_output['result']:
log.debug('Apparently this didnt work, returning '
'the raw output')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {0}: {1}'.format(command,
processed_cli_output['comment'])
log.error(processed_cli_outputs['comment'])
elif processed_cli_output['out']:
log.debug('All good, %s has a nice output!', command)
processed_command_output = processed_cli_output['out']
else:
log.debug('Processing %s didnt fail, but didnt return'
' anything either. Dumping raw.', command)
processed_command_output = command_output
else:
log.error('No TextFSM template specified, or no TextFSM path defined')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {}.'.format(command)
processed_cli_outputs['out'][command] = processed_command_output
processed_cli_outputs['comment'] = processed_cli_outputs['comment'].strip()
return processed_cli_outputs
@salt.utils.napalm.proxy_napalm_wrap
def traceroute(destination, source=None, ttl=None, timeout=None, vrf=None, **kwargs): # pylint: disable=unused-argument
'''
Calls the method traceroute from the NAPALM driver object and returns a dictionary with the result of the traceroute
command executed on the device.
destination
Hostname or address of remote host
source
Source address to use in outgoing traceroute packets
ttl
IP maximum time-to-live value (or IPv6 maximum hop-limit value)
timeout
Number of seconds to wait for response (seconds)
vrf
VRF (routing instance) for traceroute attempt
.. versionadded:: 2016.11.4
CLI Example:
.. code-block:: bash
salt '*' net.traceroute 8.8.8.8
salt '*' net.traceroute 8.8.8.8 source=127.0.0.1 ttl=5 timeout=1
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'traceroute',
**{
'destination': destination,
'source': source,
'ttl': ttl,
'timeout': timeout,
'vrf': vrf
}
)
@salt.utils.napalm.proxy_napalm_wrap
def ping(destination, source=None, ttl=None, timeout=None, size=None, count=None, vrf=None, **kwargs): # pylint: disable=unused-argument
'''
Executes a ping on the network device and returns a dictionary as a result.
destination
Hostname or IP address of remote host
source
Source address of echo request
ttl
IP time-to-live value (IPv6 hop-limit value) (1..255 hops)
timeout
Maximum wait time after sending final packet (seconds)
size
Size of request packets (0..65468 bytes)
count
Number of ping requests to send (1..2000000000 packets)
vrf
VRF (routing instance) for ping attempt
.. versionadded:: 2016.11.4
CLI Example:
.. code-block:: bash
salt '*' net.ping 8.8.8.8
salt '*' net.ping 8.8.8.8 ttl=3 size=65468
salt '*' net.ping 8.8.8.8 source=127.0.0.1 timeout=1 count=100
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'ping',
**{
'destination': destination,
'source': source,
'ttl': ttl,
'timeout': timeout,
'size': size,
'count': count,
'vrf': vrf
}
)
@salt.utils.napalm.proxy_napalm_wrap
def arp(interface='', ipaddr='', macaddr='', **kwargs): # pylint: disable=unused-argument
'''
NAPALM returns a list of dictionaries with details of the ARP entries.
:param interface: interface name to filter on
:param ipaddr: IP address to filter on
:param macaddr: MAC address to filter on
:return: List of the entries in the ARP table
CLI Example:
.. code-block:: bash
salt '*' net.arp
salt '*' net.arp macaddr='5c:5e:ab:da:3c:f0'
Example output:
.. code-block:: python
[
{
'interface' : 'MgmtEth0/RSP0/CPU0/0',
'mac' : '5c:5e:ab:da:3c:f0',
'ip' : '172.17.17.1',
'age' : 1454496274.84
},
{
'interface': 'MgmtEth0/RSP0/CPU0/0',
'mac' : '66:0e:94:96:e0:ff',
'ip' : '172.17.17.2',
'age' : 1435641582.49
}
]
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_arp_table',
**{
}
)
if not proxy_output.get('result'):
return proxy_output
arp_table = proxy_output.get('out')
if interface:
arp_table = _filter_list(arp_table, 'interface', interface)
if ipaddr:
arp_table = _filter_list(arp_table, 'ip', ipaddr)
if macaddr:
arp_table = _filter_list(arp_table, 'mac', macaddr)
proxy_output.update({
'out': arp_table
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def ipaddrs(**kwargs): # pylint: disable=unused-argument
'''
Returns IP addresses configured on the device.
:return: A dictionary with the IPv4 and IPv6 addresses of the interfaces.
Returns all configured IP addresses on all interfaces as a dictionary
of dictionaries. Keys of the main dictionary represent the name of the
interface. Values of the main dictionary represent are dictionaries
that may consist of two keys 'ipv4' and 'ipv6' (one, both or none)
which are themselvs dictionaries with the IP addresses as keys.
CLI Example:
.. code-block:: bash
salt '*' net.ipaddrs
Example output:
.. code-block:: python
{
'FastEthernet8': {
'ipv4': {
'10.66.43.169': {
'prefix_length': 22
}
}
},
'Loopback555': {
'ipv4': {
'192.168.1.1': {
'prefix_length': 24
}
},
'ipv6': {
'1::1': {
'prefix_length': 64
},
'2001:DB8:1::1': {
'prefix_length': 64
},
'FE80::3': {
'prefix_length': 'N/A'
}
}
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_interfaces_ip',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def interfaces(**kwargs): # pylint: disable=unused-argument
'''
Returns details of the interfaces on the device.
:return: Returns a dictionary of dictionaries. The keys for the first
dictionary will be the interfaces in the devices.
CLI Example:
.. code-block:: bash
salt '*' net.interfaces
Example output:
.. code-block:: python
{
'Management1': {
'is_up': False,
'is_enabled': False,
'description': '',
'last_flapped': -1,
'speed': 1000,
'mac_address': 'dead:beef:dead',
},
'Ethernet1':{
'is_up': True,
'is_enabled': True,
'description': 'foo',
'last_flapped': 1429978575.1554043,
'speed': 1000,
'mac_address': 'beef:dead:beef',
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_interfaces',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def lldp(interface='', **kwargs): # pylint: disable=unused-argument
'''
Returns a detailed view of the LLDP neighbors.
:param interface: interface name to filter on
:return: A dictionary with the LLDL neighbors. The keys are the
interfaces with LLDP activated on.
CLI Example:
.. code-block:: bash
salt '*' net.lldp
salt '*' net.lldp interface='TenGigE0/0/0/8'
Example output:
.. code-block:: python
{
'TenGigE0/0/0/8': [
{
'parent_interface': 'Bundle-Ether8',
'interface_description': 'TenGigE0/0/0/8',
'remote_chassis_id': '8c60.4f69.e96c',
'remote_system_name': 'switch',
'remote_port': 'Eth2/2/1',
'remote_port_description': 'Ethernet2/2/1',
'remote_system_description': 'Cisco Nexus Operating System (NX-OS) Software 7.1(0)N1(1a)
TAC support: http://www.cisco.com/tac
Copyright (c) 2002-2015, Cisco Systems, Inc. All rights reserved.',
'remote_system_capab': 'B, R',
'remote_system_enable_capab': 'B'
}
]
}
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_lldp_neighbors_detail',
**{
}
)
if not proxy_output.get('result'):
return proxy_output
lldp_neighbors = proxy_output.get('out')
if interface:
lldp_neighbors = {interface: lldp_neighbors.get(interface)}
proxy_output.update({
'out': lldp_neighbors
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def mac(address='', interface='', vlan=0, **kwargs): # pylint: disable=unused-argument
'''
Returns the MAC Address Table on the device.
:param address: MAC address to filter on
:param interface: Interface name to filter on
:param vlan: VLAN identifier
:return: A list of dictionaries representing the entries in the MAC Address Table
CLI Example:
.. code-block:: bash
salt '*' net.mac
salt '*' net.mac vlan=10
Example output:
.. code-block:: python
[
{
'mac' : '00:1c:58:29:4a:71',
'interface' : 'xe-3/0/2',
'static' : False,
'active' : True,
'moves' : 1,
'vlan' : 10,
'last_move' : 1454417742.58
},
{
'mac' : '8c:60:4f:58:e1:c1',
'interface' : 'xe-1/0/1',
'static' : False,
'active' : True,
'moves' : 2,
'vlan' : 42,
'last_move' : 1453191948.11
}
]
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_mac_address_table',
**{
}
)
if not proxy_output.get('result'):
# if negative, leave the output unchanged
return proxy_output
mac_address_table = proxy_output.get('out')
if vlan and isinstance(vlan, int):
mac_address_table = _filter_list(mac_address_table, 'vlan', vlan)
if address:
mac_address_table = _filter_list(mac_address_table, 'mac', address)
if interface:
mac_address_table = _filter_list(mac_address_table, 'interface', interface)
proxy_output.update({
'out': mac_address_table
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def config(source=None, **kwargs): # pylint: disable=unused-argument
'''
.. versionadded:: 2017.7.0
Return the whole configuration of the network device. By default, it will
return all possible configuration sources supported by the network device.
At most, there will be:
- running config
- startup config
- candidate config
To return only one of the configurations, you can use the ``source``
argument.
source
Which configuration type you want to display, default is all of them.
Options:
- running
- candidate
- startup
:return:
The object returned is a dictionary with the following keys:
- running (string): Representation of the native running configuration.
- candidate (string): Representation of the native candidate configuration.
If the device doesn't differentiate between running and startup
configuration this will an empty string.
- startup (string): Representation of the native startup configuration.
If the device doesn't differentiate between running and startup
configuration this will an empty string.
CLI Example:
.. code-block:: bash
salt '*' net.config
salt '*' net.config source=candidate
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_config',
**{
'retrieve': source
}
)
@salt.utils.napalm.proxy_napalm_wrap
def optics(**kwargs): # pylint: disable=unused-argument
'''
.. versionadded:: 2017.7.0
Fetches the power usage on the various transceivers installed
on the network device (in dBm), and returns a view that conforms with the
OpenConfig model openconfig-platform-transceiver.yang.
:return:
Returns a dictionary where the keys are as listed below:
* intf_name (unicode)
* physical_channels
* channels (list of dicts)
* index (int)
* state
* input_power
* instant (float)
* avg (float)
* min (float)
* max (float)
* output_power
* instant (float)
* avg (float)
* min (float)
* max (float)
* laser_bias_current
* instant (float)
* avg (float)
* min (float)
* max (float)
CLI Example:
.. code-block:: bash
salt '*' net.optics
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_optics',
**{
}
)
# <---- Call NAPALM getters --------------------------------------------------------------------------------------------
# ----- Configuration specific functions ------------------------------------------------------------------------------>
@salt.utils.napalm.proxy_napalm_wrap
def load_config(filename=None,
text=None,
test=False,
commit=True,
debug=False,
replace=False,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
commit_jid=None,
inherit_napalm_device=None,
saltenv='base',
**kwargs): # pylint: disable=unused-argument
'''
Applies configuration changes on the device. It can be loaded from a file or from inline string.
If you send both a filename and a string containing the configuration, the file has higher precedence.
By default this function will commit the changes. If there are no changes, it does not commit and
the flag ``already_configured`` will be set as ``True`` to point this out.
To avoid committing the configuration, set the argument ``test`` to ``True`` and will discard (dry run).
To keep the changes but not commit, set ``commit`` to ``False``.
To replace the config, set ``replace`` to ``True``.
filename
Path to the file containing the desired configuration.
This can be specified using the absolute path to the file,
or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
.. versionchanged:: 2018.3.0
text
String containing the desired configuration.
This argument is ignored when ``filename`` is specified.
test: False
Dry run? If set as ``True``, will apply the config, discard and return the changes. Default: ``False``
and will commit the changes on the device.
commit: True
Commit? Default: ``True``.
debug: False
Debug mode. Will insert a new key under the output dictionary, as ``loaded_config`` containing the raw
configuration loaded on the device.
.. versionadded:: 2016.11.2
replace: False
Load and replace the configuration. Default: ``False``.
.. versionadded:: 2016.11.2
commit_in: ``None``
Commit the changes in a specific number of minutes / hours. Example of
accepted formats: ``5`` (commit in 5 minutes), ``2m`` (commit in 2
minutes), ``1h`` (commit the changes in 1 hour)`, ``5h30m`` (commit
the changes in 5 hours and 30 minutes).
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
commit_at: ``None``
Commit the changes at a specific time. Example of accepted formats:
``1am`` (will commit the changes at the next 1AM), ``13:20`` (will
commit at 13:20), ``1:20am``, etc.
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
revert_in: ``None``
Commit and revert the changes in a specific number of minutes / hours.
Example of accepted formats: ``5`` (revert in 5 minutes), ``2m`` (revert
in 2 minutes), ``1h`` (revert the changes in 1 hour)`, ``5h30m`` (revert
the changes in 5 hours and 30 minutes).
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
revert_at: ``None``
Commit and revert the changes at a specific time. Example of accepted
formats: ``1am`` (will commit and revert the changes at the next 1AM),
``13:20`` (will commit and revert at 13:20), ``1:20am``, etc.
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
saltenv: ``base``
Specifies the Salt environment name.
.. versionadded:: 2018.3.0
:return: a dictionary having the following keys:
* result (bool): if the config was applied successfully. It is ``False`` only in case of failure. In case \
there are no changes to be applied and successfully performs all operations it is still ``True`` and so will be \
the ``already_configured`` flag (example below)
* comment (str): a message for the user
* already_configured (bool): flag to check if there were no changes applied
* loaded_config (str): the configuration loaded on the device. Requires ``debug`` to be set as ``True``
* diff (str): returns the config changes applied
CLI Example:
.. code-block:: bash
salt '*' net.load_config text='ntp peer 192.168.0.1'
salt '*' net.load_config filename='/absolute/path/to/your/file'
salt '*' net.load_config filename='/absolute/path/to/your/file' test=True
salt '*' net.load_config filename='/absolute/path/to/your/file' commit=False
Example output:
.. code-block:: python
{
'comment': 'Configuration discarded.',
'already_configured': False,
'result': True,
'diff': '[edit interfaces xe-0/0/5]+ description "Adding a description";'
}
'''
fun = 'load_merge_candidate'
if replace:
fun = 'load_replace_candidate'
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
if filename:
text = __salt__['cp.get_file_str'](filename, saltenv=saltenv)
if text is False:
# When using salt:// or https://, if the resource is not available,
# it will either raise an exception, or return False.
ret = {
'result': False,
'out': None
}
ret['comment'] = 'Unable to read from {}. Please specify a valid file or text.'.format(filename)
log.error(ret['comment'])
return ret
if commit_jid:
# When the commit_jid argument is passed, it probably is a scheduled
# commit to be executed, and filename is a temporary file which
# can be removed after reading it.
salt.utils.files.safe_rm(filename)
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
fun,
**{
'config': text
}
)
return _config_logic(napalm_device, # pylint: disable=undefined-variable
_loaded,
test=test,
debug=debug,
replace=replace,
commit_config=commit,
loaded_config=text,
commit_at=commit_at,
commit_in=commit_in,
revert_in=revert_in,
revert_at=revert_at,
commit_jid=commit_jid,
**kwargs)
@salt.utils.napalm.proxy_napalm_wrap
def load_template(template_name=None,
template_source=None,
context=None,
defaults=None,
template_engine='jinja',
saltenv='base',
template_hash=None,
template_hash_name=None,
skip_verify=False,
test=False,
commit=True,
debug=False,
replace=False,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
inherit_napalm_device=None, # pylint: disable=unused-argument
**template_vars):
'''
Renders a configuration template (default: Jinja) and loads the result on the device.
By default this function will commit the changes. If there are no changes,
it does not commit, discards he config and the flag ``already_configured``
will be set as ``True`` to point this out.
To avoid committing the configuration, set the argument ``test`` to ``True``
and will discard (dry run).
To preserve the changes, set ``commit`` to ``False``.
However, this is recommended to be used only in exceptional cases
when there are applied few consecutive states
and/or configuration changes.
Otherwise the user might forget that the config DB is locked
and the candidate config buffer is not cleared/merged in the running config.
To replace the config, set ``replace`` to ``True``.
template_name
Identifies path to the template source.
The template can be either stored on the local machine, either remotely.
The recommended location is under the ``file_roots``
as specified in the master config file.
For example, let's suppose the ``file_roots`` is configured as:
.. code-block:: yaml
file_roots:
base:
- /etc/salt/states
Placing the template under ``/etc/salt/states/templates/example.jinja``,
it can be used as ``salt://templates/example.jinja``.
Alternatively, for local files, the user can specify the absolute path.
If remotely, the source can be retrieved via ``http``, ``https`` or ``ftp``.
Examples:
- ``salt://my_template.jinja``
- ``/absolute/path/to/my_template.jinja``
- ``http://example.com/template.cheetah``
- ``https:/example.com/template.mako``
- ``ftp://example.com/template.py``
.. versionchanged:: 2019.2.0
This argument can now support a list of templates to be rendered.
The resulting configuration text is loaded at once, as a single
configuration chunk.
template_source: None
Inline config template to be rendered and loaded on the device.
template_hash: None
Hash of the template file. Format: ``{hash_type: 'md5', 'hsum': <md5sum>}``
.. versionadded:: 2016.11.2
context: None
Overrides default context variables passed to the template.
.. versionadded:: 2019.2.0
template_hash_name: None
When ``template_hash`` refers to a remote file,
this specifies the filename to look for in that file.
.. versionadded:: 2016.11.2
saltenv: ``base``
Specifies the template environment.
This will influence the relative imports inside the templates.
.. versionadded:: 2016.11.2
template_engine: jinja
The following templates engines are supported:
- :mod:`cheetah<salt.renderers.cheetah>`
- :mod:`genshi<salt.renderers.genshi>`
- :mod:`jinja<salt.renderers.jinja>`
- :mod:`mako<salt.renderers.mako>`
- :mod:`py<salt.renderers.py>`
- :mod:`wempy<salt.renderers.wempy>`
.. versionadded:: 2016.11.2
skip_verify: True
If ``True``, hash verification of remote file sources
(``http://``, ``https://``, ``ftp://``) will be skipped,
and the ``source_hash`` argument will be ignored.
.. versionadded:: 2016.11.2
test: False
Dry run? If set to ``True``, will apply the config,
discard and return the changes.
Default: ``False`` and will commit the changes on the device.
commit: True
Commit? (default: ``True``)
debug: False
Debug mode. Will insert a new key under the output dictionary,
as ``loaded_config`` containing the raw result after the template was rendered.
.. versionadded:: 2016.11.2
replace: False
Load and replace the configuration.
.. versionadded:: 2016.11.2
commit_in: ``None``
Commit the changes in a specific number of minutes / hours. Example of
accepted formats: ``5`` (commit in 5 minutes), ``2m`` (commit in 2
minutes), ``1h`` (commit the changes in 1 hour)`, ``5h30m`` (commit
the changes in 5 hours and 30 minutes).
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
commit_at: ``None``
Commit the changes at a specific time. Example of accepted formats:
``1am`` (will commit the changes at the next 1AM), ``13:20`` (will
commit at 13:20), ``1:20am``, etc.
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
revert_in: ``None``
Commit and revert the changes in a specific number of minutes / hours.
Example of accepted formats: ``5`` (revert in 5 minutes), ``2m`` (revert
in 2 minutes), ``1h`` (revert the changes in 1 hour)`, ``5h30m`` (revert
the changes in 5 hours and 30 minutes).
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
revert_at: ``None``
Commit and revert the changes at a specific time. Example of accepted
formats: ``1am`` (will commit and revert the changes at the next 1AM),
``13:20`` (will commit and revert at 13:20), ``1:20am``, etc.
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
defaults: None
Default variables/context passed to the template.
.. versionadded:: 2016.11.2
template_vars
Dictionary with the arguments/context to be used when the template is rendered.
.. note::
Do not explicitly specify this argument. This represents any other
variable that will be sent to the template rendering system.
Please see the examples below!
.. note::
It is more recommended to use the ``context`` argument to avoid
conflicts between CLI arguments and template variables.
:return: a dictionary having the following keys:
- result (bool): if the config was applied successfully. It is ``False``
only in case of failure. In case there are no changes to be applied and
successfully performs all operations it is still ``True`` and so will be
the ``already_configured`` flag (example below)
- comment (str): a message for the user
- already_configured (bool): flag to check if there were no changes applied
- loaded_config (str): the configuration loaded on the device, after
rendering the template. Requires ``debug`` to be set as ``True``
- diff (str): returns the config changes applied
The template can use variables from the ``grains``, ``pillar`` or ``opts``, for example:
.. code-block:: jinja
{% set router_model = grains.get('model') -%}
{% set router_vendor = grains.get('vendor') -%}
{% set os_version = grains.get('version') -%}
{% set hostname = pillar.get('proxy', {}).get('host') -%}
{% if router_vendor|lower == 'juniper' %}
system {
host-name {{hostname}};
}
{% elif router_vendor|lower == 'cisco' %}
hostname {{hostname}}
{% endif %}
CLI Examples:
.. code-block:: bash
salt '*' net.load_template set_ntp_peers peers=[192.168.0.1] # uses NAPALM default templates
# inline template:
salt -G 'os:junos' net.load_template template_source='system { host-name {{host_name}}; }' \
host_name='MX480.lab'
# inline template using grains info:
salt -G 'os:junos' net.load_template \
template_source='system { host-name {{grains.model}}.lab; }'
# if the device is a MX480, the command above will set the hostname as: MX480.lab
# inline template using pillar data:
salt -G 'os:junos' net.load_template template_source='system { host-name {{pillar.proxy.host}}; }'
salt '*' net.load_template https://bit.ly/2OhSgqP hostname=example # will commit
salt '*' net.load_template https://bit.ly/2OhSgqP hostname=example test=True # dry run
salt '*' net.load_template salt://templates/example.jinja debug=True # Using the salt:// URI
# render a mako template:
salt '*' net.load_template salt://templates/example.mako template_engine=mako debug=True
# render remote template
salt -G 'os:junos' net.load_template http://bit.ly/2fReJg7 test=True debug=True peers=['192.168.0.1']
salt -G 'os:ios' net.load_template http://bit.ly/2gKOj20 test=True debug=True peers=['192.168.0.1']
# render multiple templates at once
salt '*' net.load_template "['https://bit.ly/2OhSgqP', 'salt://templates/example.jinja']" context="{'hostname': 'example'}"
Example output:
.. code-block:: python
{
'comment': '',
'already_configured': False,
'result': True,
'diff': '[edit system]+ host-name edge01.bjm01',
'loaded_config': 'system { host-name edge01.bjm01; }''
}
'''
_rendered = ''
_loaded = {
'result': True,
'comment': '',
'out': None
}
loaded_config = None
# prechecks
deprecated_args = ('template_user', 'template_attrs', 'template_group', 'template_mode')
for deprecated_arg in deprecated_args:
if template_vars.get(deprecated_arg):
del template_vars[deprecated_arg]
salt.utils.versions.warn_until(
'Sodium',
('The \'{arg}\' argument to \'net.load_template\' is deprecated '
'and has been ignored').format(arg=deprecated_arg)
)
if template_engine not in salt.utils.templates.TEMPLATE_REGISTRY:
_loaded.update({
'result': False,
'comment': 'Invalid templating engine! Choose between: {tpl_eng_opts}'.format(
tpl_eng_opts=', '.join(list(salt.utils.templates.TEMPLATE_REGISTRY.keys()))
)
})
return _loaded # exit
# to check if will be rendered by salt or NAPALM
salt_render_prefixes = ('salt://', 'http://', 'https://', 'ftp://')
salt_render = False
file_exists = False
if not isinstance(template_name, (tuple, list)):
for salt_render_prefix in salt_render_prefixes:
if not salt_render:
salt_render = salt_render or template_name.startswith(salt_render_prefix)
file_exists = __salt__['file.file_exists'](template_name)
if template_source or file_exists or salt_render or isinstance(template_name, (tuple, list)):
# either inline template
# either template in a custom path
# either abs path send
# either starts with salt:// and
# then use Salt render system
if context is None:
context = {}
context.update(template_vars)
# if needed to render the template send as inline arg
if template_source:
# render the content
_rendered = __salt__['file.apply_template_on_contents'](
contents=template_source,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv
)
if not isinstance(_rendered, six.string_types):
if 'result' in _rendered:
_loaded['result'] = _rendered['result']
else:
_loaded['result'] = False
if 'comment' in _rendered:
_loaded['comment'] = _rendered['comment']
else:
_loaded['comment'] = 'Error while rendering the template.'
return _loaded
else:
# render the file - either local, either remote
if not isinstance(template_name, (list, tuple)):
template_name = [template_name]
if template_hash_name and not isinstance(template_hash_name, (list, tuple)):
template_hash_name = [template_hash_name]
elif not template_hash_name:
template_hash_name = [None] * len(template_name)
if template_hash and isinstance(template_hash, six.string_types) and not\
(template_hash.startswith('salt://') or template_hash.startswith('file://')):
# If the template hash is passed as string, and it's not a file
# (starts with the salt:// or file:// URI), then make it a list
# of 1 element (for the iteration below)
template_hash = [template_hash]
elif template_hash and isinstance(template_hash, six.string_types) and\
(template_hash.startswith('salt://') or template_hash.startswith('file://')):
# If the template hash is a file URI, then provide the same value
# for each of the templates in the list, as probably they all
# share the same hash file, otherwise the user should provide
# this as a list
template_hash = [template_hash] * len(template_name)
elif not template_hash:
template_hash = [None] * len(template_name)
for tpl_index, tpl_name in enumerate(template_name):
tpl_hash = template_hash[tpl_index]
tpl_hash_name = template_hash_name[tpl_index]
_rand_filename = __salt__['random.hash'](tpl_name, 'md5')
_temp_file = __salt__['file.join']('/tmp', _rand_filename)
_managed = __salt__['file.get_managed'](name=_temp_file,
source=tpl_name,
source_hash=tpl_hash,
source_hash_name=tpl_hash_name,
user=None,
group=None,
mode=None,
attrs=None,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv,
skip_verify=skip_verify)
if not isinstance(_managed, (list, tuple)) and isinstance(_managed, six.string_types):
_loaded['comment'] += _managed
_loaded['result'] = False
elif isinstance(_managed, (list, tuple)) and not _managed:
_loaded['result'] = False
_loaded['comment'] += 'Error while rendering the template.'
elif isinstance(_managed, (list, tuple)) and not _managed[0]:
_loaded['result'] = False
_loaded['comment'] += _managed[-1] # contains the error message
if _loaded['result']: # all good
_temp_tpl_file = _managed[0]
_temp_tpl_file_exists = __salt__['file.file_exists'](_temp_tpl_file)
if not _temp_tpl_file_exists:
_loaded['result'] = False
_loaded['comment'] += 'Error while rendering the template.'
return _loaded
_rendered += __salt__['file.read'](_temp_tpl_file)
__salt__['file.remove'](_temp_tpl_file)
else:
return _loaded # exit
loaded_config = _rendered
if _loaded['result']: # all good
fun = 'load_merge_candidate'
if replace: # replace requested
fun = 'load_replace_candidate'
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
fun,
**{
'config': _rendered
}
)
else:
salt.utils.versions.warn_until(
'Sodium',
'Native NAPALM templates support will be removed in the Sodium '
'release. Please consider using the Salt rendering pipeline instead.'
'If you are using the \'netntp\', \'netsnmp\', or \'netusers\' Salt '
'State modules, you can ignore this message'
)
# otherwise, use NAPALM render system, injecting pillar/grains/opts vars
load_templates_params = defaults if defaults else {}
load_templates_params.update(template_vars)
load_templates_params.update(
{
'template_name': template_name,
'template_source': template_source, # inline template
'pillar': __pillar__, # inject pillar content
'grains': __grains__, # inject grains content
'opts': __opts__ # inject opts content
}
)
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
# so we'll set the CLOSE global explicitly as False
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'load_template',
**load_templates_params
)
return _config_logic(napalm_device, # pylint: disable=undefined-variable
_loaded,
test=test,
debug=debug,
replace=replace,
commit_config=commit,
loaded_config=loaded_config,
commit_at=commit_at,
commit_in=commit_in,
revert_in=revert_in,
revert_at=revert_at,
**template_vars)
@salt.utils.napalm.proxy_napalm_wrap
def commit(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Commits the configuration changes made on the network device.
CLI Example:
.. code-block:: bash
salt '*' net.commit
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'commit_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def discard_config(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
"""
Discards the changes applied.
CLI Example:
.. code-block:: bash
salt '*' net.discard_config
"""
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'discard_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def compare_config(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Returns the difference between the running config and the candidate config.
CLI Example:
.. code-block:: bash
salt '*' net.compare_config
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'compare_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def rollback(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Rollbacks the configuration.
CLI Example:
.. code-block:: bash
salt '*' net.rollback
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'rollback',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
@salt.utils.napalm.proxy_napalm_wrap
def config_control(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Will check if the configuration was changed.
If differences found, will try to commit.
In case commit unsuccessful, will try to rollback.
:return: A tuple with a boolean that specifies if the config was changed/committed/rollbacked on the device.\
And a string that provides more details of the reason why the configuration was not committed properly.
CLI Example:
.. code-block:: bash
salt '*' net.config_control
'''
result = True
comment = ''
changed, not_changed_rsn = config_changed(inherit_napalm_device=napalm_device) # pylint: disable=undefined-variable
if not changed:
return (changed, not_changed_rsn)
# config changed, thus let's try to commit
try_commit = commit()
if not try_commit.get('result'):
result = False
comment = 'Unable to commit the changes: {reason}.\n\
Will try to rollback now!'.format(
reason=try_commit.get('comment')
)
try_rollback = rollback()
if not try_rollback.get('result'):
comment += '\nCannot rollback! {reason}'.format(
reason=try_rollback.get('comment')
)
return result, comment
def cancel_commit(jid):
'''
.. versionadded:: 2019.2.0
Cancel a commit scheduled to be executed via the ``commit_in`` and
``commit_at`` arguments from the
:py:func:`net.load_template <salt.modules.napalm_network.load_template>` or
:py:func:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit ID is displayed when the commit is scheduled
via the functions named above.
CLI Example:
.. code-block:: bash
salt '*' net.cancel_commit 20180726083540640360
'''
job_name = '__napalm_commit_{}'.format(jid)
removed = __salt__['schedule.delete'](job_name)
if removed['result']:
saved = __salt__['schedule.save']()
removed['comment'] = 'Commit #{jid} cancelled.'.format(jid=jid)
else:
removed['comment'] = 'Unable to find commit #{jid}.'.format(jid=jid)
return removed
def confirm_commit(jid):
'''
.. versionadded:: 2019.2.0
Confirm a commit scheduled to be reverted via the ``revert_in`` and
``revert_at`` arguments from the
:mod:`net.load_template <salt.modules.napalm_network.load_template>` or
:mod:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit ID is displayed when the commit confirmed
is scheduled via the functions named above.
CLI Example:
.. code-block:: bash
salt '*' net.confirm_commit 20180726083540640360
'''
if __grains__['os'] == 'junos':
# Confirm the commit, by committing (i.e., invoking the RPC call)
confirmed = __salt__['napalm.junos_commit']()
confirmed['result'] = confirmed.pop('out')
confirmed['comment'] = confirmed.pop('message')
else:
confirmed = cancel_commit(jid)
if confirmed['result']:
confirmed['comment'] = 'Commit #{jid} confirmed.'.format(jid=jid)
return confirmed
def save_config(source=None,
path=None):
'''
.. versionadded:: 2019.2.0
Save the configuration to a file on the local file system.
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``,
``startup``. Default: ``running``.
path
Absolute path to file where to save the configuration.
To push the files to the Master, use
:mod:`cp.push <salt.modules.cp.push>` Execution function.
CLI Example:
.. code-block:: bash
salt '*' net.save_config source=running
'''
if not source:
source = 'running'
if not path:
path = salt.utils.files.mkstemp()
running_config = __salt__['net.config'](source=source)
if not running_config or not running_config['result']:
log.error('Unable to retrieve the config')
return running_config
with salt.utils.files.fopen(path, 'w') as fh_:
fh_.write(running_config['out'][source])
return {
'result': True,
'out': path,
'comment': '{source} config saved to {path}'.format(source=source, path=path)
}
def replace_pattern(pattern,
repl,
count=0,
flags=8,
bufsize=1,
append_if_not_found=False,
prepend_if_not_found=False,
not_found_content=None,
search_only=False,
show_changes=True,
backslash_literal=False,
source=None,
path=None,
test=False,
replace=True,
debug=False,
commit=True):
'''
.. versionadded:: 2019.2.0
Replace occurrences of a pattern in the configuration source. If
``show_changes`` is ``True``, then a diff of what changed will be returned,
otherwise a ``True`` will be returned when changes are made, and ``False``
when no changes are made.
This is a pure Python implementation that wraps Python's :py:func:`~re.sub`.
pattern
A regular expression, to be matched using Python's
:py:func:`~re.search`.
repl
The replacement text.
count: ``0``
Maximum number of pattern occurrences to be replaced. If count is a
positive integer ``n``, only ``n`` occurrences will be replaced,
otherwise all occurrences will be replaced.
flags (list or int): ``8``
A list of flags defined in the ``re`` module documentation from the
Python standard library. Each list item should be a string that will
correlate to the human-friendly flag name. E.g., ``['IGNORECASE',
'MULTILINE']``. Optionally, ``flags`` may be an int, with a value
corresponding to the XOR (``|``) of all the desired flags. Defaults to
8 (which supports 'MULTILINE').
bufsize (int or str): ``1``
How much of the configuration to buffer into memory at once. The
default value ``1`` processes one line at a time. The special value
``file`` may be specified which will read the entire file into memory
before processing.
append_if_not_found: ``False``
If set to ``True``, and pattern is not found, then the content will be
appended to the file.
prepend_if_not_found: ``False``
If set to ``True`` and pattern is not found, then the content will be
prepended to the file.
not_found_content
Content to use for append/prepend if not found. If None (default), uses
``repl``. Useful when ``repl`` uses references to group in pattern.
search_only: ``False``
If set to true, this no changes will be performed on the file, and this
function will simply return ``True`` if the pattern was matched, and
``False`` if not.
show_changes: ``True``
If ``True``, return a diff of changes made. Otherwise, return ``True``
if changes were made, and ``False`` if not.
backslash_literal: ``False``
Interpret backslashes as literal backslashes for the repl and not
escape characters. This will help when using append/prepend so that
the backslashes are not interpreted for the repl on the second run of
the state.
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path
Save the temporary configuration to a specific path, then read from
there.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' net.replace_pattern "bind-address\\s*=" "bind-address:"
CLI Example:
.. code-block:: bash
salt '*' net.replace_pattern PREFIX-LIST_NAME new-prefix-list-name
salt '*' net.replace_pattern bgp-group-name new-bgp-group-name count=1
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
replace_pattern = __salt__['file.replace'](path,
pattern,
repl,
count=count,
flags=flags,
bufsize=bufsize,
append_if_not_found=append_if_not_found,
prepend_if_not_found=prepend_if_not_found,
not_found_content=not_found_content,
search_only=search_only,
show_changes=show_changes,
backslash_literal=backslash_literal)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
def blockreplace(marker_start,
marker_end,
content='',
append_if_not_found=False,
prepend_if_not_found=False,
show_changes=True,
append_newline=False,
source='running',
path=None,
test=False,
commit=True,
debug=False,
replace=True):
'''
.. versionadded:: 2019.2.0
Replace content of the configuration source, delimited by the line markers.
A block of content delimited by comments can help you manage several lines
without worrying about old entries removal.
marker_start
The line content identifying a line as the start of the content block.
Note that the whole line containing this marker will be considered,
so whitespace or extra content before or after the marker is included
in final output.
marker_end
The line content identifying a line as the end of the content block.
Note that the whole line containing this marker will be considered,
so whitespace or extra content before or after the marker is included
in final output.
content
The content to be used between the two lines identified by
``marker_start`` and ``marker_stop``.
append_if_not_found: ``False``
If markers are not found and set to True then, the markers and content
will be appended to the file.
prepend_if_not_found: ``False``
If markers are not found and set to True then, the markers and content
will be prepended to the file.
append_newline: ``False``
Controls whether or not a newline is appended to the content block.
If the value of this argument is ``True`` then a newline will be added
to the content block. If it is ``False``, then a newline will not be
added to the content block. If it is ``None`` then a newline will only
be added to the content block if it does not already end in a newline.
show_changes: ``True``
Controls how changes are presented. If ``True``, this function will
return the of the changes made.
If ``False``, then it will return a boolean (``True`` if any changes
were made, otherwise False).
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path: ``None``
Save the temporary configuration to a specific path, then read from
there. This argument is optional, can be used when you prefers a
particular location of the temporary file.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
CLI Example:
.. code-block:: bash
salt '*' net.blockreplace 'ntp' 'interface' ''
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
replace_pattern = __salt__['file.blockreplace'](path,
marker_start=marker_start,
marker_end=marker_end,
content=content,
append_if_not_found=append_if_not_found,
prepend_if_not_found=prepend_if_not_found,
show_changes=show_changes,
append_newline=append_newline)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
def patch(patchfile,
options='',
saltenv='base',
source_hash=None,
show_changes=True,
source='running',
path=None,
test=False,
commit=True,
debug=False,
replace=True):
'''
.. versionadded:: 2019.2.0
Apply a patch to the configuration source, and load the result into the
running config of the device.
patchfile
A patch file to apply to the configuration source.
options
Options to pass to patch.
source_hash
If the patch file (specified via the ``patchfile`` argument) is an
HTTP(S) or FTP URL and the file exists in the minion's file cache, this
option can be passed to keep the minion from re-downloading the file if
the cached copy matches the specified hash.
show_changes: ``True``
Controls how changes are presented. If ``True``, this function will
return the of the changes made.
If ``False``, then it will return a boolean (``True`` if any changes
were made, otherwise False).
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path: ``None``
Save the temporary configuration to a specific path, then read from
there. This argument is optional, can the user prefers a particular
location of the temporary file.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
CLI Example:
.. code-block:: bash
salt '*' net.patch https://example.com/running_config.patch
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
patchfile_cache = __salt__['cp.cache_file'](patchfile)
if patchfile_cache is False:
return {
'out': None,
'result': False,
'comment': 'The file "{}" does not exist.'.format(patchfile)
}
replace_pattern = __salt__['file.patch'](path,
patchfile_cache,
options=options)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
# <---- Configuration specific functions -------------------------------------------------------------------------------
|
saltstack/salt
|
salt/modules/napalm_network.py
|
config_control
|
python
|
def config_control(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Will check if the configuration was changed.
If differences found, will try to commit.
In case commit unsuccessful, will try to rollback.
:return: A tuple with a boolean that specifies if the config was changed/committed/rollbacked on the device.\
And a string that provides more details of the reason why the configuration was not committed properly.
CLI Example:
.. code-block:: bash
salt '*' net.config_control
'''
result = True
comment = ''
changed, not_changed_rsn = config_changed(inherit_napalm_device=napalm_device) # pylint: disable=undefined-variable
if not changed:
return (changed, not_changed_rsn)
# config changed, thus let's try to commit
try_commit = commit()
if not try_commit.get('result'):
result = False
comment = 'Unable to commit the changes: {reason}.\n\
Will try to rollback now!'.format(
reason=try_commit.get('comment')
)
try_rollback = rollback()
if not try_rollback.get('result'):
comment += '\nCannot rollback! {reason}'.format(
reason=try_rollback.get('comment')
)
return result, comment
|
Will check if the configuration was changed.
If differences found, will try to commit.
In case commit unsuccessful, will try to rollback.
:return: A tuple with a boolean that specifies if the config was changed/committed/rollbacked on the device.\
And a string that provides more details of the reason why the configuration was not committed properly.
CLI Example:
.. code-block:: bash
salt '*' net.config_control
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_network.py#L2197-L2235
| null |
# -*- coding: utf-8 -*-
'''
NAPALM Network
==============
Basic methods for interaction with the network device through the virtual proxy 'napalm'.
:codeauthor: Mircea Ulinic <mircea@cloudflare.com> & Jerome Fleury <jf@cloudflare.com>
:maturity: new
:depends: napalm
:platform: unix
Dependencies
------------
- :mod:`napalm proxy minion <salt.proxy.napalm>`
.. versionadded:: 2016.11.0
.. versionchanged:: 2017.7.0
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import time
import logging
import datetime
log = logging.getLogger(__name__)
# Import Salt libs
from salt.ext import six
import salt.utils.files
import salt.utils.napalm
import salt.utils.versions
import salt.utils.templates
# Import 3rd-party libs
try:
import jxmlease # pylint: disable=unused-import
HAS_JXMLEASE = True
except ImportError:
HAS_JXMLEASE = False
# ----------------------------------------------------------------------------------------------------------------------
# module properties
# ----------------------------------------------------------------------------------------------------------------------
__virtualname__ = 'net'
__proxyenabled__ = ['*']
__virtual_aliases__ = ('napalm_net',)
# uses NAPALM-based proxy to interact with network devices
# ----------------------------------------------------------------------------------------------------------------------
# property functions
# ----------------------------------------------------------------------------------------------------------------------
def __virtual__():
'''
NAPALM library must be installed for this module to work and run in a (proxy) minion.
'''
return salt.utils.napalm.virtual(__opts__, __virtualname__, __file__)
# ----------------------------------------------------------------------------------------------------------------------
# helper functions -- will not be exported
# ----------------------------------------------------------------------------------------------------------------------
def _filter_list(input_list, search_key, search_value):
'''
Filters a list of dictionary by a set of key-value pair.
:param input_list: is a list of dictionaries
:param search_key: is the key we are looking for
:param search_value: is the value we are looking for the key specified in search_key
:return: filered list of dictionaries
'''
output_list = list()
for dictionary in input_list:
if dictionary.get(search_key) == search_value:
output_list.append(dictionary)
return output_list
def _filter_dict(input_dict, search_key, search_value):
'''
Filters a dictionary of dictionaries by a key-value pair.
:param input_dict: is a dictionary whose values are lists of dictionaries
:param search_key: is the key in the leaf dictionaries
:param search_values: is the value in the leaf dictionaries
:return: filtered dictionary
'''
output_dict = dict()
for key, key_list in six.iteritems(input_dict):
key_list_filtered = _filter_list(key_list, search_key, search_value)
if key_list_filtered:
output_dict[key] = key_list_filtered
return output_dict
def _safe_commit_config(loaded_result, napalm_device):
_commit = commit(inherit_napalm_device=napalm_device) # calls the function commit, defined below
if not _commit.get('result', False):
# if unable to commit
loaded_result['comment'] += _commit['comment'] if _commit.get('comment') else 'Unable to commit.'
loaded_result['result'] = False
# unable to commit, something went wrong
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
return _commit
def _safe_dicard_config(loaded_result, napalm_device):
'''
'''
log.debug('Discarding the config')
log.debug(loaded_result)
_discarded = discard_config(inherit_napalm_device=napalm_device)
if not _discarded.get('result', False):
loaded_result['comment'] += _discarded['comment'] if _discarded.get('comment') \
else 'Unable to discard config.'
loaded_result['result'] = False
# make sure it notifies
# that something went wrong
_explicit_close(napalm_device)
__context__['retcode'] = 1
return loaded_result
return _discarded
def _explicit_close(napalm_device):
'''
Will explicily close the config session with the network device,
when running in a now-always-alive proxy minion or regular minion.
This helper must be used in configuration-related functions,
as the session is preserved and not closed before making any changes.
'''
if salt.utils.napalm.not_always_alive(__opts__):
# force closing the configuration session
# when running in a non-always-alive proxy
# or regular minion
try:
napalm_device['DRIVER'].close()
except Exception as err:
log.error('Unable to close the temp connection with the device:')
log.error(err)
log.error('Please report.')
def _config_logic(napalm_device,
loaded_result,
test=False,
debug=False,
replace=False,
commit_config=True,
loaded_config=None,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
commit_jid=None,
**kwargs):
'''
Builds the config logic for `load_config` and `load_template` functions.
'''
# As the Salt logic is built around independent events
# when it comes to configuration changes in the
# candidate DB on the network devices, we need to
# make sure we're using the same session.
# Hence, we need to pass the same object around.
# the napalm_device object is inherited from
# the load_config or load_template functions
# and forwarded to compare, discard, commit etc.
# then the decorator will make sure that
# if not proxy (when the connection is always alive)
# and the `inherit_napalm_device` is set,
# `napalm_device` will be overridden.
# See `salt.utils.napalm.proxy_napalm_wrap` decorator.
current_jid = kwargs.get('__pub_jid')
if not current_jid:
current_jid = '{0:%Y%m%d%H%M%S%f}'.format(datetime.datetime.now())
loaded_result['already_configured'] = False
loaded_result['loaded_config'] = ''
if debug:
loaded_result['loaded_config'] = loaded_config
_compare = compare_config(inherit_napalm_device=napalm_device)
if _compare.get('result', False):
loaded_result['diff'] = _compare.get('out')
loaded_result.pop('out', '') # not needed
else:
loaded_result['diff'] = None
loaded_result['result'] = False
loaded_result['comment'] = _compare.get('comment')
__context__['retcode'] = 1
return loaded_result
_loaded_res = loaded_result.get('result', False)
if not _loaded_res or test:
# if unable to load the config (errors / warnings)
# or in testing mode,
# will discard the config
if loaded_result['comment']:
loaded_result['comment'] += '\n'
if not loaded_result.get('diff', ''):
loaded_result['already_configured'] = True
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
loaded_result['comment'] += 'Configuration discarded.'
# loaded_result['result'] = False not necessary
# as the result can be true when test=True
_explicit_close(napalm_device)
if not loaded_result['result']:
__context__['retcode'] = 1
return loaded_result
if not test and commit_config:
# if not in testing mode and trying to commit
if commit_jid:
log.info('Committing the JID: %s', str(commit_jid))
removed = cancel_commit(commit_jid)
log.debug('Cleaned up the commit from the schedule')
log.debug(removed['comment'])
if loaded_result.get('diff', ''):
# if not testing mode
# and also the user wants to commit (default)
# and there are changes to commit
if commit_in or commit_at:
commit_time = __utils__['timeutil.get_time_at'](time_in=commit_in,
time_at=commit_in)
# schedule job
scheduled_job_name = '__napalm_commit_{}'.format(current_jid)
temp_file = salt.utils.files.mkstemp()
with salt.utils.files.fopen(temp_file, 'w') as fp_:
fp_.write(loaded_config)
scheduled = __salt__['schedule.add'](scheduled_job_name,
function='net.load_config',
job_kwargs={
'filename': temp_file,
'commit_jid': current_jid,
'replace': replace
},
once=commit_time)
log.debug('Scheduling job')
log.debug(scheduled)
saved = __salt__['schedule.save']() # ensure the schedule is
# persistent cross Minion restart
discarded = _safe_dicard_config(loaded_result, napalm_device)
# discard the changes
if not discarded['result']:
discarded['comment'] += ('Scheduled the job to be executed at {schedule_ts}, '
'but was unable to discard the config: \n').format(schedule_ts=commit_time)
return discarded
loaded_result['comment'] = ('Changes discarded for now, and scheduled commit at: {schedule_ts}.\n'
'The commit ID is: {current_jid}.\n'
'To discard this commit, you can execute: \n\n'
'salt {min_id} net.cancel_commit {current_jid}').format(schedule_ts=commit_time,
min_id=__opts__['id'],
current_jid=current_jid)
loaded_result['commit_id'] = current_jid
return loaded_result
log.debug('About to commit:')
log.debug(loaded_result['diff'])
if revert_in or revert_at:
revert_time = __utils__['timeutil.get_time_at'](time_in=revert_in,
time_at=revert_at)
if __grains__['os'] == 'junos':
if not HAS_JXMLEASE:
loaded_result['comment'] = ('This feature requires the library jxmlease to be installed.\n'
'To install, please execute: ``pip install jxmlease``.')
loaded_result['result'] = False
return loaded_result
timestamp_at = __utils__['timeutil.get_timestamp_at'](time_in=revert_in,
time_at=revert_at)
minutes = int((timestamp_at - time.time())/60)
_comm = __salt__['napalm.junos_commit'](confirm=minutes)
if not _comm['out']:
# If unable to commit confirm, should try to bail out
loaded_result['comment'] = 'Unable to commit confirm: {}'.format(_comm['message'])
loaded_result['result'] = False
# But before exiting, we must gracefully discard the config
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
else:
temp_file = salt.utils.files.mkstemp()
running_config = __salt__['net.config'](source='running')['out']['running']
with salt.utils.files.fopen(temp_file, 'w') as fp_:
fp_.write(running_config)
committed = _safe_commit_config(loaded_result, napalm_device)
if not committed['result']:
# If unable to commit, dicard the config (which is
# already done by the _safe_commit_config function), and
# return with the command and other details.
return loaded_result
scheduled_job_name = '__napalm_commit_{}'.format(current_jid)
scheduled = __salt__['schedule.add'](scheduled_job_name,
function='net.load_config',
job_kwargs={
'filename': temp_file,
'commit_jid': current_jid,
'replace': True
},
once=revert_time)
log.debug('Scheduling commit confirmed')
log.debug(scheduled)
saved = __salt__['schedule.save']()
loaded_result['comment'] = ('The commit ID is: {current_jid}.\n'
'This commit will be reverted at: {schedule_ts}, unless confirmed.\n'
'To confirm the commit and avoid reverting, you can execute:\n\n'
'salt {min_id} net.confirm_commit {current_jid}').format(schedule_ts=revert_time,
min_id=__opts__['id'],
current_jid=current_jid)
loaded_result['commit_id'] = current_jid
return loaded_result
committed = _safe_commit_config(loaded_result, napalm_device)
if not committed['result']:
return loaded_result
else:
# would like to commit, but there's no change
# need to call discard_config() to release the config DB
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
loaded_result['already_configured'] = True
loaded_result['comment'] = 'Already configured.'
_explicit_close(napalm_device)
if not loaded_result['result']:
__context__['retcode'] = 1
return loaded_result
# ----------------------------------------------------------------------------------------------------------------------
# callable functions
# ----------------------------------------------------------------------------------------------------------------------
@salt.utils.napalm.proxy_napalm_wrap
def connected(**kwargs): # pylint: disable=unused-argument
'''
Specifies if the connection to the device succeeded.
CLI Example:
.. code-block:: bash
salt '*' net.connected
'''
return {
'out': napalm_device.get('UP', False) # pylint: disable=undefined-variable
}
@salt.utils.napalm.proxy_napalm_wrap
def facts(**kwargs): # pylint: disable=unused-argument
'''
Returns characteristics of the network device.
:return: a dictionary with the following keys:
* uptime - Uptime of the device in seconds.
* vendor - Manufacturer of the device.
* model - Device model.
* hostname - Hostname of the device
* fqdn - Fqdn of the device
* os_version - String with the OS version running on the device.
* serial_number - Serial number of the device
* interface_list - List of the interfaces of the device
CLI Example:
.. code-block:: bash
salt '*' net.facts
Example output:
.. code-block:: python
{
'os_version': '13.3R6.5',
'uptime': 10117140,
'interface_list': [
'lc-0/0/0',
'pfe-0/0/0',
'pfh-0/0/0',
'xe-0/0/0',
'xe-0/0/1',
'xe-0/0/2',
'xe-0/0/3',
'gr-0/0/10',
'ip-0/0/10'
],
'vendor': 'Juniper',
'serial_number': 'JN131356FBFA',
'model': 'MX480',
'hostname': 're0.edge05.syd01',
'fqdn': 're0.edge05.syd01'
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_facts',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def environment(**kwargs): # pylint: disable=unused-argument
'''
Returns the environment of the device.
CLI Example:
.. code-block:: bash
salt '*' net.environment
Example output:
.. code-block:: python
{
'fans': {
'Bottom Rear Fan': {
'status': True
},
'Bottom Middle Fan': {
'status': True
},
'Top Middle Fan': {
'status': True
},
'Bottom Front Fan': {
'status': True
},
'Top Front Fan': {
'status': True
},
'Top Rear Fan': {
'status': True
}
},
'memory': {
'available_ram': 16349,
'used_ram': 4934
},
'temperature': {
'FPC 0 Exhaust A': {
'is_alert': False,
'temperature': 35.0,
'is_critical': False
}
},
'cpu': {
'1': {
'%usage': 19.0
},
'0': {
'%usage': 35.0
}
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_environment',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def cli(*commands, **kwargs): # pylint: disable=unused-argument
'''
Returns a dictionary with the raw output of all commands passed as arguments.
commands
List of commands to be executed on the device.
textfsm_parse: ``False``
Try parsing the outputs using the TextFSM templates.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``napalm_cli_textfsm_parse``.
textfsm_path
The path where the TextFSM templates can be found. This option implies
the usage of the TextFSM index file.
``textfsm_path`` can be either absolute path on the server,
either specified using the following URL mschemes: ``file://``,
``salt://``, ``http://``, ``https://``, ``ftp://``,
``s3://``, ``swift://``.
.. versionadded:: 2018.3.0
.. note::
This needs to be a directory with a flat structure, having an
index file (whose name can be specified using the ``index_file`` option)
and a number of TextFSM templates.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_path``.
textfsm_template
The path to a certain the TextFSM template.
This can be specified using the absolute path
to the file, or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
.. versionadded:: 2018.3.0
textfsm_template_dict
A dictionary with the mapping between a command
and the corresponding TextFSM path to use to extract the data.
The TextFSM paths can be specified as in ``textfsm_template``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``napalm_cli_textfsm_template_dict``.
platform_grain_name: ``os``
The name of the grain used to identify the platform name
in the TextFSM index file. Default: ``os``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_grain``.
platform_column_name: ``Platform``
The column name used to identify the platform,
exactly as specified in the TextFSM index file.
Default: ``Platform``.
.. versionadded:: 2018.3.0
.. note::
This is field is case sensitive, make sure
to assign the correct value to this option,
exactly as defined in the index file.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_column_name``.
index_file: ``index``
The name of the TextFSM index file, under the ``textfsm_path``. Default: ``index``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_index_file``.
saltenv: ``base``
Salt fileserver envrionment from which to retrieve the file.
Ignored if ``textfsm_path`` is not a ``salt://`` URL.
.. versionadded:: 2018.3.0
include_empty: ``False``
Include empty files under the ``textfsm_path``.
.. versionadded:: 2018.3.0
include_pat
Glob or regex to narrow down the files cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. versionadded:: 2018.3.0
exclude_pat
Glob or regex to exclude certain files from being cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. versionadded:: 2018.3.0
.. note::
If used with ``include_pat``, files matching this pattern will be
excluded from the subset of files defined by ``include_pat``.
CLI Example:
.. code-block:: bash
salt '*' net.cli "show version" "show chassis fan"
CLI Example with TextFSM template:
.. code-block:: bash
salt '*' net.cli textfsm_parse=True textfsm_path=salt://textfsm/
Example output:
.. code-block:: python
{
'show version and haiku': 'Hostname: re0.edge01.arn01
Model: mx480
Junos: 13.3R6.5
Help me, Obi-Wan
I just saw Episode Two
You're my only hope
',
'show chassis fan' : 'Item Status RPM Measurement
Top Rear Fan OK 3840 Spinning at intermediate-speed
Bottom Rear Fan OK 3840 Spinning at intermediate-speed
Top Middle Fan OK 3900 Spinning at intermediate-speed
Bottom Middle Fan OK 3840 Spinning at intermediate-speed
Top Front Fan OK 3810 Spinning at intermediate-speed
Bottom Front Fan OK 3840 Spinning at intermediate-speed
'
}
Example output with TextFSM parsing:
.. code-block:: json
{
"comment": "",
"result": true,
"out": {
"sh ver": [
{
"kernel": "9.1S3.5",
"documentation": "9.1S3.5",
"boot": "9.1S3.5",
"crypto": "9.1S3.5",
"chassis": "",
"routing": "9.1S3.5",
"base": "9.1S3.5",
"model": "mx960"
}
]
}
}
'''
raw_cli_outputs = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'cli',
**{
'commands': list(commands)
}
)
# thus we can display the output as is
# in case of errors, they'll be catched in the proxy
if not raw_cli_outputs['result']:
# Error -> dispaly the output as-is.
return raw_cli_outputs
textfsm_parse = kwargs.get('textfsm_parse') or __opts__.get('napalm_cli_textfsm_parse') or\
__pillar__.get('napalm_cli_textfsm_parse', False)
if not textfsm_parse:
# No TextFSM parsing required, return raw commands.
log.debug('No TextFSM parsing requested.')
return raw_cli_outputs
if 'textfsm.extract' not in __salt__ or 'textfsm.index' not in __salt__:
raw_cli_outputs['comment'] += 'Unable to process: is TextFSM installed?'
log.error(raw_cli_outputs['comment'])
return raw_cli_outputs
textfsm_template = kwargs.get('textfsm_template')
log.debug('textfsm_template: %s', textfsm_template)
textfsm_path = kwargs.get('textfsm_path') or __opts__.get('textfsm_path') or\
__pillar__.get('textfsm_path')
log.debug('textfsm_path: %s', textfsm_path)
textfsm_template_dict = kwargs.get('textfsm_template_dict') or __opts__.get('napalm_cli_textfsm_template_dict') or\
__pillar__.get('napalm_cli_textfsm_template_dict', {})
log.debug('TextFSM command-template mapping: %s', textfsm_template_dict)
index_file = kwargs.get('index_file') or __opts__.get('textfsm_index_file') or\
__pillar__.get('textfsm_index_file')
log.debug('index_file: %s', index_file)
platform_grain_name = kwargs.get('platform_grain_name') or __opts__.get('textfsm_platform_grain') or\
__pillar__.get('textfsm_platform_grain', 'os')
log.debug('platform_grain_name: %s', platform_grain_name)
platform_column_name = kwargs.get('platform_column_name') or __opts__.get('textfsm_platform_column_name') or\
__pillar__.get('textfsm_platform_column_name', 'Platform')
log.debug('platform_column_name: %s', platform_column_name)
saltenv = kwargs.get('saltenv', 'base')
include_empty = kwargs.get('include_empty', False)
include_pat = kwargs.get('include_pat')
exclude_pat = kwargs.get('exclude_pat')
processed_cli_outputs = {
'comment': raw_cli_outputs.get('comment', ''),
'result': raw_cli_outputs['result'],
'out': {}
}
log.debug('Starting to analyse the raw outputs')
for command in list(commands):
command_output = raw_cli_outputs['out'][command]
log.debug('Output from command: %s', command)
log.debug(command_output)
processed_command_output = None
if textfsm_path:
log.debug('Using the templates under %s', textfsm_path)
processed_cli_output = __salt__['textfsm.index'](command,
platform_grain_name=platform_grain_name,
platform_column_name=platform_column_name,
output=command_output.strip(),
textfsm_path=textfsm_path,
saltenv=saltenv,
include_empty=include_empty,
include_pat=include_pat,
exclude_pat=exclude_pat)
log.debug('Processed CLI output:')
log.debug(processed_cli_output)
if not processed_cli_output['result']:
log.debug('Apparently this didnt work, returnin the raw output')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {0}: {1}.'.format(command,
processed_cli_output['comment'])
log.error(processed_cli_outputs['comment'])
elif processed_cli_output['out']:
log.debug('All good, %s has a nice output!', command)
processed_command_output = processed_cli_output['out']
else:
comment = '''\nProcessing "{}" didn't fail, but didn't return anything either. Dumping raw.'''.format(
command)
processed_cli_outputs['comment'] += comment
log.error(comment)
processed_command_output = command_output
elif textfsm_template or command in textfsm_template_dict:
if command in textfsm_template_dict:
textfsm_template = textfsm_template_dict[command]
log.debug('Using %s to process the command: %s', textfsm_template, command)
processed_cli_output = __salt__['textfsm.extract'](textfsm_template,
raw_text=command_output,
saltenv=saltenv)
log.debug('Processed CLI output:')
log.debug(processed_cli_output)
if not processed_cli_output['result']:
log.debug('Apparently this didnt work, returning '
'the raw output')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {0}: {1}'.format(command,
processed_cli_output['comment'])
log.error(processed_cli_outputs['comment'])
elif processed_cli_output['out']:
log.debug('All good, %s has a nice output!', command)
processed_command_output = processed_cli_output['out']
else:
log.debug('Processing %s didnt fail, but didnt return'
' anything either. Dumping raw.', command)
processed_command_output = command_output
else:
log.error('No TextFSM template specified, or no TextFSM path defined')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {}.'.format(command)
processed_cli_outputs['out'][command] = processed_command_output
processed_cli_outputs['comment'] = processed_cli_outputs['comment'].strip()
return processed_cli_outputs
@salt.utils.napalm.proxy_napalm_wrap
def traceroute(destination, source=None, ttl=None, timeout=None, vrf=None, **kwargs): # pylint: disable=unused-argument
'''
Calls the method traceroute from the NAPALM driver object and returns a dictionary with the result of the traceroute
command executed on the device.
destination
Hostname or address of remote host
source
Source address to use in outgoing traceroute packets
ttl
IP maximum time-to-live value (or IPv6 maximum hop-limit value)
timeout
Number of seconds to wait for response (seconds)
vrf
VRF (routing instance) for traceroute attempt
.. versionadded:: 2016.11.4
CLI Example:
.. code-block:: bash
salt '*' net.traceroute 8.8.8.8
salt '*' net.traceroute 8.8.8.8 source=127.0.0.1 ttl=5 timeout=1
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'traceroute',
**{
'destination': destination,
'source': source,
'ttl': ttl,
'timeout': timeout,
'vrf': vrf
}
)
@salt.utils.napalm.proxy_napalm_wrap
def ping(destination, source=None, ttl=None, timeout=None, size=None, count=None, vrf=None, **kwargs): # pylint: disable=unused-argument
'''
Executes a ping on the network device and returns a dictionary as a result.
destination
Hostname or IP address of remote host
source
Source address of echo request
ttl
IP time-to-live value (IPv6 hop-limit value) (1..255 hops)
timeout
Maximum wait time after sending final packet (seconds)
size
Size of request packets (0..65468 bytes)
count
Number of ping requests to send (1..2000000000 packets)
vrf
VRF (routing instance) for ping attempt
.. versionadded:: 2016.11.4
CLI Example:
.. code-block:: bash
salt '*' net.ping 8.8.8.8
salt '*' net.ping 8.8.8.8 ttl=3 size=65468
salt '*' net.ping 8.8.8.8 source=127.0.0.1 timeout=1 count=100
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'ping',
**{
'destination': destination,
'source': source,
'ttl': ttl,
'timeout': timeout,
'size': size,
'count': count,
'vrf': vrf
}
)
@salt.utils.napalm.proxy_napalm_wrap
def arp(interface='', ipaddr='', macaddr='', **kwargs): # pylint: disable=unused-argument
'''
NAPALM returns a list of dictionaries with details of the ARP entries.
:param interface: interface name to filter on
:param ipaddr: IP address to filter on
:param macaddr: MAC address to filter on
:return: List of the entries in the ARP table
CLI Example:
.. code-block:: bash
salt '*' net.arp
salt '*' net.arp macaddr='5c:5e:ab:da:3c:f0'
Example output:
.. code-block:: python
[
{
'interface' : 'MgmtEth0/RSP0/CPU0/0',
'mac' : '5c:5e:ab:da:3c:f0',
'ip' : '172.17.17.1',
'age' : 1454496274.84
},
{
'interface': 'MgmtEth0/RSP0/CPU0/0',
'mac' : '66:0e:94:96:e0:ff',
'ip' : '172.17.17.2',
'age' : 1435641582.49
}
]
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_arp_table',
**{
}
)
if not proxy_output.get('result'):
return proxy_output
arp_table = proxy_output.get('out')
if interface:
arp_table = _filter_list(arp_table, 'interface', interface)
if ipaddr:
arp_table = _filter_list(arp_table, 'ip', ipaddr)
if macaddr:
arp_table = _filter_list(arp_table, 'mac', macaddr)
proxy_output.update({
'out': arp_table
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def ipaddrs(**kwargs): # pylint: disable=unused-argument
'''
Returns IP addresses configured on the device.
:return: A dictionary with the IPv4 and IPv6 addresses of the interfaces.
Returns all configured IP addresses on all interfaces as a dictionary
of dictionaries. Keys of the main dictionary represent the name of the
interface. Values of the main dictionary represent are dictionaries
that may consist of two keys 'ipv4' and 'ipv6' (one, both or none)
which are themselvs dictionaries with the IP addresses as keys.
CLI Example:
.. code-block:: bash
salt '*' net.ipaddrs
Example output:
.. code-block:: python
{
'FastEthernet8': {
'ipv4': {
'10.66.43.169': {
'prefix_length': 22
}
}
},
'Loopback555': {
'ipv4': {
'192.168.1.1': {
'prefix_length': 24
}
},
'ipv6': {
'1::1': {
'prefix_length': 64
},
'2001:DB8:1::1': {
'prefix_length': 64
},
'FE80::3': {
'prefix_length': 'N/A'
}
}
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_interfaces_ip',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def interfaces(**kwargs): # pylint: disable=unused-argument
'''
Returns details of the interfaces on the device.
:return: Returns a dictionary of dictionaries. The keys for the first
dictionary will be the interfaces in the devices.
CLI Example:
.. code-block:: bash
salt '*' net.interfaces
Example output:
.. code-block:: python
{
'Management1': {
'is_up': False,
'is_enabled': False,
'description': '',
'last_flapped': -1,
'speed': 1000,
'mac_address': 'dead:beef:dead',
},
'Ethernet1':{
'is_up': True,
'is_enabled': True,
'description': 'foo',
'last_flapped': 1429978575.1554043,
'speed': 1000,
'mac_address': 'beef:dead:beef',
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_interfaces',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def lldp(interface='', **kwargs): # pylint: disable=unused-argument
'''
Returns a detailed view of the LLDP neighbors.
:param interface: interface name to filter on
:return: A dictionary with the LLDL neighbors. The keys are the
interfaces with LLDP activated on.
CLI Example:
.. code-block:: bash
salt '*' net.lldp
salt '*' net.lldp interface='TenGigE0/0/0/8'
Example output:
.. code-block:: python
{
'TenGigE0/0/0/8': [
{
'parent_interface': 'Bundle-Ether8',
'interface_description': 'TenGigE0/0/0/8',
'remote_chassis_id': '8c60.4f69.e96c',
'remote_system_name': 'switch',
'remote_port': 'Eth2/2/1',
'remote_port_description': 'Ethernet2/2/1',
'remote_system_description': 'Cisco Nexus Operating System (NX-OS) Software 7.1(0)N1(1a)
TAC support: http://www.cisco.com/tac
Copyright (c) 2002-2015, Cisco Systems, Inc. All rights reserved.',
'remote_system_capab': 'B, R',
'remote_system_enable_capab': 'B'
}
]
}
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_lldp_neighbors_detail',
**{
}
)
if not proxy_output.get('result'):
return proxy_output
lldp_neighbors = proxy_output.get('out')
if interface:
lldp_neighbors = {interface: lldp_neighbors.get(interface)}
proxy_output.update({
'out': lldp_neighbors
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def mac(address='', interface='', vlan=0, **kwargs): # pylint: disable=unused-argument
'''
Returns the MAC Address Table on the device.
:param address: MAC address to filter on
:param interface: Interface name to filter on
:param vlan: VLAN identifier
:return: A list of dictionaries representing the entries in the MAC Address Table
CLI Example:
.. code-block:: bash
salt '*' net.mac
salt '*' net.mac vlan=10
Example output:
.. code-block:: python
[
{
'mac' : '00:1c:58:29:4a:71',
'interface' : 'xe-3/0/2',
'static' : False,
'active' : True,
'moves' : 1,
'vlan' : 10,
'last_move' : 1454417742.58
},
{
'mac' : '8c:60:4f:58:e1:c1',
'interface' : 'xe-1/0/1',
'static' : False,
'active' : True,
'moves' : 2,
'vlan' : 42,
'last_move' : 1453191948.11
}
]
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_mac_address_table',
**{
}
)
if not proxy_output.get('result'):
# if negative, leave the output unchanged
return proxy_output
mac_address_table = proxy_output.get('out')
if vlan and isinstance(vlan, int):
mac_address_table = _filter_list(mac_address_table, 'vlan', vlan)
if address:
mac_address_table = _filter_list(mac_address_table, 'mac', address)
if interface:
mac_address_table = _filter_list(mac_address_table, 'interface', interface)
proxy_output.update({
'out': mac_address_table
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def config(source=None, **kwargs): # pylint: disable=unused-argument
'''
.. versionadded:: 2017.7.0
Return the whole configuration of the network device. By default, it will
return all possible configuration sources supported by the network device.
At most, there will be:
- running config
- startup config
- candidate config
To return only one of the configurations, you can use the ``source``
argument.
source
Which configuration type you want to display, default is all of them.
Options:
- running
- candidate
- startup
:return:
The object returned is a dictionary with the following keys:
- running (string): Representation of the native running configuration.
- candidate (string): Representation of the native candidate configuration.
If the device doesn't differentiate between running and startup
configuration this will an empty string.
- startup (string): Representation of the native startup configuration.
If the device doesn't differentiate between running and startup
configuration this will an empty string.
CLI Example:
.. code-block:: bash
salt '*' net.config
salt '*' net.config source=candidate
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_config',
**{
'retrieve': source
}
)
@salt.utils.napalm.proxy_napalm_wrap
def optics(**kwargs): # pylint: disable=unused-argument
'''
.. versionadded:: 2017.7.0
Fetches the power usage on the various transceivers installed
on the network device (in dBm), and returns a view that conforms with the
OpenConfig model openconfig-platform-transceiver.yang.
:return:
Returns a dictionary where the keys are as listed below:
* intf_name (unicode)
* physical_channels
* channels (list of dicts)
* index (int)
* state
* input_power
* instant (float)
* avg (float)
* min (float)
* max (float)
* output_power
* instant (float)
* avg (float)
* min (float)
* max (float)
* laser_bias_current
* instant (float)
* avg (float)
* min (float)
* max (float)
CLI Example:
.. code-block:: bash
salt '*' net.optics
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_optics',
**{
}
)
# <---- Call NAPALM getters --------------------------------------------------------------------------------------------
# ----- Configuration specific functions ------------------------------------------------------------------------------>
@salt.utils.napalm.proxy_napalm_wrap
def load_config(filename=None,
text=None,
test=False,
commit=True,
debug=False,
replace=False,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
commit_jid=None,
inherit_napalm_device=None,
saltenv='base',
**kwargs): # pylint: disable=unused-argument
'''
Applies configuration changes on the device. It can be loaded from a file or from inline string.
If you send both a filename and a string containing the configuration, the file has higher precedence.
By default this function will commit the changes. If there are no changes, it does not commit and
the flag ``already_configured`` will be set as ``True`` to point this out.
To avoid committing the configuration, set the argument ``test`` to ``True`` and will discard (dry run).
To keep the changes but not commit, set ``commit`` to ``False``.
To replace the config, set ``replace`` to ``True``.
filename
Path to the file containing the desired configuration.
This can be specified using the absolute path to the file,
or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
.. versionchanged:: 2018.3.0
text
String containing the desired configuration.
This argument is ignored when ``filename`` is specified.
test: False
Dry run? If set as ``True``, will apply the config, discard and return the changes. Default: ``False``
and will commit the changes on the device.
commit: True
Commit? Default: ``True``.
debug: False
Debug mode. Will insert a new key under the output dictionary, as ``loaded_config`` containing the raw
configuration loaded on the device.
.. versionadded:: 2016.11.2
replace: False
Load and replace the configuration. Default: ``False``.
.. versionadded:: 2016.11.2
commit_in: ``None``
Commit the changes in a specific number of minutes / hours. Example of
accepted formats: ``5`` (commit in 5 minutes), ``2m`` (commit in 2
minutes), ``1h`` (commit the changes in 1 hour)`, ``5h30m`` (commit
the changes in 5 hours and 30 minutes).
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
commit_at: ``None``
Commit the changes at a specific time. Example of accepted formats:
``1am`` (will commit the changes at the next 1AM), ``13:20`` (will
commit at 13:20), ``1:20am``, etc.
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
revert_in: ``None``
Commit and revert the changes in a specific number of minutes / hours.
Example of accepted formats: ``5`` (revert in 5 minutes), ``2m`` (revert
in 2 minutes), ``1h`` (revert the changes in 1 hour)`, ``5h30m`` (revert
the changes in 5 hours and 30 minutes).
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
revert_at: ``None``
Commit and revert the changes at a specific time. Example of accepted
formats: ``1am`` (will commit and revert the changes at the next 1AM),
``13:20`` (will commit and revert at 13:20), ``1:20am``, etc.
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
saltenv: ``base``
Specifies the Salt environment name.
.. versionadded:: 2018.3.0
:return: a dictionary having the following keys:
* result (bool): if the config was applied successfully. It is ``False`` only in case of failure. In case \
there are no changes to be applied and successfully performs all operations it is still ``True`` and so will be \
the ``already_configured`` flag (example below)
* comment (str): a message for the user
* already_configured (bool): flag to check if there were no changes applied
* loaded_config (str): the configuration loaded on the device. Requires ``debug`` to be set as ``True``
* diff (str): returns the config changes applied
CLI Example:
.. code-block:: bash
salt '*' net.load_config text='ntp peer 192.168.0.1'
salt '*' net.load_config filename='/absolute/path/to/your/file'
salt '*' net.load_config filename='/absolute/path/to/your/file' test=True
salt '*' net.load_config filename='/absolute/path/to/your/file' commit=False
Example output:
.. code-block:: python
{
'comment': 'Configuration discarded.',
'already_configured': False,
'result': True,
'diff': '[edit interfaces xe-0/0/5]+ description "Adding a description";'
}
'''
fun = 'load_merge_candidate'
if replace:
fun = 'load_replace_candidate'
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
if filename:
text = __salt__['cp.get_file_str'](filename, saltenv=saltenv)
if text is False:
# When using salt:// or https://, if the resource is not available,
# it will either raise an exception, or return False.
ret = {
'result': False,
'out': None
}
ret['comment'] = 'Unable to read from {}. Please specify a valid file or text.'.format(filename)
log.error(ret['comment'])
return ret
if commit_jid:
# When the commit_jid argument is passed, it probably is a scheduled
# commit to be executed, and filename is a temporary file which
# can be removed after reading it.
salt.utils.files.safe_rm(filename)
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
fun,
**{
'config': text
}
)
return _config_logic(napalm_device, # pylint: disable=undefined-variable
_loaded,
test=test,
debug=debug,
replace=replace,
commit_config=commit,
loaded_config=text,
commit_at=commit_at,
commit_in=commit_in,
revert_in=revert_in,
revert_at=revert_at,
commit_jid=commit_jid,
**kwargs)
@salt.utils.napalm.proxy_napalm_wrap
def load_template(template_name=None,
template_source=None,
context=None,
defaults=None,
template_engine='jinja',
saltenv='base',
template_hash=None,
template_hash_name=None,
skip_verify=False,
test=False,
commit=True,
debug=False,
replace=False,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
inherit_napalm_device=None, # pylint: disable=unused-argument
**template_vars):
'''
Renders a configuration template (default: Jinja) and loads the result on the device.
By default this function will commit the changes. If there are no changes,
it does not commit, discards he config and the flag ``already_configured``
will be set as ``True`` to point this out.
To avoid committing the configuration, set the argument ``test`` to ``True``
and will discard (dry run).
To preserve the changes, set ``commit`` to ``False``.
However, this is recommended to be used only in exceptional cases
when there are applied few consecutive states
and/or configuration changes.
Otherwise the user might forget that the config DB is locked
and the candidate config buffer is not cleared/merged in the running config.
To replace the config, set ``replace`` to ``True``.
template_name
Identifies path to the template source.
The template can be either stored on the local machine, either remotely.
The recommended location is under the ``file_roots``
as specified in the master config file.
For example, let's suppose the ``file_roots`` is configured as:
.. code-block:: yaml
file_roots:
base:
- /etc/salt/states
Placing the template under ``/etc/salt/states/templates/example.jinja``,
it can be used as ``salt://templates/example.jinja``.
Alternatively, for local files, the user can specify the absolute path.
If remotely, the source can be retrieved via ``http``, ``https`` or ``ftp``.
Examples:
- ``salt://my_template.jinja``
- ``/absolute/path/to/my_template.jinja``
- ``http://example.com/template.cheetah``
- ``https:/example.com/template.mako``
- ``ftp://example.com/template.py``
.. versionchanged:: 2019.2.0
This argument can now support a list of templates to be rendered.
The resulting configuration text is loaded at once, as a single
configuration chunk.
template_source: None
Inline config template to be rendered and loaded on the device.
template_hash: None
Hash of the template file. Format: ``{hash_type: 'md5', 'hsum': <md5sum>}``
.. versionadded:: 2016.11.2
context: None
Overrides default context variables passed to the template.
.. versionadded:: 2019.2.0
template_hash_name: None
When ``template_hash`` refers to a remote file,
this specifies the filename to look for in that file.
.. versionadded:: 2016.11.2
saltenv: ``base``
Specifies the template environment.
This will influence the relative imports inside the templates.
.. versionadded:: 2016.11.2
template_engine: jinja
The following templates engines are supported:
- :mod:`cheetah<salt.renderers.cheetah>`
- :mod:`genshi<salt.renderers.genshi>`
- :mod:`jinja<salt.renderers.jinja>`
- :mod:`mako<salt.renderers.mako>`
- :mod:`py<salt.renderers.py>`
- :mod:`wempy<salt.renderers.wempy>`
.. versionadded:: 2016.11.2
skip_verify: True
If ``True``, hash verification of remote file sources
(``http://``, ``https://``, ``ftp://``) will be skipped,
and the ``source_hash`` argument will be ignored.
.. versionadded:: 2016.11.2
test: False
Dry run? If set to ``True``, will apply the config,
discard and return the changes.
Default: ``False`` and will commit the changes on the device.
commit: True
Commit? (default: ``True``)
debug: False
Debug mode. Will insert a new key under the output dictionary,
as ``loaded_config`` containing the raw result after the template was rendered.
.. versionadded:: 2016.11.2
replace: False
Load and replace the configuration.
.. versionadded:: 2016.11.2
commit_in: ``None``
Commit the changes in a specific number of minutes / hours. Example of
accepted formats: ``5`` (commit in 5 minutes), ``2m`` (commit in 2
minutes), ``1h`` (commit the changes in 1 hour)`, ``5h30m`` (commit
the changes in 5 hours and 30 minutes).
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
commit_at: ``None``
Commit the changes at a specific time. Example of accepted formats:
``1am`` (will commit the changes at the next 1AM), ``13:20`` (will
commit at 13:20), ``1:20am``, etc.
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
revert_in: ``None``
Commit and revert the changes in a specific number of minutes / hours.
Example of accepted formats: ``5`` (revert in 5 minutes), ``2m`` (revert
in 2 minutes), ``1h`` (revert the changes in 1 hour)`, ``5h30m`` (revert
the changes in 5 hours and 30 minutes).
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
revert_at: ``None``
Commit and revert the changes at a specific time. Example of accepted
formats: ``1am`` (will commit and revert the changes at the next 1AM),
``13:20`` (will commit and revert at 13:20), ``1:20am``, etc.
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
defaults: None
Default variables/context passed to the template.
.. versionadded:: 2016.11.2
template_vars
Dictionary with the arguments/context to be used when the template is rendered.
.. note::
Do not explicitly specify this argument. This represents any other
variable that will be sent to the template rendering system.
Please see the examples below!
.. note::
It is more recommended to use the ``context`` argument to avoid
conflicts between CLI arguments and template variables.
:return: a dictionary having the following keys:
- result (bool): if the config was applied successfully. It is ``False``
only in case of failure. In case there are no changes to be applied and
successfully performs all operations it is still ``True`` and so will be
the ``already_configured`` flag (example below)
- comment (str): a message for the user
- already_configured (bool): flag to check if there were no changes applied
- loaded_config (str): the configuration loaded on the device, after
rendering the template. Requires ``debug`` to be set as ``True``
- diff (str): returns the config changes applied
The template can use variables from the ``grains``, ``pillar`` or ``opts``, for example:
.. code-block:: jinja
{% set router_model = grains.get('model') -%}
{% set router_vendor = grains.get('vendor') -%}
{% set os_version = grains.get('version') -%}
{% set hostname = pillar.get('proxy', {}).get('host') -%}
{% if router_vendor|lower == 'juniper' %}
system {
host-name {{hostname}};
}
{% elif router_vendor|lower == 'cisco' %}
hostname {{hostname}}
{% endif %}
CLI Examples:
.. code-block:: bash
salt '*' net.load_template set_ntp_peers peers=[192.168.0.1] # uses NAPALM default templates
# inline template:
salt -G 'os:junos' net.load_template template_source='system { host-name {{host_name}}; }' \
host_name='MX480.lab'
# inline template using grains info:
salt -G 'os:junos' net.load_template \
template_source='system { host-name {{grains.model}}.lab; }'
# if the device is a MX480, the command above will set the hostname as: MX480.lab
# inline template using pillar data:
salt -G 'os:junos' net.load_template template_source='system { host-name {{pillar.proxy.host}}; }'
salt '*' net.load_template https://bit.ly/2OhSgqP hostname=example # will commit
salt '*' net.load_template https://bit.ly/2OhSgqP hostname=example test=True # dry run
salt '*' net.load_template salt://templates/example.jinja debug=True # Using the salt:// URI
# render a mako template:
salt '*' net.load_template salt://templates/example.mako template_engine=mako debug=True
# render remote template
salt -G 'os:junos' net.load_template http://bit.ly/2fReJg7 test=True debug=True peers=['192.168.0.1']
salt -G 'os:ios' net.load_template http://bit.ly/2gKOj20 test=True debug=True peers=['192.168.0.1']
# render multiple templates at once
salt '*' net.load_template "['https://bit.ly/2OhSgqP', 'salt://templates/example.jinja']" context="{'hostname': 'example'}"
Example output:
.. code-block:: python
{
'comment': '',
'already_configured': False,
'result': True,
'diff': '[edit system]+ host-name edge01.bjm01',
'loaded_config': 'system { host-name edge01.bjm01; }''
}
'''
_rendered = ''
_loaded = {
'result': True,
'comment': '',
'out': None
}
loaded_config = None
# prechecks
deprecated_args = ('template_user', 'template_attrs', 'template_group', 'template_mode')
for deprecated_arg in deprecated_args:
if template_vars.get(deprecated_arg):
del template_vars[deprecated_arg]
salt.utils.versions.warn_until(
'Sodium',
('The \'{arg}\' argument to \'net.load_template\' is deprecated '
'and has been ignored').format(arg=deprecated_arg)
)
if template_engine not in salt.utils.templates.TEMPLATE_REGISTRY:
_loaded.update({
'result': False,
'comment': 'Invalid templating engine! Choose between: {tpl_eng_opts}'.format(
tpl_eng_opts=', '.join(list(salt.utils.templates.TEMPLATE_REGISTRY.keys()))
)
})
return _loaded # exit
# to check if will be rendered by salt or NAPALM
salt_render_prefixes = ('salt://', 'http://', 'https://', 'ftp://')
salt_render = False
file_exists = False
if not isinstance(template_name, (tuple, list)):
for salt_render_prefix in salt_render_prefixes:
if not salt_render:
salt_render = salt_render or template_name.startswith(salt_render_prefix)
file_exists = __salt__['file.file_exists'](template_name)
if template_source or file_exists or salt_render or isinstance(template_name, (tuple, list)):
# either inline template
# either template in a custom path
# either abs path send
# either starts with salt:// and
# then use Salt render system
if context is None:
context = {}
context.update(template_vars)
# if needed to render the template send as inline arg
if template_source:
# render the content
_rendered = __salt__['file.apply_template_on_contents'](
contents=template_source,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv
)
if not isinstance(_rendered, six.string_types):
if 'result' in _rendered:
_loaded['result'] = _rendered['result']
else:
_loaded['result'] = False
if 'comment' in _rendered:
_loaded['comment'] = _rendered['comment']
else:
_loaded['comment'] = 'Error while rendering the template.'
return _loaded
else:
# render the file - either local, either remote
if not isinstance(template_name, (list, tuple)):
template_name = [template_name]
if template_hash_name and not isinstance(template_hash_name, (list, tuple)):
template_hash_name = [template_hash_name]
elif not template_hash_name:
template_hash_name = [None] * len(template_name)
if template_hash and isinstance(template_hash, six.string_types) and not\
(template_hash.startswith('salt://') or template_hash.startswith('file://')):
# If the template hash is passed as string, and it's not a file
# (starts with the salt:// or file:// URI), then make it a list
# of 1 element (for the iteration below)
template_hash = [template_hash]
elif template_hash and isinstance(template_hash, six.string_types) and\
(template_hash.startswith('salt://') or template_hash.startswith('file://')):
# If the template hash is a file URI, then provide the same value
# for each of the templates in the list, as probably they all
# share the same hash file, otherwise the user should provide
# this as a list
template_hash = [template_hash] * len(template_name)
elif not template_hash:
template_hash = [None] * len(template_name)
for tpl_index, tpl_name in enumerate(template_name):
tpl_hash = template_hash[tpl_index]
tpl_hash_name = template_hash_name[tpl_index]
_rand_filename = __salt__['random.hash'](tpl_name, 'md5')
_temp_file = __salt__['file.join']('/tmp', _rand_filename)
_managed = __salt__['file.get_managed'](name=_temp_file,
source=tpl_name,
source_hash=tpl_hash,
source_hash_name=tpl_hash_name,
user=None,
group=None,
mode=None,
attrs=None,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv,
skip_verify=skip_verify)
if not isinstance(_managed, (list, tuple)) and isinstance(_managed, six.string_types):
_loaded['comment'] += _managed
_loaded['result'] = False
elif isinstance(_managed, (list, tuple)) and not _managed:
_loaded['result'] = False
_loaded['comment'] += 'Error while rendering the template.'
elif isinstance(_managed, (list, tuple)) and not _managed[0]:
_loaded['result'] = False
_loaded['comment'] += _managed[-1] # contains the error message
if _loaded['result']: # all good
_temp_tpl_file = _managed[0]
_temp_tpl_file_exists = __salt__['file.file_exists'](_temp_tpl_file)
if not _temp_tpl_file_exists:
_loaded['result'] = False
_loaded['comment'] += 'Error while rendering the template.'
return _loaded
_rendered += __salt__['file.read'](_temp_tpl_file)
__salt__['file.remove'](_temp_tpl_file)
else:
return _loaded # exit
loaded_config = _rendered
if _loaded['result']: # all good
fun = 'load_merge_candidate'
if replace: # replace requested
fun = 'load_replace_candidate'
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
fun,
**{
'config': _rendered
}
)
else:
salt.utils.versions.warn_until(
'Sodium',
'Native NAPALM templates support will be removed in the Sodium '
'release. Please consider using the Salt rendering pipeline instead.'
'If you are using the \'netntp\', \'netsnmp\', or \'netusers\' Salt '
'State modules, you can ignore this message'
)
# otherwise, use NAPALM render system, injecting pillar/grains/opts vars
load_templates_params = defaults if defaults else {}
load_templates_params.update(template_vars)
load_templates_params.update(
{
'template_name': template_name,
'template_source': template_source, # inline template
'pillar': __pillar__, # inject pillar content
'grains': __grains__, # inject grains content
'opts': __opts__ # inject opts content
}
)
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
# so we'll set the CLOSE global explicitly as False
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'load_template',
**load_templates_params
)
return _config_logic(napalm_device, # pylint: disable=undefined-variable
_loaded,
test=test,
debug=debug,
replace=replace,
commit_config=commit,
loaded_config=loaded_config,
commit_at=commit_at,
commit_in=commit_in,
revert_in=revert_in,
revert_at=revert_at,
**template_vars)
@salt.utils.napalm.proxy_napalm_wrap
def commit(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Commits the configuration changes made on the network device.
CLI Example:
.. code-block:: bash
salt '*' net.commit
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'commit_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def discard_config(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
"""
Discards the changes applied.
CLI Example:
.. code-block:: bash
salt '*' net.discard_config
"""
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'discard_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def compare_config(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Returns the difference between the running config and the candidate config.
CLI Example:
.. code-block:: bash
salt '*' net.compare_config
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'compare_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def rollback(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Rollbacks the configuration.
CLI Example:
.. code-block:: bash
salt '*' net.rollback
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'rollback',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def config_changed(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Will prompt if the configuration has been changed.
:return: A tuple with a boolean that specifies if the config was changed on the device.\
And a string that provides more details of the reason why the configuration was not changed.
CLI Example:
.. code-block:: bash
salt '*' net.config_changed
'''
is_config_changed = False
reason = ''
try_compare = compare_config(inherit_napalm_device=napalm_device) # pylint: disable=undefined-variable
if try_compare.get('result'):
if try_compare.get('out'):
is_config_changed = True
else:
reason = 'Configuration was not changed on the device.'
else:
reason = try_compare.get('comment')
return is_config_changed, reason
@salt.utils.napalm.proxy_napalm_wrap
def cancel_commit(jid):
'''
.. versionadded:: 2019.2.0
Cancel a commit scheduled to be executed via the ``commit_in`` and
``commit_at`` arguments from the
:py:func:`net.load_template <salt.modules.napalm_network.load_template>` or
:py:func:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit ID is displayed when the commit is scheduled
via the functions named above.
CLI Example:
.. code-block:: bash
salt '*' net.cancel_commit 20180726083540640360
'''
job_name = '__napalm_commit_{}'.format(jid)
removed = __salt__['schedule.delete'](job_name)
if removed['result']:
saved = __salt__['schedule.save']()
removed['comment'] = 'Commit #{jid} cancelled.'.format(jid=jid)
else:
removed['comment'] = 'Unable to find commit #{jid}.'.format(jid=jid)
return removed
def confirm_commit(jid):
'''
.. versionadded:: 2019.2.0
Confirm a commit scheduled to be reverted via the ``revert_in`` and
``revert_at`` arguments from the
:mod:`net.load_template <salt.modules.napalm_network.load_template>` or
:mod:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit ID is displayed when the commit confirmed
is scheduled via the functions named above.
CLI Example:
.. code-block:: bash
salt '*' net.confirm_commit 20180726083540640360
'''
if __grains__['os'] == 'junos':
# Confirm the commit, by committing (i.e., invoking the RPC call)
confirmed = __salt__['napalm.junos_commit']()
confirmed['result'] = confirmed.pop('out')
confirmed['comment'] = confirmed.pop('message')
else:
confirmed = cancel_commit(jid)
if confirmed['result']:
confirmed['comment'] = 'Commit #{jid} confirmed.'.format(jid=jid)
return confirmed
def save_config(source=None,
path=None):
'''
.. versionadded:: 2019.2.0
Save the configuration to a file on the local file system.
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``,
``startup``. Default: ``running``.
path
Absolute path to file where to save the configuration.
To push the files to the Master, use
:mod:`cp.push <salt.modules.cp.push>` Execution function.
CLI Example:
.. code-block:: bash
salt '*' net.save_config source=running
'''
if not source:
source = 'running'
if not path:
path = salt.utils.files.mkstemp()
running_config = __salt__['net.config'](source=source)
if not running_config or not running_config['result']:
log.error('Unable to retrieve the config')
return running_config
with salt.utils.files.fopen(path, 'w') as fh_:
fh_.write(running_config['out'][source])
return {
'result': True,
'out': path,
'comment': '{source} config saved to {path}'.format(source=source, path=path)
}
def replace_pattern(pattern,
repl,
count=0,
flags=8,
bufsize=1,
append_if_not_found=False,
prepend_if_not_found=False,
not_found_content=None,
search_only=False,
show_changes=True,
backslash_literal=False,
source=None,
path=None,
test=False,
replace=True,
debug=False,
commit=True):
'''
.. versionadded:: 2019.2.0
Replace occurrences of a pattern in the configuration source. If
``show_changes`` is ``True``, then a diff of what changed will be returned,
otherwise a ``True`` will be returned when changes are made, and ``False``
when no changes are made.
This is a pure Python implementation that wraps Python's :py:func:`~re.sub`.
pattern
A regular expression, to be matched using Python's
:py:func:`~re.search`.
repl
The replacement text.
count: ``0``
Maximum number of pattern occurrences to be replaced. If count is a
positive integer ``n``, only ``n`` occurrences will be replaced,
otherwise all occurrences will be replaced.
flags (list or int): ``8``
A list of flags defined in the ``re`` module documentation from the
Python standard library. Each list item should be a string that will
correlate to the human-friendly flag name. E.g., ``['IGNORECASE',
'MULTILINE']``. Optionally, ``flags`` may be an int, with a value
corresponding to the XOR (``|``) of all the desired flags. Defaults to
8 (which supports 'MULTILINE').
bufsize (int or str): ``1``
How much of the configuration to buffer into memory at once. The
default value ``1`` processes one line at a time. The special value
``file`` may be specified which will read the entire file into memory
before processing.
append_if_not_found: ``False``
If set to ``True``, and pattern is not found, then the content will be
appended to the file.
prepend_if_not_found: ``False``
If set to ``True`` and pattern is not found, then the content will be
prepended to the file.
not_found_content
Content to use for append/prepend if not found. If None (default), uses
``repl``. Useful when ``repl`` uses references to group in pattern.
search_only: ``False``
If set to true, this no changes will be performed on the file, and this
function will simply return ``True`` if the pattern was matched, and
``False`` if not.
show_changes: ``True``
If ``True``, return a diff of changes made. Otherwise, return ``True``
if changes were made, and ``False`` if not.
backslash_literal: ``False``
Interpret backslashes as literal backslashes for the repl and not
escape characters. This will help when using append/prepend so that
the backslashes are not interpreted for the repl on the second run of
the state.
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path
Save the temporary configuration to a specific path, then read from
there.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' net.replace_pattern "bind-address\\s*=" "bind-address:"
CLI Example:
.. code-block:: bash
salt '*' net.replace_pattern PREFIX-LIST_NAME new-prefix-list-name
salt '*' net.replace_pattern bgp-group-name new-bgp-group-name count=1
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
replace_pattern = __salt__['file.replace'](path,
pattern,
repl,
count=count,
flags=flags,
bufsize=bufsize,
append_if_not_found=append_if_not_found,
prepend_if_not_found=prepend_if_not_found,
not_found_content=not_found_content,
search_only=search_only,
show_changes=show_changes,
backslash_literal=backslash_literal)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
def blockreplace(marker_start,
marker_end,
content='',
append_if_not_found=False,
prepend_if_not_found=False,
show_changes=True,
append_newline=False,
source='running',
path=None,
test=False,
commit=True,
debug=False,
replace=True):
'''
.. versionadded:: 2019.2.0
Replace content of the configuration source, delimited by the line markers.
A block of content delimited by comments can help you manage several lines
without worrying about old entries removal.
marker_start
The line content identifying a line as the start of the content block.
Note that the whole line containing this marker will be considered,
so whitespace or extra content before or after the marker is included
in final output.
marker_end
The line content identifying a line as the end of the content block.
Note that the whole line containing this marker will be considered,
so whitespace or extra content before or after the marker is included
in final output.
content
The content to be used between the two lines identified by
``marker_start`` and ``marker_stop``.
append_if_not_found: ``False``
If markers are not found and set to True then, the markers and content
will be appended to the file.
prepend_if_not_found: ``False``
If markers are not found and set to True then, the markers and content
will be prepended to the file.
append_newline: ``False``
Controls whether or not a newline is appended to the content block.
If the value of this argument is ``True`` then a newline will be added
to the content block. If it is ``False``, then a newline will not be
added to the content block. If it is ``None`` then a newline will only
be added to the content block if it does not already end in a newline.
show_changes: ``True``
Controls how changes are presented. If ``True``, this function will
return the of the changes made.
If ``False``, then it will return a boolean (``True`` if any changes
were made, otherwise False).
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path: ``None``
Save the temporary configuration to a specific path, then read from
there. This argument is optional, can be used when you prefers a
particular location of the temporary file.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
CLI Example:
.. code-block:: bash
salt '*' net.blockreplace 'ntp' 'interface' ''
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
replace_pattern = __salt__['file.blockreplace'](path,
marker_start=marker_start,
marker_end=marker_end,
content=content,
append_if_not_found=append_if_not_found,
prepend_if_not_found=prepend_if_not_found,
show_changes=show_changes,
append_newline=append_newline)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
def patch(patchfile,
options='',
saltenv='base',
source_hash=None,
show_changes=True,
source='running',
path=None,
test=False,
commit=True,
debug=False,
replace=True):
'''
.. versionadded:: 2019.2.0
Apply a patch to the configuration source, and load the result into the
running config of the device.
patchfile
A patch file to apply to the configuration source.
options
Options to pass to patch.
source_hash
If the patch file (specified via the ``patchfile`` argument) is an
HTTP(S) or FTP URL and the file exists in the minion's file cache, this
option can be passed to keep the minion from re-downloading the file if
the cached copy matches the specified hash.
show_changes: ``True``
Controls how changes are presented. If ``True``, this function will
return the of the changes made.
If ``False``, then it will return a boolean (``True`` if any changes
were made, otherwise False).
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path: ``None``
Save the temporary configuration to a specific path, then read from
there. This argument is optional, can the user prefers a particular
location of the temporary file.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
CLI Example:
.. code-block:: bash
salt '*' net.patch https://example.com/running_config.patch
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
patchfile_cache = __salt__['cp.cache_file'](patchfile)
if patchfile_cache is False:
return {
'out': None,
'result': False,
'comment': 'The file "{}" does not exist.'.format(patchfile)
}
replace_pattern = __salt__['file.patch'](path,
patchfile_cache,
options=options)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
# <---- Configuration specific functions -------------------------------------------------------------------------------
|
saltstack/salt
|
salt/modules/napalm_network.py
|
cancel_commit
|
python
|
def cancel_commit(jid):
'''
.. versionadded:: 2019.2.0
Cancel a commit scheduled to be executed via the ``commit_in`` and
``commit_at`` arguments from the
:py:func:`net.load_template <salt.modules.napalm_network.load_template>` or
:py:func:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit ID is displayed when the commit is scheduled
via the functions named above.
CLI Example:
.. code-block:: bash
salt '*' net.cancel_commit 20180726083540640360
'''
job_name = '__napalm_commit_{}'.format(jid)
removed = __salt__['schedule.delete'](job_name)
if removed['result']:
saved = __salt__['schedule.save']()
removed['comment'] = 'Commit #{jid} cancelled.'.format(jid=jid)
else:
removed['comment'] = 'Unable to find commit #{jid}.'.format(jid=jid)
return removed
|
.. versionadded:: 2019.2.0
Cancel a commit scheduled to be executed via the ``commit_in`` and
``commit_at`` arguments from the
:py:func:`net.load_template <salt.modules.napalm_network.load_template>` or
:py:func:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit ID is displayed when the commit is scheduled
via the functions named above.
CLI Example:
.. code-block:: bash
salt '*' net.cancel_commit 20180726083540640360
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_network.py#L2238-L2262
| null |
# -*- coding: utf-8 -*-
'''
NAPALM Network
==============
Basic methods for interaction with the network device through the virtual proxy 'napalm'.
:codeauthor: Mircea Ulinic <mircea@cloudflare.com> & Jerome Fleury <jf@cloudflare.com>
:maturity: new
:depends: napalm
:platform: unix
Dependencies
------------
- :mod:`napalm proxy minion <salt.proxy.napalm>`
.. versionadded:: 2016.11.0
.. versionchanged:: 2017.7.0
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import time
import logging
import datetime
log = logging.getLogger(__name__)
# Import Salt libs
from salt.ext import six
import salt.utils.files
import salt.utils.napalm
import salt.utils.versions
import salt.utils.templates
# Import 3rd-party libs
try:
import jxmlease # pylint: disable=unused-import
HAS_JXMLEASE = True
except ImportError:
HAS_JXMLEASE = False
# ----------------------------------------------------------------------------------------------------------------------
# module properties
# ----------------------------------------------------------------------------------------------------------------------
__virtualname__ = 'net'
__proxyenabled__ = ['*']
__virtual_aliases__ = ('napalm_net',)
# uses NAPALM-based proxy to interact with network devices
# ----------------------------------------------------------------------------------------------------------------------
# property functions
# ----------------------------------------------------------------------------------------------------------------------
def __virtual__():
'''
NAPALM library must be installed for this module to work and run in a (proxy) minion.
'''
return salt.utils.napalm.virtual(__opts__, __virtualname__, __file__)
# ----------------------------------------------------------------------------------------------------------------------
# helper functions -- will not be exported
# ----------------------------------------------------------------------------------------------------------------------
def _filter_list(input_list, search_key, search_value):
'''
Filters a list of dictionary by a set of key-value pair.
:param input_list: is a list of dictionaries
:param search_key: is the key we are looking for
:param search_value: is the value we are looking for the key specified in search_key
:return: filered list of dictionaries
'''
output_list = list()
for dictionary in input_list:
if dictionary.get(search_key) == search_value:
output_list.append(dictionary)
return output_list
def _filter_dict(input_dict, search_key, search_value):
'''
Filters a dictionary of dictionaries by a key-value pair.
:param input_dict: is a dictionary whose values are lists of dictionaries
:param search_key: is the key in the leaf dictionaries
:param search_values: is the value in the leaf dictionaries
:return: filtered dictionary
'''
output_dict = dict()
for key, key_list in six.iteritems(input_dict):
key_list_filtered = _filter_list(key_list, search_key, search_value)
if key_list_filtered:
output_dict[key] = key_list_filtered
return output_dict
def _safe_commit_config(loaded_result, napalm_device):
_commit = commit(inherit_napalm_device=napalm_device) # calls the function commit, defined below
if not _commit.get('result', False):
# if unable to commit
loaded_result['comment'] += _commit['comment'] if _commit.get('comment') else 'Unable to commit.'
loaded_result['result'] = False
# unable to commit, something went wrong
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
return _commit
def _safe_dicard_config(loaded_result, napalm_device):
'''
'''
log.debug('Discarding the config')
log.debug(loaded_result)
_discarded = discard_config(inherit_napalm_device=napalm_device)
if not _discarded.get('result', False):
loaded_result['comment'] += _discarded['comment'] if _discarded.get('comment') \
else 'Unable to discard config.'
loaded_result['result'] = False
# make sure it notifies
# that something went wrong
_explicit_close(napalm_device)
__context__['retcode'] = 1
return loaded_result
return _discarded
def _explicit_close(napalm_device):
'''
Will explicily close the config session with the network device,
when running in a now-always-alive proxy minion or regular minion.
This helper must be used in configuration-related functions,
as the session is preserved and not closed before making any changes.
'''
if salt.utils.napalm.not_always_alive(__opts__):
# force closing the configuration session
# when running in a non-always-alive proxy
# or regular minion
try:
napalm_device['DRIVER'].close()
except Exception as err:
log.error('Unable to close the temp connection with the device:')
log.error(err)
log.error('Please report.')
def _config_logic(napalm_device,
loaded_result,
test=False,
debug=False,
replace=False,
commit_config=True,
loaded_config=None,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
commit_jid=None,
**kwargs):
'''
Builds the config logic for `load_config` and `load_template` functions.
'''
# As the Salt logic is built around independent events
# when it comes to configuration changes in the
# candidate DB on the network devices, we need to
# make sure we're using the same session.
# Hence, we need to pass the same object around.
# the napalm_device object is inherited from
# the load_config or load_template functions
# and forwarded to compare, discard, commit etc.
# then the decorator will make sure that
# if not proxy (when the connection is always alive)
# and the `inherit_napalm_device` is set,
# `napalm_device` will be overridden.
# See `salt.utils.napalm.proxy_napalm_wrap` decorator.
current_jid = kwargs.get('__pub_jid')
if not current_jid:
current_jid = '{0:%Y%m%d%H%M%S%f}'.format(datetime.datetime.now())
loaded_result['already_configured'] = False
loaded_result['loaded_config'] = ''
if debug:
loaded_result['loaded_config'] = loaded_config
_compare = compare_config(inherit_napalm_device=napalm_device)
if _compare.get('result', False):
loaded_result['diff'] = _compare.get('out')
loaded_result.pop('out', '') # not needed
else:
loaded_result['diff'] = None
loaded_result['result'] = False
loaded_result['comment'] = _compare.get('comment')
__context__['retcode'] = 1
return loaded_result
_loaded_res = loaded_result.get('result', False)
if not _loaded_res or test:
# if unable to load the config (errors / warnings)
# or in testing mode,
# will discard the config
if loaded_result['comment']:
loaded_result['comment'] += '\n'
if not loaded_result.get('diff', ''):
loaded_result['already_configured'] = True
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
loaded_result['comment'] += 'Configuration discarded.'
# loaded_result['result'] = False not necessary
# as the result can be true when test=True
_explicit_close(napalm_device)
if not loaded_result['result']:
__context__['retcode'] = 1
return loaded_result
if not test and commit_config:
# if not in testing mode and trying to commit
if commit_jid:
log.info('Committing the JID: %s', str(commit_jid))
removed = cancel_commit(commit_jid)
log.debug('Cleaned up the commit from the schedule')
log.debug(removed['comment'])
if loaded_result.get('diff', ''):
# if not testing mode
# and also the user wants to commit (default)
# and there are changes to commit
if commit_in or commit_at:
commit_time = __utils__['timeutil.get_time_at'](time_in=commit_in,
time_at=commit_in)
# schedule job
scheduled_job_name = '__napalm_commit_{}'.format(current_jid)
temp_file = salt.utils.files.mkstemp()
with salt.utils.files.fopen(temp_file, 'w') as fp_:
fp_.write(loaded_config)
scheduled = __salt__['schedule.add'](scheduled_job_name,
function='net.load_config',
job_kwargs={
'filename': temp_file,
'commit_jid': current_jid,
'replace': replace
},
once=commit_time)
log.debug('Scheduling job')
log.debug(scheduled)
saved = __salt__['schedule.save']() # ensure the schedule is
# persistent cross Minion restart
discarded = _safe_dicard_config(loaded_result, napalm_device)
# discard the changes
if not discarded['result']:
discarded['comment'] += ('Scheduled the job to be executed at {schedule_ts}, '
'but was unable to discard the config: \n').format(schedule_ts=commit_time)
return discarded
loaded_result['comment'] = ('Changes discarded for now, and scheduled commit at: {schedule_ts}.\n'
'The commit ID is: {current_jid}.\n'
'To discard this commit, you can execute: \n\n'
'salt {min_id} net.cancel_commit {current_jid}').format(schedule_ts=commit_time,
min_id=__opts__['id'],
current_jid=current_jid)
loaded_result['commit_id'] = current_jid
return loaded_result
log.debug('About to commit:')
log.debug(loaded_result['diff'])
if revert_in or revert_at:
revert_time = __utils__['timeutil.get_time_at'](time_in=revert_in,
time_at=revert_at)
if __grains__['os'] == 'junos':
if not HAS_JXMLEASE:
loaded_result['comment'] = ('This feature requires the library jxmlease to be installed.\n'
'To install, please execute: ``pip install jxmlease``.')
loaded_result['result'] = False
return loaded_result
timestamp_at = __utils__['timeutil.get_timestamp_at'](time_in=revert_in,
time_at=revert_at)
minutes = int((timestamp_at - time.time())/60)
_comm = __salt__['napalm.junos_commit'](confirm=minutes)
if not _comm['out']:
# If unable to commit confirm, should try to bail out
loaded_result['comment'] = 'Unable to commit confirm: {}'.format(_comm['message'])
loaded_result['result'] = False
# But before exiting, we must gracefully discard the config
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
else:
temp_file = salt.utils.files.mkstemp()
running_config = __salt__['net.config'](source='running')['out']['running']
with salt.utils.files.fopen(temp_file, 'w') as fp_:
fp_.write(running_config)
committed = _safe_commit_config(loaded_result, napalm_device)
if not committed['result']:
# If unable to commit, dicard the config (which is
# already done by the _safe_commit_config function), and
# return with the command and other details.
return loaded_result
scheduled_job_name = '__napalm_commit_{}'.format(current_jid)
scheduled = __salt__['schedule.add'](scheduled_job_name,
function='net.load_config',
job_kwargs={
'filename': temp_file,
'commit_jid': current_jid,
'replace': True
},
once=revert_time)
log.debug('Scheduling commit confirmed')
log.debug(scheduled)
saved = __salt__['schedule.save']()
loaded_result['comment'] = ('The commit ID is: {current_jid}.\n'
'This commit will be reverted at: {schedule_ts}, unless confirmed.\n'
'To confirm the commit and avoid reverting, you can execute:\n\n'
'salt {min_id} net.confirm_commit {current_jid}').format(schedule_ts=revert_time,
min_id=__opts__['id'],
current_jid=current_jid)
loaded_result['commit_id'] = current_jid
return loaded_result
committed = _safe_commit_config(loaded_result, napalm_device)
if not committed['result']:
return loaded_result
else:
# would like to commit, but there's no change
# need to call discard_config() to release the config DB
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
loaded_result['already_configured'] = True
loaded_result['comment'] = 'Already configured.'
_explicit_close(napalm_device)
if not loaded_result['result']:
__context__['retcode'] = 1
return loaded_result
# ----------------------------------------------------------------------------------------------------------------------
# callable functions
# ----------------------------------------------------------------------------------------------------------------------
@salt.utils.napalm.proxy_napalm_wrap
def connected(**kwargs): # pylint: disable=unused-argument
'''
Specifies if the connection to the device succeeded.
CLI Example:
.. code-block:: bash
salt '*' net.connected
'''
return {
'out': napalm_device.get('UP', False) # pylint: disable=undefined-variable
}
@salt.utils.napalm.proxy_napalm_wrap
def facts(**kwargs): # pylint: disable=unused-argument
'''
Returns characteristics of the network device.
:return: a dictionary with the following keys:
* uptime - Uptime of the device in seconds.
* vendor - Manufacturer of the device.
* model - Device model.
* hostname - Hostname of the device
* fqdn - Fqdn of the device
* os_version - String with the OS version running on the device.
* serial_number - Serial number of the device
* interface_list - List of the interfaces of the device
CLI Example:
.. code-block:: bash
salt '*' net.facts
Example output:
.. code-block:: python
{
'os_version': '13.3R6.5',
'uptime': 10117140,
'interface_list': [
'lc-0/0/0',
'pfe-0/0/0',
'pfh-0/0/0',
'xe-0/0/0',
'xe-0/0/1',
'xe-0/0/2',
'xe-0/0/3',
'gr-0/0/10',
'ip-0/0/10'
],
'vendor': 'Juniper',
'serial_number': 'JN131356FBFA',
'model': 'MX480',
'hostname': 're0.edge05.syd01',
'fqdn': 're0.edge05.syd01'
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_facts',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def environment(**kwargs): # pylint: disable=unused-argument
'''
Returns the environment of the device.
CLI Example:
.. code-block:: bash
salt '*' net.environment
Example output:
.. code-block:: python
{
'fans': {
'Bottom Rear Fan': {
'status': True
},
'Bottom Middle Fan': {
'status': True
},
'Top Middle Fan': {
'status': True
},
'Bottom Front Fan': {
'status': True
},
'Top Front Fan': {
'status': True
},
'Top Rear Fan': {
'status': True
}
},
'memory': {
'available_ram': 16349,
'used_ram': 4934
},
'temperature': {
'FPC 0 Exhaust A': {
'is_alert': False,
'temperature': 35.0,
'is_critical': False
}
},
'cpu': {
'1': {
'%usage': 19.0
},
'0': {
'%usage': 35.0
}
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_environment',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def cli(*commands, **kwargs): # pylint: disable=unused-argument
'''
Returns a dictionary with the raw output of all commands passed as arguments.
commands
List of commands to be executed on the device.
textfsm_parse: ``False``
Try parsing the outputs using the TextFSM templates.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``napalm_cli_textfsm_parse``.
textfsm_path
The path where the TextFSM templates can be found. This option implies
the usage of the TextFSM index file.
``textfsm_path`` can be either absolute path on the server,
either specified using the following URL mschemes: ``file://``,
``salt://``, ``http://``, ``https://``, ``ftp://``,
``s3://``, ``swift://``.
.. versionadded:: 2018.3.0
.. note::
This needs to be a directory with a flat structure, having an
index file (whose name can be specified using the ``index_file`` option)
and a number of TextFSM templates.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_path``.
textfsm_template
The path to a certain the TextFSM template.
This can be specified using the absolute path
to the file, or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
.. versionadded:: 2018.3.0
textfsm_template_dict
A dictionary with the mapping between a command
and the corresponding TextFSM path to use to extract the data.
The TextFSM paths can be specified as in ``textfsm_template``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``napalm_cli_textfsm_template_dict``.
platform_grain_name: ``os``
The name of the grain used to identify the platform name
in the TextFSM index file. Default: ``os``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_grain``.
platform_column_name: ``Platform``
The column name used to identify the platform,
exactly as specified in the TextFSM index file.
Default: ``Platform``.
.. versionadded:: 2018.3.0
.. note::
This is field is case sensitive, make sure
to assign the correct value to this option,
exactly as defined in the index file.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_column_name``.
index_file: ``index``
The name of the TextFSM index file, under the ``textfsm_path``. Default: ``index``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_index_file``.
saltenv: ``base``
Salt fileserver envrionment from which to retrieve the file.
Ignored if ``textfsm_path`` is not a ``salt://`` URL.
.. versionadded:: 2018.3.0
include_empty: ``False``
Include empty files under the ``textfsm_path``.
.. versionadded:: 2018.3.0
include_pat
Glob or regex to narrow down the files cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. versionadded:: 2018.3.0
exclude_pat
Glob or regex to exclude certain files from being cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. versionadded:: 2018.3.0
.. note::
If used with ``include_pat``, files matching this pattern will be
excluded from the subset of files defined by ``include_pat``.
CLI Example:
.. code-block:: bash
salt '*' net.cli "show version" "show chassis fan"
CLI Example with TextFSM template:
.. code-block:: bash
salt '*' net.cli textfsm_parse=True textfsm_path=salt://textfsm/
Example output:
.. code-block:: python
{
'show version and haiku': 'Hostname: re0.edge01.arn01
Model: mx480
Junos: 13.3R6.5
Help me, Obi-Wan
I just saw Episode Two
You're my only hope
',
'show chassis fan' : 'Item Status RPM Measurement
Top Rear Fan OK 3840 Spinning at intermediate-speed
Bottom Rear Fan OK 3840 Spinning at intermediate-speed
Top Middle Fan OK 3900 Spinning at intermediate-speed
Bottom Middle Fan OK 3840 Spinning at intermediate-speed
Top Front Fan OK 3810 Spinning at intermediate-speed
Bottom Front Fan OK 3840 Spinning at intermediate-speed
'
}
Example output with TextFSM parsing:
.. code-block:: json
{
"comment": "",
"result": true,
"out": {
"sh ver": [
{
"kernel": "9.1S3.5",
"documentation": "9.1S3.5",
"boot": "9.1S3.5",
"crypto": "9.1S3.5",
"chassis": "",
"routing": "9.1S3.5",
"base": "9.1S3.5",
"model": "mx960"
}
]
}
}
'''
raw_cli_outputs = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'cli',
**{
'commands': list(commands)
}
)
# thus we can display the output as is
# in case of errors, they'll be catched in the proxy
if not raw_cli_outputs['result']:
# Error -> dispaly the output as-is.
return raw_cli_outputs
textfsm_parse = kwargs.get('textfsm_parse') or __opts__.get('napalm_cli_textfsm_parse') or\
__pillar__.get('napalm_cli_textfsm_parse', False)
if not textfsm_parse:
# No TextFSM parsing required, return raw commands.
log.debug('No TextFSM parsing requested.')
return raw_cli_outputs
if 'textfsm.extract' not in __salt__ or 'textfsm.index' not in __salt__:
raw_cli_outputs['comment'] += 'Unable to process: is TextFSM installed?'
log.error(raw_cli_outputs['comment'])
return raw_cli_outputs
textfsm_template = kwargs.get('textfsm_template')
log.debug('textfsm_template: %s', textfsm_template)
textfsm_path = kwargs.get('textfsm_path') or __opts__.get('textfsm_path') or\
__pillar__.get('textfsm_path')
log.debug('textfsm_path: %s', textfsm_path)
textfsm_template_dict = kwargs.get('textfsm_template_dict') or __opts__.get('napalm_cli_textfsm_template_dict') or\
__pillar__.get('napalm_cli_textfsm_template_dict', {})
log.debug('TextFSM command-template mapping: %s', textfsm_template_dict)
index_file = kwargs.get('index_file') or __opts__.get('textfsm_index_file') or\
__pillar__.get('textfsm_index_file')
log.debug('index_file: %s', index_file)
platform_grain_name = kwargs.get('platform_grain_name') or __opts__.get('textfsm_platform_grain') or\
__pillar__.get('textfsm_platform_grain', 'os')
log.debug('platform_grain_name: %s', platform_grain_name)
platform_column_name = kwargs.get('platform_column_name') or __opts__.get('textfsm_platform_column_name') or\
__pillar__.get('textfsm_platform_column_name', 'Platform')
log.debug('platform_column_name: %s', platform_column_name)
saltenv = kwargs.get('saltenv', 'base')
include_empty = kwargs.get('include_empty', False)
include_pat = kwargs.get('include_pat')
exclude_pat = kwargs.get('exclude_pat')
processed_cli_outputs = {
'comment': raw_cli_outputs.get('comment', ''),
'result': raw_cli_outputs['result'],
'out': {}
}
log.debug('Starting to analyse the raw outputs')
for command in list(commands):
command_output = raw_cli_outputs['out'][command]
log.debug('Output from command: %s', command)
log.debug(command_output)
processed_command_output = None
if textfsm_path:
log.debug('Using the templates under %s', textfsm_path)
processed_cli_output = __salt__['textfsm.index'](command,
platform_grain_name=platform_grain_name,
platform_column_name=platform_column_name,
output=command_output.strip(),
textfsm_path=textfsm_path,
saltenv=saltenv,
include_empty=include_empty,
include_pat=include_pat,
exclude_pat=exclude_pat)
log.debug('Processed CLI output:')
log.debug(processed_cli_output)
if not processed_cli_output['result']:
log.debug('Apparently this didnt work, returnin the raw output')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {0}: {1}.'.format(command,
processed_cli_output['comment'])
log.error(processed_cli_outputs['comment'])
elif processed_cli_output['out']:
log.debug('All good, %s has a nice output!', command)
processed_command_output = processed_cli_output['out']
else:
comment = '''\nProcessing "{}" didn't fail, but didn't return anything either. Dumping raw.'''.format(
command)
processed_cli_outputs['comment'] += comment
log.error(comment)
processed_command_output = command_output
elif textfsm_template or command in textfsm_template_dict:
if command in textfsm_template_dict:
textfsm_template = textfsm_template_dict[command]
log.debug('Using %s to process the command: %s', textfsm_template, command)
processed_cli_output = __salt__['textfsm.extract'](textfsm_template,
raw_text=command_output,
saltenv=saltenv)
log.debug('Processed CLI output:')
log.debug(processed_cli_output)
if not processed_cli_output['result']:
log.debug('Apparently this didnt work, returning '
'the raw output')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {0}: {1}'.format(command,
processed_cli_output['comment'])
log.error(processed_cli_outputs['comment'])
elif processed_cli_output['out']:
log.debug('All good, %s has a nice output!', command)
processed_command_output = processed_cli_output['out']
else:
log.debug('Processing %s didnt fail, but didnt return'
' anything either. Dumping raw.', command)
processed_command_output = command_output
else:
log.error('No TextFSM template specified, or no TextFSM path defined')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {}.'.format(command)
processed_cli_outputs['out'][command] = processed_command_output
processed_cli_outputs['comment'] = processed_cli_outputs['comment'].strip()
return processed_cli_outputs
@salt.utils.napalm.proxy_napalm_wrap
def traceroute(destination, source=None, ttl=None, timeout=None, vrf=None, **kwargs): # pylint: disable=unused-argument
'''
Calls the method traceroute from the NAPALM driver object and returns a dictionary with the result of the traceroute
command executed on the device.
destination
Hostname or address of remote host
source
Source address to use in outgoing traceroute packets
ttl
IP maximum time-to-live value (or IPv6 maximum hop-limit value)
timeout
Number of seconds to wait for response (seconds)
vrf
VRF (routing instance) for traceroute attempt
.. versionadded:: 2016.11.4
CLI Example:
.. code-block:: bash
salt '*' net.traceroute 8.8.8.8
salt '*' net.traceroute 8.8.8.8 source=127.0.0.1 ttl=5 timeout=1
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'traceroute',
**{
'destination': destination,
'source': source,
'ttl': ttl,
'timeout': timeout,
'vrf': vrf
}
)
@salt.utils.napalm.proxy_napalm_wrap
def ping(destination, source=None, ttl=None, timeout=None, size=None, count=None, vrf=None, **kwargs): # pylint: disable=unused-argument
'''
Executes a ping on the network device and returns a dictionary as a result.
destination
Hostname or IP address of remote host
source
Source address of echo request
ttl
IP time-to-live value (IPv6 hop-limit value) (1..255 hops)
timeout
Maximum wait time after sending final packet (seconds)
size
Size of request packets (0..65468 bytes)
count
Number of ping requests to send (1..2000000000 packets)
vrf
VRF (routing instance) for ping attempt
.. versionadded:: 2016.11.4
CLI Example:
.. code-block:: bash
salt '*' net.ping 8.8.8.8
salt '*' net.ping 8.8.8.8 ttl=3 size=65468
salt '*' net.ping 8.8.8.8 source=127.0.0.1 timeout=1 count=100
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'ping',
**{
'destination': destination,
'source': source,
'ttl': ttl,
'timeout': timeout,
'size': size,
'count': count,
'vrf': vrf
}
)
@salt.utils.napalm.proxy_napalm_wrap
def arp(interface='', ipaddr='', macaddr='', **kwargs): # pylint: disable=unused-argument
'''
NAPALM returns a list of dictionaries with details of the ARP entries.
:param interface: interface name to filter on
:param ipaddr: IP address to filter on
:param macaddr: MAC address to filter on
:return: List of the entries in the ARP table
CLI Example:
.. code-block:: bash
salt '*' net.arp
salt '*' net.arp macaddr='5c:5e:ab:da:3c:f0'
Example output:
.. code-block:: python
[
{
'interface' : 'MgmtEth0/RSP0/CPU0/0',
'mac' : '5c:5e:ab:da:3c:f0',
'ip' : '172.17.17.1',
'age' : 1454496274.84
},
{
'interface': 'MgmtEth0/RSP0/CPU0/0',
'mac' : '66:0e:94:96:e0:ff',
'ip' : '172.17.17.2',
'age' : 1435641582.49
}
]
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_arp_table',
**{
}
)
if not proxy_output.get('result'):
return proxy_output
arp_table = proxy_output.get('out')
if interface:
arp_table = _filter_list(arp_table, 'interface', interface)
if ipaddr:
arp_table = _filter_list(arp_table, 'ip', ipaddr)
if macaddr:
arp_table = _filter_list(arp_table, 'mac', macaddr)
proxy_output.update({
'out': arp_table
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def ipaddrs(**kwargs): # pylint: disable=unused-argument
'''
Returns IP addresses configured on the device.
:return: A dictionary with the IPv4 and IPv6 addresses of the interfaces.
Returns all configured IP addresses on all interfaces as a dictionary
of dictionaries. Keys of the main dictionary represent the name of the
interface. Values of the main dictionary represent are dictionaries
that may consist of two keys 'ipv4' and 'ipv6' (one, both or none)
which are themselvs dictionaries with the IP addresses as keys.
CLI Example:
.. code-block:: bash
salt '*' net.ipaddrs
Example output:
.. code-block:: python
{
'FastEthernet8': {
'ipv4': {
'10.66.43.169': {
'prefix_length': 22
}
}
},
'Loopback555': {
'ipv4': {
'192.168.1.1': {
'prefix_length': 24
}
},
'ipv6': {
'1::1': {
'prefix_length': 64
},
'2001:DB8:1::1': {
'prefix_length': 64
},
'FE80::3': {
'prefix_length': 'N/A'
}
}
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_interfaces_ip',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def interfaces(**kwargs): # pylint: disable=unused-argument
'''
Returns details of the interfaces on the device.
:return: Returns a dictionary of dictionaries. The keys for the first
dictionary will be the interfaces in the devices.
CLI Example:
.. code-block:: bash
salt '*' net.interfaces
Example output:
.. code-block:: python
{
'Management1': {
'is_up': False,
'is_enabled': False,
'description': '',
'last_flapped': -1,
'speed': 1000,
'mac_address': 'dead:beef:dead',
},
'Ethernet1':{
'is_up': True,
'is_enabled': True,
'description': 'foo',
'last_flapped': 1429978575.1554043,
'speed': 1000,
'mac_address': 'beef:dead:beef',
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_interfaces',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def lldp(interface='', **kwargs): # pylint: disable=unused-argument
'''
Returns a detailed view of the LLDP neighbors.
:param interface: interface name to filter on
:return: A dictionary with the LLDL neighbors. The keys are the
interfaces with LLDP activated on.
CLI Example:
.. code-block:: bash
salt '*' net.lldp
salt '*' net.lldp interface='TenGigE0/0/0/8'
Example output:
.. code-block:: python
{
'TenGigE0/0/0/8': [
{
'parent_interface': 'Bundle-Ether8',
'interface_description': 'TenGigE0/0/0/8',
'remote_chassis_id': '8c60.4f69.e96c',
'remote_system_name': 'switch',
'remote_port': 'Eth2/2/1',
'remote_port_description': 'Ethernet2/2/1',
'remote_system_description': 'Cisco Nexus Operating System (NX-OS) Software 7.1(0)N1(1a)
TAC support: http://www.cisco.com/tac
Copyright (c) 2002-2015, Cisco Systems, Inc. All rights reserved.',
'remote_system_capab': 'B, R',
'remote_system_enable_capab': 'B'
}
]
}
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_lldp_neighbors_detail',
**{
}
)
if not proxy_output.get('result'):
return proxy_output
lldp_neighbors = proxy_output.get('out')
if interface:
lldp_neighbors = {interface: lldp_neighbors.get(interface)}
proxy_output.update({
'out': lldp_neighbors
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def mac(address='', interface='', vlan=0, **kwargs): # pylint: disable=unused-argument
'''
Returns the MAC Address Table on the device.
:param address: MAC address to filter on
:param interface: Interface name to filter on
:param vlan: VLAN identifier
:return: A list of dictionaries representing the entries in the MAC Address Table
CLI Example:
.. code-block:: bash
salt '*' net.mac
salt '*' net.mac vlan=10
Example output:
.. code-block:: python
[
{
'mac' : '00:1c:58:29:4a:71',
'interface' : 'xe-3/0/2',
'static' : False,
'active' : True,
'moves' : 1,
'vlan' : 10,
'last_move' : 1454417742.58
},
{
'mac' : '8c:60:4f:58:e1:c1',
'interface' : 'xe-1/0/1',
'static' : False,
'active' : True,
'moves' : 2,
'vlan' : 42,
'last_move' : 1453191948.11
}
]
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_mac_address_table',
**{
}
)
if not proxy_output.get('result'):
# if negative, leave the output unchanged
return proxy_output
mac_address_table = proxy_output.get('out')
if vlan and isinstance(vlan, int):
mac_address_table = _filter_list(mac_address_table, 'vlan', vlan)
if address:
mac_address_table = _filter_list(mac_address_table, 'mac', address)
if interface:
mac_address_table = _filter_list(mac_address_table, 'interface', interface)
proxy_output.update({
'out': mac_address_table
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def config(source=None, **kwargs): # pylint: disable=unused-argument
'''
.. versionadded:: 2017.7.0
Return the whole configuration of the network device. By default, it will
return all possible configuration sources supported by the network device.
At most, there will be:
- running config
- startup config
- candidate config
To return only one of the configurations, you can use the ``source``
argument.
source
Which configuration type you want to display, default is all of them.
Options:
- running
- candidate
- startup
:return:
The object returned is a dictionary with the following keys:
- running (string): Representation of the native running configuration.
- candidate (string): Representation of the native candidate configuration.
If the device doesn't differentiate between running and startup
configuration this will an empty string.
- startup (string): Representation of the native startup configuration.
If the device doesn't differentiate between running and startup
configuration this will an empty string.
CLI Example:
.. code-block:: bash
salt '*' net.config
salt '*' net.config source=candidate
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_config',
**{
'retrieve': source
}
)
@salt.utils.napalm.proxy_napalm_wrap
def optics(**kwargs): # pylint: disable=unused-argument
'''
.. versionadded:: 2017.7.0
Fetches the power usage on the various transceivers installed
on the network device (in dBm), and returns a view that conforms with the
OpenConfig model openconfig-platform-transceiver.yang.
:return:
Returns a dictionary where the keys are as listed below:
* intf_name (unicode)
* physical_channels
* channels (list of dicts)
* index (int)
* state
* input_power
* instant (float)
* avg (float)
* min (float)
* max (float)
* output_power
* instant (float)
* avg (float)
* min (float)
* max (float)
* laser_bias_current
* instant (float)
* avg (float)
* min (float)
* max (float)
CLI Example:
.. code-block:: bash
salt '*' net.optics
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_optics',
**{
}
)
# <---- Call NAPALM getters --------------------------------------------------------------------------------------------
# ----- Configuration specific functions ------------------------------------------------------------------------------>
@salt.utils.napalm.proxy_napalm_wrap
def load_config(filename=None,
text=None,
test=False,
commit=True,
debug=False,
replace=False,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
commit_jid=None,
inherit_napalm_device=None,
saltenv='base',
**kwargs): # pylint: disable=unused-argument
'''
Applies configuration changes on the device. It can be loaded from a file or from inline string.
If you send both a filename and a string containing the configuration, the file has higher precedence.
By default this function will commit the changes. If there are no changes, it does not commit and
the flag ``already_configured`` will be set as ``True`` to point this out.
To avoid committing the configuration, set the argument ``test`` to ``True`` and will discard (dry run).
To keep the changes but not commit, set ``commit`` to ``False``.
To replace the config, set ``replace`` to ``True``.
filename
Path to the file containing the desired configuration.
This can be specified using the absolute path to the file,
or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
.. versionchanged:: 2018.3.0
text
String containing the desired configuration.
This argument is ignored when ``filename`` is specified.
test: False
Dry run? If set as ``True``, will apply the config, discard and return the changes. Default: ``False``
and will commit the changes on the device.
commit: True
Commit? Default: ``True``.
debug: False
Debug mode. Will insert a new key under the output dictionary, as ``loaded_config`` containing the raw
configuration loaded on the device.
.. versionadded:: 2016.11.2
replace: False
Load and replace the configuration. Default: ``False``.
.. versionadded:: 2016.11.2
commit_in: ``None``
Commit the changes in a specific number of minutes / hours. Example of
accepted formats: ``5`` (commit in 5 minutes), ``2m`` (commit in 2
minutes), ``1h`` (commit the changes in 1 hour)`, ``5h30m`` (commit
the changes in 5 hours and 30 minutes).
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
commit_at: ``None``
Commit the changes at a specific time. Example of accepted formats:
``1am`` (will commit the changes at the next 1AM), ``13:20`` (will
commit at 13:20), ``1:20am``, etc.
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
revert_in: ``None``
Commit and revert the changes in a specific number of minutes / hours.
Example of accepted formats: ``5`` (revert in 5 minutes), ``2m`` (revert
in 2 minutes), ``1h`` (revert the changes in 1 hour)`, ``5h30m`` (revert
the changes in 5 hours and 30 minutes).
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
revert_at: ``None``
Commit and revert the changes at a specific time. Example of accepted
formats: ``1am`` (will commit and revert the changes at the next 1AM),
``13:20`` (will commit and revert at 13:20), ``1:20am``, etc.
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
saltenv: ``base``
Specifies the Salt environment name.
.. versionadded:: 2018.3.0
:return: a dictionary having the following keys:
* result (bool): if the config was applied successfully. It is ``False`` only in case of failure. In case \
there are no changes to be applied and successfully performs all operations it is still ``True`` and so will be \
the ``already_configured`` flag (example below)
* comment (str): a message for the user
* already_configured (bool): flag to check if there were no changes applied
* loaded_config (str): the configuration loaded on the device. Requires ``debug`` to be set as ``True``
* diff (str): returns the config changes applied
CLI Example:
.. code-block:: bash
salt '*' net.load_config text='ntp peer 192.168.0.1'
salt '*' net.load_config filename='/absolute/path/to/your/file'
salt '*' net.load_config filename='/absolute/path/to/your/file' test=True
salt '*' net.load_config filename='/absolute/path/to/your/file' commit=False
Example output:
.. code-block:: python
{
'comment': 'Configuration discarded.',
'already_configured': False,
'result': True,
'diff': '[edit interfaces xe-0/0/5]+ description "Adding a description";'
}
'''
fun = 'load_merge_candidate'
if replace:
fun = 'load_replace_candidate'
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
if filename:
text = __salt__['cp.get_file_str'](filename, saltenv=saltenv)
if text is False:
# When using salt:// or https://, if the resource is not available,
# it will either raise an exception, or return False.
ret = {
'result': False,
'out': None
}
ret['comment'] = 'Unable to read from {}. Please specify a valid file or text.'.format(filename)
log.error(ret['comment'])
return ret
if commit_jid:
# When the commit_jid argument is passed, it probably is a scheduled
# commit to be executed, and filename is a temporary file which
# can be removed after reading it.
salt.utils.files.safe_rm(filename)
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
fun,
**{
'config': text
}
)
return _config_logic(napalm_device, # pylint: disable=undefined-variable
_loaded,
test=test,
debug=debug,
replace=replace,
commit_config=commit,
loaded_config=text,
commit_at=commit_at,
commit_in=commit_in,
revert_in=revert_in,
revert_at=revert_at,
commit_jid=commit_jid,
**kwargs)
@salt.utils.napalm.proxy_napalm_wrap
def load_template(template_name=None,
template_source=None,
context=None,
defaults=None,
template_engine='jinja',
saltenv='base',
template_hash=None,
template_hash_name=None,
skip_verify=False,
test=False,
commit=True,
debug=False,
replace=False,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
inherit_napalm_device=None, # pylint: disable=unused-argument
**template_vars):
'''
Renders a configuration template (default: Jinja) and loads the result on the device.
By default this function will commit the changes. If there are no changes,
it does not commit, discards he config and the flag ``already_configured``
will be set as ``True`` to point this out.
To avoid committing the configuration, set the argument ``test`` to ``True``
and will discard (dry run).
To preserve the changes, set ``commit`` to ``False``.
However, this is recommended to be used only in exceptional cases
when there are applied few consecutive states
and/or configuration changes.
Otherwise the user might forget that the config DB is locked
and the candidate config buffer is not cleared/merged in the running config.
To replace the config, set ``replace`` to ``True``.
template_name
Identifies path to the template source.
The template can be either stored on the local machine, either remotely.
The recommended location is under the ``file_roots``
as specified in the master config file.
For example, let's suppose the ``file_roots`` is configured as:
.. code-block:: yaml
file_roots:
base:
- /etc/salt/states
Placing the template under ``/etc/salt/states/templates/example.jinja``,
it can be used as ``salt://templates/example.jinja``.
Alternatively, for local files, the user can specify the absolute path.
If remotely, the source can be retrieved via ``http``, ``https`` or ``ftp``.
Examples:
- ``salt://my_template.jinja``
- ``/absolute/path/to/my_template.jinja``
- ``http://example.com/template.cheetah``
- ``https:/example.com/template.mako``
- ``ftp://example.com/template.py``
.. versionchanged:: 2019.2.0
This argument can now support a list of templates to be rendered.
The resulting configuration text is loaded at once, as a single
configuration chunk.
template_source: None
Inline config template to be rendered and loaded on the device.
template_hash: None
Hash of the template file. Format: ``{hash_type: 'md5', 'hsum': <md5sum>}``
.. versionadded:: 2016.11.2
context: None
Overrides default context variables passed to the template.
.. versionadded:: 2019.2.0
template_hash_name: None
When ``template_hash`` refers to a remote file,
this specifies the filename to look for in that file.
.. versionadded:: 2016.11.2
saltenv: ``base``
Specifies the template environment.
This will influence the relative imports inside the templates.
.. versionadded:: 2016.11.2
template_engine: jinja
The following templates engines are supported:
- :mod:`cheetah<salt.renderers.cheetah>`
- :mod:`genshi<salt.renderers.genshi>`
- :mod:`jinja<salt.renderers.jinja>`
- :mod:`mako<salt.renderers.mako>`
- :mod:`py<salt.renderers.py>`
- :mod:`wempy<salt.renderers.wempy>`
.. versionadded:: 2016.11.2
skip_verify: True
If ``True``, hash verification of remote file sources
(``http://``, ``https://``, ``ftp://``) will be skipped,
and the ``source_hash`` argument will be ignored.
.. versionadded:: 2016.11.2
test: False
Dry run? If set to ``True``, will apply the config,
discard and return the changes.
Default: ``False`` and will commit the changes on the device.
commit: True
Commit? (default: ``True``)
debug: False
Debug mode. Will insert a new key under the output dictionary,
as ``loaded_config`` containing the raw result after the template was rendered.
.. versionadded:: 2016.11.2
replace: False
Load and replace the configuration.
.. versionadded:: 2016.11.2
commit_in: ``None``
Commit the changes in a specific number of minutes / hours. Example of
accepted formats: ``5`` (commit in 5 minutes), ``2m`` (commit in 2
minutes), ``1h`` (commit the changes in 1 hour)`, ``5h30m`` (commit
the changes in 5 hours and 30 minutes).
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
commit_at: ``None``
Commit the changes at a specific time. Example of accepted formats:
``1am`` (will commit the changes at the next 1AM), ``13:20`` (will
commit at 13:20), ``1:20am``, etc.
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
revert_in: ``None``
Commit and revert the changes in a specific number of minutes / hours.
Example of accepted formats: ``5`` (revert in 5 minutes), ``2m`` (revert
in 2 minutes), ``1h`` (revert the changes in 1 hour)`, ``5h30m`` (revert
the changes in 5 hours and 30 minutes).
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
revert_at: ``None``
Commit and revert the changes at a specific time. Example of accepted
formats: ``1am`` (will commit and revert the changes at the next 1AM),
``13:20`` (will commit and revert at 13:20), ``1:20am``, etc.
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
defaults: None
Default variables/context passed to the template.
.. versionadded:: 2016.11.2
template_vars
Dictionary with the arguments/context to be used when the template is rendered.
.. note::
Do not explicitly specify this argument. This represents any other
variable that will be sent to the template rendering system.
Please see the examples below!
.. note::
It is more recommended to use the ``context`` argument to avoid
conflicts between CLI arguments and template variables.
:return: a dictionary having the following keys:
- result (bool): if the config was applied successfully. It is ``False``
only in case of failure. In case there are no changes to be applied and
successfully performs all operations it is still ``True`` and so will be
the ``already_configured`` flag (example below)
- comment (str): a message for the user
- already_configured (bool): flag to check if there were no changes applied
- loaded_config (str): the configuration loaded on the device, after
rendering the template. Requires ``debug`` to be set as ``True``
- diff (str): returns the config changes applied
The template can use variables from the ``grains``, ``pillar`` or ``opts``, for example:
.. code-block:: jinja
{% set router_model = grains.get('model') -%}
{% set router_vendor = grains.get('vendor') -%}
{% set os_version = grains.get('version') -%}
{% set hostname = pillar.get('proxy', {}).get('host') -%}
{% if router_vendor|lower == 'juniper' %}
system {
host-name {{hostname}};
}
{% elif router_vendor|lower == 'cisco' %}
hostname {{hostname}}
{% endif %}
CLI Examples:
.. code-block:: bash
salt '*' net.load_template set_ntp_peers peers=[192.168.0.1] # uses NAPALM default templates
# inline template:
salt -G 'os:junos' net.load_template template_source='system { host-name {{host_name}}; }' \
host_name='MX480.lab'
# inline template using grains info:
salt -G 'os:junos' net.load_template \
template_source='system { host-name {{grains.model}}.lab; }'
# if the device is a MX480, the command above will set the hostname as: MX480.lab
# inline template using pillar data:
salt -G 'os:junos' net.load_template template_source='system { host-name {{pillar.proxy.host}}; }'
salt '*' net.load_template https://bit.ly/2OhSgqP hostname=example # will commit
salt '*' net.load_template https://bit.ly/2OhSgqP hostname=example test=True # dry run
salt '*' net.load_template salt://templates/example.jinja debug=True # Using the salt:// URI
# render a mako template:
salt '*' net.load_template salt://templates/example.mako template_engine=mako debug=True
# render remote template
salt -G 'os:junos' net.load_template http://bit.ly/2fReJg7 test=True debug=True peers=['192.168.0.1']
salt -G 'os:ios' net.load_template http://bit.ly/2gKOj20 test=True debug=True peers=['192.168.0.1']
# render multiple templates at once
salt '*' net.load_template "['https://bit.ly/2OhSgqP', 'salt://templates/example.jinja']" context="{'hostname': 'example'}"
Example output:
.. code-block:: python
{
'comment': '',
'already_configured': False,
'result': True,
'diff': '[edit system]+ host-name edge01.bjm01',
'loaded_config': 'system { host-name edge01.bjm01; }''
}
'''
_rendered = ''
_loaded = {
'result': True,
'comment': '',
'out': None
}
loaded_config = None
# prechecks
deprecated_args = ('template_user', 'template_attrs', 'template_group', 'template_mode')
for deprecated_arg in deprecated_args:
if template_vars.get(deprecated_arg):
del template_vars[deprecated_arg]
salt.utils.versions.warn_until(
'Sodium',
('The \'{arg}\' argument to \'net.load_template\' is deprecated '
'and has been ignored').format(arg=deprecated_arg)
)
if template_engine not in salt.utils.templates.TEMPLATE_REGISTRY:
_loaded.update({
'result': False,
'comment': 'Invalid templating engine! Choose between: {tpl_eng_opts}'.format(
tpl_eng_opts=', '.join(list(salt.utils.templates.TEMPLATE_REGISTRY.keys()))
)
})
return _loaded # exit
# to check if will be rendered by salt or NAPALM
salt_render_prefixes = ('salt://', 'http://', 'https://', 'ftp://')
salt_render = False
file_exists = False
if not isinstance(template_name, (tuple, list)):
for salt_render_prefix in salt_render_prefixes:
if not salt_render:
salt_render = salt_render or template_name.startswith(salt_render_prefix)
file_exists = __salt__['file.file_exists'](template_name)
if template_source or file_exists or salt_render or isinstance(template_name, (tuple, list)):
# either inline template
# either template in a custom path
# either abs path send
# either starts with salt:// and
# then use Salt render system
if context is None:
context = {}
context.update(template_vars)
# if needed to render the template send as inline arg
if template_source:
# render the content
_rendered = __salt__['file.apply_template_on_contents'](
contents=template_source,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv
)
if not isinstance(_rendered, six.string_types):
if 'result' in _rendered:
_loaded['result'] = _rendered['result']
else:
_loaded['result'] = False
if 'comment' in _rendered:
_loaded['comment'] = _rendered['comment']
else:
_loaded['comment'] = 'Error while rendering the template.'
return _loaded
else:
# render the file - either local, either remote
if not isinstance(template_name, (list, tuple)):
template_name = [template_name]
if template_hash_name and not isinstance(template_hash_name, (list, tuple)):
template_hash_name = [template_hash_name]
elif not template_hash_name:
template_hash_name = [None] * len(template_name)
if template_hash and isinstance(template_hash, six.string_types) and not\
(template_hash.startswith('salt://') or template_hash.startswith('file://')):
# If the template hash is passed as string, and it's not a file
# (starts with the salt:// or file:// URI), then make it a list
# of 1 element (for the iteration below)
template_hash = [template_hash]
elif template_hash and isinstance(template_hash, six.string_types) and\
(template_hash.startswith('salt://') or template_hash.startswith('file://')):
# If the template hash is a file URI, then provide the same value
# for each of the templates in the list, as probably they all
# share the same hash file, otherwise the user should provide
# this as a list
template_hash = [template_hash] * len(template_name)
elif not template_hash:
template_hash = [None] * len(template_name)
for tpl_index, tpl_name in enumerate(template_name):
tpl_hash = template_hash[tpl_index]
tpl_hash_name = template_hash_name[tpl_index]
_rand_filename = __salt__['random.hash'](tpl_name, 'md5')
_temp_file = __salt__['file.join']('/tmp', _rand_filename)
_managed = __salt__['file.get_managed'](name=_temp_file,
source=tpl_name,
source_hash=tpl_hash,
source_hash_name=tpl_hash_name,
user=None,
group=None,
mode=None,
attrs=None,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv,
skip_verify=skip_verify)
if not isinstance(_managed, (list, tuple)) and isinstance(_managed, six.string_types):
_loaded['comment'] += _managed
_loaded['result'] = False
elif isinstance(_managed, (list, tuple)) and not _managed:
_loaded['result'] = False
_loaded['comment'] += 'Error while rendering the template.'
elif isinstance(_managed, (list, tuple)) and not _managed[0]:
_loaded['result'] = False
_loaded['comment'] += _managed[-1] # contains the error message
if _loaded['result']: # all good
_temp_tpl_file = _managed[0]
_temp_tpl_file_exists = __salt__['file.file_exists'](_temp_tpl_file)
if not _temp_tpl_file_exists:
_loaded['result'] = False
_loaded['comment'] += 'Error while rendering the template.'
return _loaded
_rendered += __salt__['file.read'](_temp_tpl_file)
__salt__['file.remove'](_temp_tpl_file)
else:
return _loaded # exit
loaded_config = _rendered
if _loaded['result']: # all good
fun = 'load_merge_candidate'
if replace: # replace requested
fun = 'load_replace_candidate'
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
fun,
**{
'config': _rendered
}
)
else:
salt.utils.versions.warn_until(
'Sodium',
'Native NAPALM templates support will be removed in the Sodium '
'release. Please consider using the Salt rendering pipeline instead.'
'If you are using the \'netntp\', \'netsnmp\', or \'netusers\' Salt '
'State modules, you can ignore this message'
)
# otherwise, use NAPALM render system, injecting pillar/grains/opts vars
load_templates_params = defaults if defaults else {}
load_templates_params.update(template_vars)
load_templates_params.update(
{
'template_name': template_name,
'template_source': template_source, # inline template
'pillar': __pillar__, # inject pillar content
'grains': __grains__, # inject grains content
'opts': __opts__ # inject opts content
}
)
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
# so we'll set the CLOSE global explicitly as False
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'load_template',
**load_templates_params
)
return _config_logic(napalm_device, # pylint: disable=undefined-variable
_loaded,
test=test,
debug=debug,
replace=replace,
commit_config=commit,
loaded_config=loaded_config,
commit_at=commit_at,
commit_in=commit_in,
revert_in=revert_in,
revert_at=revert_at,
**template_vars)
@salt.utils.napalm.proxy_napalm_wrap
def commit(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Commits the configuration changes made on the network device.
CLI Example:
.. code-block:: bash
salt '*' net.commit
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'commit_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def discard_config(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
"""
Discards the changes applied.
CLI Example:
.. code-block:: bash
salt '*' net.discard_config
"""
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'discard_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def compare_config(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Returns the difference between the running config and the candidate config.
CLI Example:
.. code-block:: bash
salt '*' net.compare_config
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'compare_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def rollback(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Rollbacks the configuration.
CLI Example:
.. code-block:: bash
salt '*' net.rollback
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'rollback',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def config_changed(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Will prompt if the configuration has been changed.
:return: A tuple with a boolean that specifies if the config was changed on the device.\
And a string that provides more details of the reason why the configuration was not changed.
CLI Example:
.. code-block:: bash
salt '*' net.config_changed
'''
is_config_changed = False
reason = ''
try_compare = compare_config(inherit_napalm_device=napalm_device) # pylint: disable=undefined-variable
if try_compare.get('result'):
if try_compare.get('out'):
is_config_changed = True
else:
reason = 'Configuration was not changed on the device.'
else:
reason = try_compare.get('comment')
return is_config_changed, reason
@salt.utils.napalm.proxy_napalm_wrap
def config_control(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Will check if the configuration was changed.
If differences found, will try to commit.
In case commit unsuccessful, will try to rollback.
:return: A tuple with a boolean that specifies if the config was changed/committed/rollbacked on the device.\
And a string that provides more details of the reason why the configuration was not committed properly.
CLI Example:
.. code-block:: bash
salt '*' net.config_control
'''
result = True
comment = ''
changed, not_changed_rsn = config_changed(inherit_napalm_device=napalm_device) # pylint: disable=undefined-variable
if not changed:
return (changed, not_changed_rsn)
# config changed, thus let's try to commit
try_commit = commit()
if not try_commit.get('result'):
result = False
comment = 'Unable to commit the changes: {reason}.\n\
Will try to rollback now!'.format(
reason=try_commit.get('comment')
)
try_rollback = rollback()
if not try_rollback.get('result'):
comment += '\nCannot rollback! {reason}'.format(
reason=try_rollback.get('comment')
)
return result, comment
def confirm_commit(jid):
'''
.. versionadded:: 2019.2.0
Confirm a commit scheduled to be reverted via the ``revert_in`` and
``revert_at`` arguments from the
:mod:`net.load_template <salt.modules.napalm_network.load_template>` or
:mod:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit ID is displayed when the commit confirmed
is scheduled via the functions named above.
CLI Example:
.. code-block:: bash
salt '*' net.confirm_commit 20180726083540640360
'''
if __grains__['os'] == 'junos':
# Confirm the commit, by committing (i.e., invoking the RPC call)
confirmed = __salt__['napalm.junos_commit']()
confirmed['result'] = confirmed.pop('out')
confirmed['comment'] = confirmed.pop('message')
else:
confirmed = cancel_commit(jid)
if confirmed['result']:
confirmed['comment'] = 'Commit #{jid} confirmed.'.format(jid=jid)
return confirmed
def save_config(source=None,
path=None):
'''
.. versionadded:: 2019.2.0
Save the configuration to a file on the local file system.
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``,
``startup``. Default: ``running``.
path
Absolute path to file where to save the configuration.
To push the files to the Master, use
:mod:`cp.push <salt.modules.cp.push>` Execution function.
CLI Example:
.. code-block:: bash
salt '*' net.save_config source=running
'''
if not source:
source = 'running'
if not path:
path = salt.utils.files.mkstemp()
running_config = __salt__['net.config'](source=source)
if not running_config or not running_config['result']:
log.error('Unable to retrieve the config')
return running_config
with salt.utils.files.fopen(path, 'w') as fh_:
fh_.write(running_config['out'][source])
return {
'result': True,
'out': path,
'comment': '{source} config saved to {path}'.format(source=source, path=path)
}
def replace_pattern(pattern,
repl,
count=0,
flags=8,
bufsize=1,
append_if_not_found=False,
prepend_if_not_found=False,
not_found_content=None,
search_only=False,
show_changes=True,
backslash_literal=False,
source=None,
path=None,
test=False,
replace=True,
debug=False,
commit=True):
'''
.. versionadded:: 2019.2.0
Replace occurrences of a pattern in the configuration source. If
``show_changes`` is ``True``, then a diff of what changed will be returned,
otherwise a ``True`` will be returned when changes are made, and ``False``
when no changes are made.
This is a pure Python implementation that wraps Python's :py:func:`~re.sub`.
pattern
A regular expression, to be matched using Python's
:py:func:`~re.search`.
repl
The replacement text.
count: ``0``
Maximum number of pattern occurrences to be replaced. If count is a
positive integer ``n``, only ``n`` occurrences will be replaced,
otherwise all occurrences will be replaced.
flags (list or int): ``8``
A list of flags defined in the ``re`` module documentation from the
Python standard library. Each list item should be a string that will
correlate to the human-friendly flag name. E.g., ``['IGNORECASE',
'MULTILINE']``. Optionally, ``flags`` may be an int, with a value
corresponding to the XOR (``|``) of all the desired flags. Defaults to
8 (which supports 'MULTILINE').
bufsize (int or str): ``1``
How much of the configuration to buffer into memory at once. The
default value ``1`` processes one line at a time. The special value
``file`` may be specified which will read the entire file into memory
before processing.
append_if_not_found: ``False``
If set to ``True``, and pattern is not found, then the content will be
appended to the file.
prepend_if_not_found: ``False``
If set to ``True`` and pattern is not found, then the content will be
prepended to the file.
not_found_content
Content to use for append/prepend if not found. If None (default), uses
``repl``. Useful when ``repl`` uses references to group in pattern.
search_only: ``False``
If set to true, this no changes will be performed on the file, and this
function will simply return ``True`` if the pattern was matched, and
``False`` if not.
show_changes: ``True``
If ``True``, return a diff of changes made. Otherwise, return ``True``
if changes were made, and ``False`` if not.
backslash_literal: ``False``
Interpret backslashes as literal backslashes for the repl and not
escape characters. This will help when using append/prepend so that
the backslashes are not interpreted for the repl on the second run of
the state.
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path
Save the temporary configuration to a specific path, then read from
there.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' net.replace_pattern "bind-address\\s*=" "bind-address:"
CLI Example:
.. code-block:: bash
salt '*' net.replace_pattern PREFIX-LIST_NAME new-prefix-list-name
salt '*' net.replace_pattern bgp-group-name new-bgp-group-name count=1
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
replace_pattern = __salt__['file.replace'](path,
pattern,
repl,
count=count,
flags=flags,
bufsize=bufsize,
append_if_not_found=append_if_not_found,
prepend_if_not_found=prepend_if_not_found,
not_found_content=not_found_content,
search_only=search_only,
show_changes=show_changes,
backslash_literal=backslash_literal)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
def blockreplace(marker_start,
marker_end,
content='',
append_if_not_found=False,
prepend_if_not_found=False,
show_changes=True,
append_newline=False,
source='running',
path=None,
test=False,
commit=True,
debug=False,
replace=True):
'''
.. versionadded:: 2019.2.0
Replace content of the configuration source, delimited by the line markers.
A block of content delimited by comments can help you manage several lines
without worrying about old entries removal.
marker_start
The line content identifying a line as the start of the content block.
Note that the whole line containing this marker will be considered,
so whitespace or extra content before or after the marker is included
in final output.
marker_end
The line content identifying a line as the end of the content block.
Note that the whole line containing this marker will be considered,
so whitespace or extra content before or after the marker is included
in final output.
content
The content to be used between the two lines identified by
``marker_start`` and ``marker_stop``.
append_if_not_found: ``False``
If markers are not found and set to True then, the markers and content
will be appended to the file.
prepend_if_not_found: ``False``
If markers are not found and set to True then, the markers and content
will be prepended to the file.
append_newline: ``False``
Controls whether or not a newline is appended to the content block.
If the value of this argument is ``True`` then a newline will be added
to the content block. If it is ``False``, then a newline will not be
added to the content block. If it is ``None`` then a newline will only
be added to the content block if it does not already end in a newline.
show_changes: ``True``
Controls how changes are presented. If ``True``, this function will
return the of the changes made.
If ``False``, then it will return a boolean (``True`` if any changes
were made, otherwise False).
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path: ``None``
Save the temporary configuration to a specific path, then read from
there. This argument is optional, can be used when you prefers a
particular location of the temporary file.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
CLI Example:
.. code-block:: bash
salt '*' net.blockreplace 'ntp' 'interface' ''
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
replace_pattern = __salt__['file.blockreplace'](path,
marker_start=marker_start,
marker_end=marker_end,
content=content,
append_if_not_found=append_if_not_found,
prepend_if_not_found=prepend_if_not_found,
show_changes=show_changes,
append_newline=append_newline)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
def patch(patchfile,
options='',
saltenv='base',
source_hash=None,
show_changes=True,
source='running',
path=None,
test=False,
commit=True,
debug=False,
replace=True):
'''
.. versionadded:: 2019.2.0
Apply a patch to the configuration source, and load the result into the
running config of the device.
patchfile
A patch file to apply to the configuration source.
options
Options to pass to patch.
source_hash
If the patch file (specified via the ``patchfile`` argument) is an
HTTP(S) or FTP URL and the file exists in the minion's file cache, this
option can be passed to keep the minion from re-downloading the file if
the cached copy matches the specified hash.
show_changes: ``True``
Controls how changes are presented. If ``True``, this function will
return the of the changes made.
If ``False``, then it will return a boolean (``True`` if any changes
were made, otherwise False).
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path: ``None``
Save the temporary configuration to a specific path, then read from
there. This argument is optional, can the user prefers a particular
location of the temporary file.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
CLI Example:
.. code-block:: bash
salt '*' net.patch https://example.com/running_config.patch
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
patchfile_cache = __salt__['cp.cache_file'](patchfile)
if patchfile_cache is False:
return {
'out': None,
'result': False,
'comment': 'The file "{}" does not exist.'.format(patchfile)
}
replace_pattern = __salt__['file.patch'](path,
patchfile_cache,
options=options)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
# <---- Configuration specific functions -------------------------------------------------------------------------------
|
saltstack/salt
|
salt/modules/napalm_network.py
|
confirm_commit
|
python
|
def confirm_commit(jid):
'''
.. versionadded:: 2019.2.0
Confirm a commit scheduled to be reverted via the ``revert_in`` and
``revert_at`` arguments from the
:mod:`net.load_template <salt.modules.napalm_network.load_template>` or
:mod:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit ID is displayed when the commit confirmed
is scheduled via the functions named above.
CLI Example:
.. code-block:: bash
salt '*' net.confirm_commit 20180726083540640360
'''
if __grains__['os'] == 'junos':
# Confirm the commit, by committing (i.e., invoking the RPC call)
confirmed = __salt__['napalm.junos_commit']()
confirmed['result'] = confirmed.pop('out')
confirmed['comment'] = confirmed.pop('message')
else:
confirmed = cancel_commit(jid)
if confirmed['result']:
confirmed['comment'] = 'Commit #{jid} confirmed.'.format(jid=jid)
return confirmed
|
.. versionadded:: 2019.2.0
Confirm a commit scheduled to be reverted via the ``revert_in`` and
``revert_at`` arguments from the
:mod:`net.load_template <salt.modules.napalm_network.load_template>` or
:mod:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit ID is displayed when the commit confirmed
is scheduled via the functions named above.
CLI Example:
.. code-block:: bash
salt '*' net.confirm_commit 20180726083540640360
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_network.py#L2265-L2291
|
[
"def cancel_commit(jid):\n '''\n .. versionadded:: 2019.2.0\n\n Cancel a commit scheduled to be executed via the ``commit_in`` and\n ``commit_at`` arguments from the\n :py:func:`net.load_template <salt.modules.napalm_network.load_template>` or\n :py:func:`net.load_config <salt.modules.napalm_network.load_config>`\n execution functions. The commit ID is displayed when the commit is scheduled\n via the functions named above.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' net.cancel_commit 20180726083540640360\n '''\n job_name = '__napalm_commit_{}'.format(jid)\n removed = __salt__['schedule.delete'](job_name)\n if removed['result']:\n saved = __salt__['schedule.save']()\n removed['comment'] = 'Commit #{jid} cancelled.'.format(jid=jid)\n else:\n removed['comment'] = 'Unable to find commit #{jid}.'.format(jid=jid)\n return removed\n"
] |
# -*- coding: utf-8 -*-
'''
NAPALM Network
==============
Basic methods for interaction with the network device through the virtual proxy 'napalm'.
:codeauthor: Mircea Ulinic <mircea@cloudflare.com> & Jerome Fleury <jf@cloudflare.com>
:maturity: new
:depends: napalm
:platform: unix
Dependencies
------------
- :mod:`napalm proxy minion <salt.proxy.napalm>`
.. versionadded:: 2016.11.0
.. versionchanged:: 2017.7.0
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import time
import logging
import datetime
log = logging.getLogger(__name__)
# Import Salt libs
from salt.ext import six
import salt.utils.files
import salt.utils.napalm
import salt.utils.versions
import salt.utils.templates
# Import 3rd-party libs
try:
import jxmlease # pylint: disable=unused-import
HAS_JXMLEASE = True
except ImportError:
HAS_JXMLEASE = False
# ----------------------------------------------------------------------------------------------------------------------
# module properties
# ----------------------------------------------------------------------------------------------------------------------
__virtualname__ = 'net'
__proxyenabled__ = ['*']
__virtual_aliases__ = ('napalm_net',)
# uses NAPALM-based proxy to interact with network devices
# ----------------------------------------------------------------------------------------------------------------------
# property functions
# ----------------------------------------------------------------------------------------------------------------------
def __virtual__():
'''
NAPALM library must be installed for this module to work and run in a (proxy) minion.
'''
return salt.utils.napalm.virtual(__opts__, __virtualname__, __file__)
# ----------------------------------------------------------------------------------------------------------------------
# helper functions -- will not be exported
# ----------------------------------------------------------------------------------------------------------------------
def _filter_list(input_list, search_key, search_value):
'''
Filters a list of dictionary by a set of key-value pair.
:param input_list: is a list of dictionaries
:param search_key: is the key we are looking for
:param search_value: is the value we are looking for the key specified in search_key
:return: filered list of dictionaries
'''
output_list = list()
for dictionary in input_list:
if dictionary.get(search_key) == search_value:
output_list.append(dictionary)
return output_list
def _filter_dict(input_dict, search_key, search_value):
'''
Filters a dictionary of dictionaries by a key-value pair.
:param input_dict: is a dictionary whose values are lists of dictionaries
:param search_key: is the key in the leaf dictionaries
:param search_values: is the value in the leaf dictionaries
:return: filtered dictionary
'''
output_dict = dict()
for key, key_list in six.iteritems(input_dict):
key_list_filtered = _filter_list(key_list, search_key, search_value)
if key_list_filtered:
output_dict[key] = key_list_filtered
return output_dict
def _safe_commit_config(loaded_result, napalm_device):
_commit = commit(inherit_napalm_device=napalm_device) # calls the function commit, defined below
if not _commit.get('result', False):
# if unable to commit
loaded_result['comment'] += _commit['comment'] if _commit.get('comment') else 'Unable to commit.'
loaded_result['result'] = False
# unable to commit, something went wrong
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
return _commit
def _safe_dicard_config(loaded_result, napalm_device):
'''
'''
log.debug('Discarding the config')
log.debug(loaded_result)
_discarded = discard_config(inherit_napalm_device=napalm_device)
if not _discarded.get('result', False):
loaded_result['comment'] += _discarded['comment'] if _discarded.get('comment') \
else 'Unable to discard config.'
loaded_result['result'] = False
# make sure it notifies
# that something went wrong
_explicit_close(napalm_device)
__context__['retcode'] = 1
return loaded_result
return _discarded
def _explicit_close(napalm_device):
'''
Will explicily close the config session with the network device,
when running in a now-always-alive proxy minion or regular minion.
This helper must be used in configuration-related functions,
as the session is preserved and not closed before making any changes.
'''
if salt.utils.napalm.not_always_alive(__opts__):
# force closing the configuration session
# when running in a non-always-alive proxy
# or regular minion
try:
napalm_device['DRIVER'].close()
except Exception as err:
log.error('Unable to close the temp connection with the device:')
log.error(err)
log.error('Please report.')
def _config_logic(napalm_device,
loaded_result,
test=False,
debug=False,
replace=False,
commit_config=True,
loaded_config=None,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
commit_jid=None,
**kwargs):
'''
Builds the config logic for `load_config` and `load_template` functions.
'''
# As the Salt logic is built around independent events
# when it comes to configuration changes in the
# candidate DB on the network devices, we need to
# make sure we're using the same session.
# Hence, we need to pass the same object around.
# the napalm_device object is inherited from
# the load_config or load_template functions
# and forwarded to compare, discard, commit etc.
# then the decorator will make sure that
# if not proxy (when the connection is always alive)
# and the `inherit_napalm_device` is set,
# `napalm_device` will be overridden.
# See `salt.utils.napalm.proxy_napalm_wrap` decorator.
current_jid = kwargs.get('__pub_jid')
if not current_jid:
current_jid = '{0:%Y%m%d%H%M%S%f}'.format(datetime.datetime.now())
loaded_result['already_configured'] = False
loaded_result['loaded_config'] = ''
if debug:
loaded_result['loaded_config'] = loaded_config
_compare = compare_config(inherit_napalm_device=napalm_device)
if _compare.get('result', False):
loaded_result['diff'] = _compare.get('out')
loaded_result.pop('out', '') # not needed
else:
loaded_result['diff'] = None
loaded_result['result'] = False
loaded_result['comment'] = _compare.get('comment')
__context__['retcode'] = 1
return loaded_result
_loaded_res = loaded_result.get('result', False)
if not _loaded_res or test:
# if unable to load the config (errors / warnings)
# or in testing mode,
# will discard the config
if loaded_result['comment']:
loaded_result['comment'] += '\n'
if not loaded_result.get('diff', ''):
loaded_result['already_configured'] = True
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
loaded_result['comment'] += 'Configuration discarded.'
# loaded_result['result'] = False not necessary
# as the result can be true when test=True
_explicit_close(napalm_device)
if not loaded_result['result']:
__context__['retcode'] = 1
return loaded_result
if not test and commit_config:
# if not in testing mode and trying to commit
if commit_jid:
log.info('Committing the JID: %s', str(commit_jid))
removed = cancel_commit(commit_jid)
log.debug('Cleaned up the commit from the schedule')
log.debug(removed['comment'])
if loaded_result.get('diff', ''):
# if not testing mode
# and also the user wants to commit (default)
# and there are changes to commit
if commit_in or commit_at:
commit_time = __utils__['timeutil.get_time_at'](time_in=commit_in,
time_at=commit_in)
# schedule job
scheduled_job_name = '__napalm_commit_{}'.format(current_jid)
temp_file = salt.utils.files.mkstemp()
with salt.utils.files.fopen(temp_file, 'w') as fp_:
fp_.write(loaded_config)
scheduled = __salt__['schedule.add'](scheduled_job_name,
function='net.load_config',
job_kwargs={
'filename': temp_file,
'commit_jid': current_jid,
'replace': replace
},
once=commit_time)
log.debug('Scheduling job')
log.debug(scheduled)
saved = __salt__['schedule.save']() # ensure the schedule is
# persistent cross Minion restart
discarded = _safe_dicard_config(loaded_result, napalm_device)
# discard the changes
if not discarded['result']:
discarded['comment'] += ('Scheduled the job to be executed at {schedule_ts}, '
'but was unable to discard the config: \n').format(schedule_ts=commit_time)
return discarded
loaded_result['comment'] = ('Changes discarded for now, and scheduled commit at: {schedule_ts}.\n'
'The commit ID is: {current_jid}.\n'
'To discard this commit, you can execute: \n\n'
'salt {min_id} net.cancel_commit {current_jid}').format(schedule_ts=commit_time,
min_id=__opts__['id'],
current_jid=current_jid)
loaded_result['commit_id'] = current_jid
return loaded_result
log.debug('About to commit:')
log.debug(loaded_result['diff'])
if revert_in or revert_at:
revert_time = __utils__['timeutil.get_time_at'](time_in=revert_in,
time_at=revert_at)
if __grains__['os'] == 'junos':
if not HAS_JXMLEASE:
loaded_result['comment'] = ('This feature requires the library jxmlease to be installed.\n'
'To install, please execute: ``pip install jxmlease``.')
loaded_result['result'] = False
return loaded_result
timestamp_at = __utils__['timeutil.get_timestamp_at'](time_in=revert_in,
time_at=revert_at)
minutes = int((timestamp_at - time.time())/60)
_comm = __salt__['napalm.junos_commit'](confirm=minutes)
if not _comm['out']:
# If unable to commit confirm, should try to bail out
loaded_result['comment'] = 'Unable to commit confirm: {}'.format(_comm['message'])
loaded_result['result'] = False
# But before exiting, we must gracefully discard the config
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
else:
temp_file = salt.utils.files.mkstemp()
running_config = __salt__['net.config'](source='running')['out']['running']
with salt.utils.files.fopen(temp_file, 'w') as fp_:
fp_.write(running_config)
committed = _safe_commit_config(loaded_result, napalm_device)
if not committed['result']:
# If unable to commit, dicard the config (which is
# already done by the _safe_commit_config function), and
# return with the command and other details.
return loaded_result
scheduled_job_name = '__napalm_commit_{}'.format(current_jid)
scheduled = __salt__['schedule.add'](scheduled_job_name,
function='net.load_config',
job_kwargs={
'filename': temp_file,
'commit_jid': current_jid,
'replace': True
},
once=revert_time)
log.debug('Scheduling commit confirmed')
log.debug(scheduled)
saved = __salt__['schedule.save']()
loaded_result['comment'] = ('The commit ID is: {current_jid}.\n'
'This commit will be reverted at: {schedule_ts}, unless confirmed.\n'
'To confirm the commit and avoid reverting, you can execute:\n\n'
'salt {min_id} net.confirm_commit {current_jid}').format(schedule_ts=revert_time,
min_id=__opts__['id'],
current_jid=current_jid)
loaded_result['commit_id'] = current_jid
return loaded_result
committed = _safe_commit_config(loaded_result, napalm_device)
if not committed['result']:
return loaded_result
else:
# would like to commit, but there's no change
# need to call discard_config() to release the config DB
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
loaded_result['already_configured'] = True
loaded_result['comment'] = 'Already configured.'
_explicit_close(napalm_device)
if not loaded_result['result']:
__context__['retcode'] = 1
return loaded_result
# ----------------------------------------------------------------------------------------------------------------------
# callable functions
# ----------------------------------------------------------------------------------------------------------------------
@salt.utils.napalm.proxy_napalm_wrap
def connected(**kwargs): # pylint: disable=unused-argument
'''
Specifies if the connection to the device succeeded.
CLI Example:
.. code-block:: bash
salt '*' net.connected
'''
return {
'out': napalm_device.get('UP', False) # pylint: disable=undefined-variable
}
@salt.utils.napalm.proxy_napalm_wrap
def facts(**kwargs): # pylint: disable=unused-argument
'''
Returns characteristics of the network device.
:return: a dictionary with the following keys:
* uptime - Uptime of the device in seconds.
* vendor - Manufacturer of the device.
* model - Device model.
* hostname - Hostname of the device
* fqdn - Fqdn of the device
* os_version - String with the OS version running on the device.
* serial_number - Serial number of the device
* interface_list - List of the interfaces of the device
CLI Example:
.. code-block:: bash
salt '*' net.facts
Example output:
.. code-block:: python
{
'os_version': '13.3R6.5',
'uptime': 10117140,
'interface_list': [
'lc-0/0/0',
'pfe-0/0/0',
'pfh-0/0/0',
'xe-0/0/0',
'xe-0/0/1',
'xe-0/0/2',
'xe-0/0/3',
'gr-0/0/10',
'ip-0/0/10'
],
'vendor': 'Juniper',
'serial_number': 'JN131356FBFA',
'model': 'MX480',
'hostname': 're0.edge05.syd01',
'fqdn': 're0.edge05.syd01'
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_facts',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def environment(**kwargs): # pylint: disable=unused-argument
'''
Returns the environment of the device.
CLI Example:
.. code-block:: bash
salt '*' net.environment
Example output:
.. code-block:: python
{
'fans': {
'Bottom Rear Fan': {
'status': True
},
'Bottom Middle Fan': {
'status': True
},
'Top Middle Fan': {
'status': True
},
'Bottom Front Fan': {
'status': True
},
'Top Front Fan': {
'status': True
},
'Top Rear Fan': {
'status': True
}
},
'memory': {
'available_ram': 16349,
'used_ram': 4934
},
'temperature': {
'FPC 0 Exhaust A': {
'is_alert': False,
'temperature': 35.0,
'is_critical': False
}
},
'cpu': {
'1': {
'%usage': 19.0
},
'0': {
'%usage': 35.0
}
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_environment',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def cli(*commands, **kwargs): # pylint: disable=unused-argument
'''
Returns a dictionary with the raw output of all commands passed as arguments.
commands
List of commands to be executed on the device.
textfsm_parse: ``False``
Try parsing the outputs using the TextFSM templates.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``napalm_cli_textfsm_parse``.
textfsm_path
The path where the TextFSM templates can be found. This option implies
the usage of the TextFSM index file.
``textfsm_path`` can be either absolute path on the server,
either specified using the following URL mschemes: ``file://``,
``salt://``, ``http://``, ``https://``, ``ftp://``,
``s3://``, ``swift://``.
.. versionadded:: 2018.3.0
.. note::
This needs to be a directory with a flat structure, having an
index file (whose name can be specified using the ``index_file`` option)
and a number of TextFSM templates.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_path``.
textfsm_template
The path to a certain the TextFSM template.
This can be specified using the absolute path
to the file, or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
.. versionadded:: 2018.3.0
textfsm_template_dict
A dictionary with the mapping between a command
and the corresponding TextFSM path to use to extract the data.
The TextFSM paths can be specified as in ``textfsm_template``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``napalm_cli_textfsm_template_dict``.
platform_grain_name: ``os``
The name of the grain used to identify the platform name
in the TextFSM index file. Default: ``os``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_grain``.
platform_column_name: ``Platform``
The column name used to identify the platform,
exactly as specified in the TextFSM index file.
Default: ``Platform``.
.. versionadded:: 2018.3.0
.. note::
This is field is case sensitive, make sure
to assign the correct value to this option,
exactly as defined in the index file.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_column_name``.
index_file: ``index``
The name of the TextFSM index file, under the ``textfsm_path``. Default: ``index``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_index_file``.
saltenv: ``base``
Salt fileserver envrionment from which to retrieve the file.
Ignored if ``textfsm_path`` is not a ``salt://`` URL.
.. versionadded:: 2018.3.0
include_empty: ``False``
Include empty files under the ``textfsm_path``.
.. versionadded:: 2018.3.0
include_pat
Glob or regex to narrow down the files cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. versionadded:: 2018.3.0
exclude_pat
Glob or regex to exclude certain files from being cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. versionadded:: 2018.3.0
.. note::
If used with ``include_pat``, files matching this pattern will be
excluded from the subset of files defined by ``include_pat``.
CLI Example:
.. code-block:: bash
salt '*' net.cli "show version" "show chassis fan"
CLI Example with TextFSM template:
.. code-block:: bash
salt '*' net.cli textfsm_parse=True textfsm_path=salt://textfsm/
Example output:
.. code-block:: python
{
'show version and haiku': 'Hostname: re0.edge01.arn01
Model: mx480
Junos: 13.3R6.5
Help me, Obi-Wan
I just saw Episode Two
You're my only hope
',
'show chassis fan' : 'Item Status RPM Measurement
Top Rear Fan OK 3840 Spinning at intermediate-speed
Bottom Rear Fan OK 3840 Spinning at intermediate-speed
Top Middle Fan OK 3900 Spinning at intermediate-speed
Bottom Middle Fan OK 3840 Spinning at intermediate-speed
Top Front Fan OK 3810 Spinning at intermediate-speed
Bottom Front Fan OK 3840 Spinning at intermediate-speed
'
}
Example output with TextFSM parsing:
.. code-block:: json
{
"comment": "",
"result": true,
"out": {
"sh ver": [
{
"kernel": "9.1S3.5",
"documentation": "9.1S3.5",
"boot": "9.1S3.5",
"crypto": "9.1S3.5",
"chassis": "",
"routing": "9.1S3.5",
"base": "9.1S3.5",
"model": "mx960"
}
]
}
}
'''
raw_cli_outputs = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'cli',
**{
'commands': list(commands)
}
)
# thus we can display the output as is
# in case of errors, they'll be catched in the proxy
if not raw_cli_outputs['result']:
# Error -> dispaly the output as-is.
return raw_cli_outputs
textfsm_parse = kwargs.get('textfsm_parse') or __opts__.get('napalm_cli_textfsm_parse') or\
__pillar__.get('napalm_cli_textfsm_parse', False)
if not textfsm_parse:
# No TextFSM parsing required, return raw commands.
log.debug('No TextFSM parsing requested.')
return raw_cli_outputs
if 'textfsm.extract' not in __salt__ or 'textfsm.index' not in __salt__:
raw_cli_outputs['comment'] += 'Unable to process: is TextFSM installed?'
log.error(raw_cli_outputs['comment'])
return raw_cli_outputs
textfsm_template = kwargs.get('textfsm_template')
log.debug('textfsm_template: %s', textfsm_template)
textfsm_path = kwargs.get('textfsm_path') or __opts__.get('textfsm_path') or\
__pillar__.get('textfsm_path')
log.debug('textfsm_path: %s', textfsm_path)
textfsm_template_dict = kwargs.get('textfsm_template_dict') or __opts__.get('napalm_cli_textfsm_template_dict') or\
__pillar__.get('napalm_cli_textfsm_template_dict', {})
log.debug('TextFSM command-template mapping: %s', textfsm_template_dict)
index_file = kwargs.get('index_file') or __opts__.get('textfsm_index_file') or\
__pillar__.get('textfsm_index_file')
log.debug('index_file: %s', index_file)
platform_grain_name = kwargs.get('platform_grain_name') or __opts__.get('textfsm_platform_grain') or\
__pillar__.get('textfsm_platform_grain', 'os')
log.debug('platform_grain_name: %s', platform_grain_name)
platform_column_name = kwargs.get('platform_column_name') or __opts__.get('textfsm_platform_column_name') or\
__pillar__.get('textfsm_platform_column_name', 'Platform')
log.debug('platform_column_name: %s', platform_column_name)
saltenv = kwargs.get('saltenv', 'base')
include_empty = kwargs.get('include_empty', False)
include_pat = kwargs.get('include_pat')
exclude_pat = kwargs.get('exclude_pat')
processed_cli_outputs = {
'comment': raw_cli_outputs.get('comment', ''),
'result': raw_cli_outputs['result'],
'out': {}
}
log.debug('Starting to analyse the raw outputs')
for command in list(commands):
command_output = raw_cli_outputs['out'][command]
log.debug('Output from command: %s', command)
log.debug(command_output)
processed_command_output = None
if textfsm_path:
log.debug('Using the templates under %s', textfsm_path)
processed_cli_output = __salt__['textfsm.index'](command,
platform_grain_name=platform_grain_name,
platform_column_name=platform_column_name,
output=command_output.strip(),
textfsm_path=textfsm_path,
saltenv=saltenv,
include_empty=include_empty,
include_pat=include_pat,
exclude_pat=exclude_pat)
log.debug('Processed CLI output:')
log.debug(processed_cli_output)
if not processed_cli_output['result']:
log.debug('Apparently this didnt work, returnin the raw output')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {0}: {1}.'.format(command,
processed_cli_output['comment'])
log.error(processed_cli_outputs['comment'])
elif processed_cli_output['out']:
log.debug('All good, %s has a nice output!', command)
processed_command_output = processed_cli_output['out']
else:
comment = '''\nProcessing "{}" didn't fail, but didn't return anything either. Dumping raw.'''.format(
command)
processed_cli_outputs['comment'] += comment
log.error(comment)
processed_command_output = command_output
elif textfsm_template or command in textfsm_template_dict:
if command in textfsm_template_dict:
textfsm_template = textfsm_template_dict[command]
log.debug('Using %s to process the command: %s', textfsm_template, command)
processed_cli_output = __salt__['textfsm.extract'](textfsm_template,
raw_text=command_output,
saltenv=saltenv)
log.debug('Processed CLI output:')
log.debug(processed_cli_output)
if not processed_cli_output['result']:
log.debug('Apparently this didnt work, returning '
'the raw output')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {0}: {1}'.format(command,
processed_cli_output['comment'])
log.error(processed_cli_outputs['comment'])
elif processed_cli_output['out']:
log.debug('All good, %s has a nice output!', command)
processed_command_output = processed_cli_output['out']
else:
log.debug('Processing %s didnt fail, but didnt return'
' anything either. Dumping raw.', command)
processed_command_output = command_output
else:
log.error('No TextFSM template specified, or no TextFSM path defined')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {}.'.format(command)
processed_cli_outputs['out'][command] = processed_command_output
processed_cli_outputs['comment'] = processed_cli_outputs['comment'].strip()
return processed_cli_outputs
@salt.utils.napalm.proxy_napalm_wrap
def traceroute(destination, source=None, ttl=None, timeout=None, vrf=None, **kwargs): # pylint: disable=unused-argument
'''
Calls the method traceroute from the NAPALM driver object and returns a dictionary with the result of the traceroute
command executed on the device.
destination
Hostname or address of remote host
source
Source address to use in outgoing traceroute packets
ttl
IP maximum time-to-live value (or IPv6 maximum hop-limit value)
timeout
Number of seconds to wait for response (seconds)
vrf
VRF (routing instance) for traceroute attempt
.. versionadded:: 2016.11.4
CLI Example:
.. code-block:: bash
salt '*' net.traceroute 8.8.8.8
salt '*' net.traceroute 8.8.8.8 source=127.0.0.1 ttl=5 timeout=1
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'traceroute',
**{
'destination': destination,
'source': source,
'ttl': ttl,
'timeout': timeout,
'vrf': vrf
}
)
@salt.utils.napalm.proxy_napalm_wrap
def ping(destination, source=None, ttl=None, timeout=None, size=None, count=None, vrf=None, **kwargs): # pylint: disable=unused-argument
'''
Executes a ping on the network device and returns a dictionary as a result.
destination
Hostname or IP address of remote host
source
Source address of echo request
ttl
IP time-to-live value (IPv6 hop-limit value) (1..255 hops)
timeout
Maximum wait time after sending final packet (seconds)
size
Size of request packets (0..65468 bytes)
count
Number of ping requests to send (1..2000000000 packets)
vrf
VRF (routing instance) for ping attempt
.. versionadded:: 2016.11.4
CLI Example:
.. code-block:: bash
salt '*' net.ping 8.8.8.8
salt '*' net.ping 8.8.8.8 ttl=3 size=65468
salt '*' net.ping 8.8.8.8 source=127.0.0.1 timeout=1 count=100
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'ping',
**{
'destination': destination,
'source': source,
'ttl': ttl,
'timeout': timeout,
'size': size,
'count': count,
'vrf': vrf
}
)
@salt.utils.napalm.proxy_napalm_wrap
def arp(interface='', ipaddr='', macaddr='', **kwargs): # pylint: disable=unused-argument
'''
NAPALM returns a list of dictionaries with details of the ARP entries.
:param interface: interface name to filter on
:param ipaddr: IP address to filter on
:param macaddr: MAC address to filter on
:return: List of the entries in the ARP table
CLI Example:
.. code-block:: bash
salt '*' net.arp
salt '*' net.arp macaddr='5c:5e:ab:da:3c:f0'
Example output:
.. code-block:: python
[
{
'interface' : 'MgmtEth0/RSP0/CPU0/0',
'mac' : '5c:5e:ab:da:3c:f0',
'ip' : '172.17.17.1',
'age' : 1454496274.84
},
{
'interface': 'MgmtEth0/RSP0/CPU0/0',
'mac' : '66:0e:94:96:e0:ff',
'ip' : '172.17.17.2',
'age' : 1435641582.49
}
]
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_arp_table',
**{
}
)
if not proxy_output.get('result'):
return proxy_output
arp_table = proxy_output.get('out')
if interface:
arp_table = _filter_list(arp_table, 'interface', interface)
if ipaddr:
arp_table = _filter_list(arp_table, 'ip', ipaddr)
if macaddr:
arp_table = _filter_list(arp_table, 'mac', macaddr)
proxy_output.update({
'out': arp_table
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def ipaddrs(**kwargs): # pylint: disable=unused-argument
'''
Returns IP addresses configured on the device.
:return: A dictionary with the IPv4 and IPv6 addresses of the interfaces.
Returns all configured IP addresses on all interfaces as a dictionary
of dictionaries. Keys of the main dictionary represent the name of the
interface. Values of the main dictionary represent are dictionaries
that may consist of two keys 'ipv4' and 'ipv6' (one, both or none)
which are themselvs dictionaries with the IP addresses as keys.
CLI Example:
.. code-block:: bash
salt '*' net.ipaddrs
Example output:
.. code-block:: python
{
'FastEthernet8': {
'ipv4': {
'10.66.43.169': {
'prefix_length': 22
}
}
},
'Loopback555': {
'ipv4': {
'192.168.1.1': {
'prefix_length': 24
}
},
'ipv6': {
'1::1': {
'prefix_length': 64
},
'2001:DB8:1::1': {
'prefix_length': 64
},
'FE80::3': {
'prefix_length': 'N/A'
}
}
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_interfaces_ip',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def interfaces(**kwargs): # pylint: disable=unused-argument
'''
Returns details of the interfaces on the device.
:return: Returns a dictionary of dictionaries. The keys for the first
dictionary will be the interfaces in the devices.
CLI Example:
.. code-block:: bash
salt '*' net.interfaces
Example output:
.. code-block:: python
{
'Management1': {
'is_up': False,
'is_enabled': False,
'description': '',
'last_flapped': -1,
'speed': 1000,
'mac_address': 'dead:beef:dead',
},
'Ethernet1':{
'is_up': True,
'is_enabled': True,
'description': 'foo',
'last_flapped': 1429978575.1554043,
'speed': 1000,
'mac_address': 'beef:dead:beef',
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_interfaces',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def lldp(interface='', **kwargs): # pylint: disable=unused-argument
'''
Returns a detailed view of the LLDP neighbors.
:param interface: interface name to filter on
:return: A dictionary with the LLDL neighbors. The keys are the
interfaces with LLDP activated on.
CLI Example:
.. code-block:: bash
salt '*' net.lldp
salt '*' net.lldp interface='TenGigE0/0/0/8'
Example output:
.. code-block:: python
{
'TenGigE0/0/0/8': [
{
'parent_interface': 'Bundle-Ether8',
'interface_description': 'TenGigE0/0/0/8',
'remote_chassis_id': '8c60.4f69.e96c',
'remote_system_name': 'switch',
'remote_port': 'Eth2/2/1',
'remote_port_description': 'Ethernet2/2/1',
'remote_system_description': 'Cisco Nexus Operating System (NX-OS) Software 7.1(0)N1(1a)
TAC support: http://www.cisco.com/tac
Copyright (c) 2002-2015, Cisco Systems, Inc. All rights reserved.',
'remote_system_capab': 'B, R',
'remote_system_enable_capab': 'B'
}
]
}
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_lldp_neighbors_detail',
**{
}
)
if not proxy_output.get('result'):
return proxy_output
lldp_neighbors = proxy_output.get('out')
if interface:
lldp_neighbors = {interface: lldp_neighbors.get(interface)}
proxy_output.update({
'out': lldp_neighbors
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def mac(address='', interface='', vlan=0, **kwargs): # pylint: disable=unused-argument
'''
Returns the MAC Address Table on the device.
:param address: MAC address to filter on
:param interface: Interface name to filter on
:param vlan: VLAN identifier
:return: A list of dictionaries representing the entries in the MAC Address Table
CLI Example:
.. code-block:: bash
salt '*' net.mac
salt '*' net.mac vlan=10
Example output:
.. code-block:: python
[
{
'mac' : '00:1c:58:29:4a:71',
'interface' : 'xe-3/0/2',
'static' : False,
'active' : True,
'moves' : 1,
'vlan' : 10,
'last_move' : 1454417742.58
},
{
'mac' : '8c:60:4f:58:e1:c1',
'interface' : 'xe-1/0/1',
'static' : False,
'active' : True,
'moves' : 2,
'vlan' : 42,
'last_move' : 1453191948.11
}
]
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_mac_address_table',
**{
}
)
if not proxy_output.get('result'):
# if negative, leave the output unchanged
return proxy_output
mac_address_table = proxy_output.get('out')
if vlan and isinstance(vlan, int):
mac_address_table = _filter_list(mac_address_table, 'vlan', vlan)
if address:
mac_address_table = _filter_list(mac_address_table, 'mac', address)
if interface:
mac_address_table = _filter_list(mac_address_table, 'interface', interface)
proxy_output.update({
'out': mac_address_table
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def config(source=None, **kwargs): # pylint: disable=unused-argument
'''
.. versionadded:: 2017.7.0
Return the whole configuration of the network device. By default, it will
return all possible configuration sources supported by the network device.
At most, there will be:
- running config
- startup config
- candidate config
To return only one of the configurations, you can use the ``source``
argument.
source
Which configuration type you want to display, default is all of them.
Options:
- running
- candidate
- startup
:return:
The object returned is a dictionary with the following keys:
- running (string): Representation of the native running configuration.
- candidate (string): Representation of the native candidate configuration.
If the device doesn't differentiate between running and startup
configuration this will an empty string.
- startup (string): Representation of the native startup configuration.
If the device doesn't differentiate between running and startup
configuration this will an empty string.
CLI Example:
.. code-block:: bash
salt '*' net.config
salt '*' net.config source=candidate
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_config',
**{
'retrieve': source
}
)
@salt.utils.napalm.proxy_napalm_wrap
def optics(**kwargs): # pylint: disable=unused-argument
'''
.. versionadded:: 2017.7.0
Fetches the power usage on the various transceivers installed
on the network device (in dBm), and returns a view that conforms with the
OpenConfig model openconfig-platform-transceiver.yang.
:return:
Returns a dictionary where the keys are as listed below:
* intf_name (unicode)
* physical_channels
* channels (list of dicts)
* index (int)
* state
* input_power
* instant (float)
* avg (float)
* min (float)
* max (float)
* output_power
* instant (float)
* avg (float)
* min (float)
* max (float)
* laser_bias_current
* instant (float)
* avg (float)
* min (float)
* max (float)
CLI Example:
.. code-block:: bash
salt '*' net.optics
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_optics',
**{
}
)
# <---- Call NAPALM getters --------------------------------------------------------------------------------------------
# ----- Configuration specific functions ------------------------------------------------------------------------------>
@salt.utils.napalm.proxy_napalm_wrap
def load_config(filename=None,
text=None,
test=False,
commit=True,
debug=False,
replace=False,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
commit_jid=None,
inherit_napalm_device=None,
saltenv='base',
**kwargs): # pylint: disable=unused-argument
'''
Applies configuration changes on the device. It can be loaded from a file or from inline string.
If you send both a filename and a string containing the configuration, the file has higher precedence.
By default this function will commit the changes. If there are no changes, it does not commit and
the flag ``already_configured`` will be set as ``True`` to point this out.
To avoid committing the configuration, set the argument ``test`` to ``True`` and will discard (dry run).
To keep the changes but not commit, set ``commit`` to ``False``.
To replace the config, set ``replace`` to ``True``.
filename
Path to the file containing the desired configuration.
This can be specified using the absolute path to the file,
or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
.. versionchanged:: 2018.3.0
text
String containing the desired configuration.
This argument is ignored when ``filename`` is specified.
test: False
Dry run? If set as ``True``, will apply the config, discard and return the changes. Default: ``False``
and will commit the changes on the device.
commit: True
Commit? Default: ``True``.
debug: False
Debug mode. Will insert a new key under the output dictionary, as ``loaded_config`` containing the raw
configuration loaded on the device.
.. versionadded:: 2016.11.2
replace: False
Load and replace the configuration. Default: ``False``.
.. versionadded:: 2016.11.2
commit_in: ``None``
Commit the changes in a specific number of minutes / hours. Example of
accepted formats: ``5`` (commit in 5 minutes), ``2m`` (commit in 2
minutes), ``1h`` (commit the changes in 1 hour)`, ``5h30m`` (commit
the changes in 5 hours and 30 minutes).
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
commit_at: ``None``
Commit the changes at a specific time. Example of accepted formats:
``1am`` (will commit the changes at the next 1AM), ``13:20`` (will
commit at 13:20), ``1:20am``, etc.
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
revert_in: ``None``
Commit and revert the changes in a specific number of minutes / hours.
Example of accepted formats: ``5`` (revert in 5 minutes), ``2m`` (revert
in 2 minutes), ``1h`` (revert the changes in 1 hour)`, ``5h30m`` (revert
the changes in 5 hours and 30 minutes).
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
revert_at: ``None``
Commit and revert the changes at a specific time. Example of accepted
formats: ``1am`` (will commit and revert the changes at the next 1AM),
``13:20`` (will commit and revert at 13:20), ``1:20am``, etc.
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
saltenv: ``base``
Specifies the Salt environment name.
.. versionadded:: 2018.3.0
:return: a dictionary having the following keys:
* result (bool): if the config was applied successfully. It is ``False`` only in case of failure. In case \
there are no changes to be applied and successfully performs all operations it is still ``True`` and so will be \
the ``already_configured`` flag (example below)
* comment (str): a message for the user
* already_configured (bool): flag to check if there were no changes applied
* loaded_config (str): the configuration loaded on the device. Requires ``debug`` to be set as ``True``
* diff (str): returns the config changes applied
CLI Example:
.. code-block:: bash
salt '*' net.load_config text='ntp peer 192.168.0.1'
salt '*' net.load_config filename='/absolute/path/to/your/file'
salt '*' net.load_config filename='/absolute/path/to/your/file' test=True
salt '*' net.load_config filename='/absolute/path/to/your/file' commit=False
Example output:
.. code-block:: python
{
'comment': 'Configuration discarded.',
'already_configured': False,
'result': True,
'diff': '[edit interfaces xe-0/0/5]+ description "Adding a description";'
}
'''
fun = 'load_merge_candidate'
if replace:
fun = 'load_replace_candidate'
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
if filename:
text = __salt__['cp.get_file_str'](filename, saltenv=saltenv)
if text is False:
# When using salt:// or https://, if the resource is not available,
# it will either raise an exception, or return False.
ret = {
'result': False,
'out': None
}
ret['comment'] = 'Unable to read from {}. Please specify a valid file or text.'.format(filename)
log.error(ret['comment'])
return ret
if commit_jid:
# When the commit_jid argument is passed, it probably is a scheduled
# commit to be executed, and filename is a temporary file which
# can be removed after reading it.
salt.utils.files.safe_rm(filename)
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
fun,
**{
'config': text
}
)
return _config_logic(napalm_device, # pylint: disable=undefined-variable
_loaded,
test=test,
debug=debug,
replace=replace,
commit_config=commit,
loaded_config=text,
commit_at=commit_at,
commit_in=commit_in,
revert_in=revert_in,
revert_at=revert_at,
commit_jid=commit_jid,
**kwargs)
@salt.utils.napalm.proxy_napalm_wrap
def load_template(template_name=None,
template_source=None,
context=None,
defaults=None,
template_engine='jinja',
saltenv='base',
template_hash=None,
template_hash_name=None,
skip_verify=False,
test=False,
commit=True,
debug=False,
replace=False,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
inherit_napalm_device=None, # pylint: disable=unused-argument
**template_vars):
'''
Renders a configuration template (default: Jinja) and loads the result on the device.
By default this function will commit the changes. If there are no changes,
it does not commit, discards he config and the flag ``already_configured``
will be set as ``True`` to point this out.
To avoid committing the configuration, set the argument ``test`` to ``True``
and will discard (dry run).
To preserve the changes, set ``commit`` to ``False``.
However, this is recommended to be used only in exceptional cases
when there are applied few consecutive states
and/or configuration changes.
Otherwise the user might forget that the config DB is locked
and the candidate config buffer is not cleared/merged in the running config.
To replace the config, set ``replace`` to ``True``.
template_name
Identifies path to the template source.
The template can be either stored on the local machine, either remotely.
The recommended location is under the ``file_roots``
as specified in the master config file.
For example, let's suppose the ``file_roots`` is configured as:
.. code-block:: yaml
file_roots:
base:
- /etc/salt/states
Placing the template under ``/etc/salt/states/templates/example.jinja``,
it can be used as ``salt://templates/example.jinja``.
Alternatively, for local files, the user can specify the absolute path.
If remotely, the source can be retrieved via ``http``, ``https`` or ``ftp``.
Examples:
- ``salt://my_template.jinja``
- ``/absolute/path/to/my_template.jinja``
- ``http://example.com/template.cheetah``
- ``https:/example.com/template.mako``
- ``ftp://example.com/template.py``
.. versionchanged:: 2019.2.0
This argument can now support a list of templates to be rendered.
The resulting configuration text is loaded at once, as a single
configuration chunk.
template_source: None
Inline config template to be rendered and loaded on the device.
template_hash: None
Hash of the template file. Format: ``{hash_type: 'md5', 'hsum': <md5sum>}``
.. versionadded:: 2016.11.2
context: None
Overrides default context variables passed to the template.
.. versionadded:: 2019.2.0
template_hash_name: None
When ``template_hash`` refers to a remote file,
this specifies the filename to look for in that file.
.. versionadded:: 2016.11.2
saltenv: ``base``
Specifies the template environment.
This will influence the relative imports inside the templates.
.. versionadded:: 2016.11.2
template_engine: jinja
The following templates engines are supported:
- :mod:`cheetah<salt.renderers.cheetah>`
- :mod:`genshi<salt.renderers.genshi>`
- :mod:`jinja<salt.renderers.jinja>`
- :mod:`mako<salt.renderers.mako>`
- :mod:`py<salt.renderers.py>`
- :mod:`wempy<salt.renderers.wempy>`
.. versionadded:: 2016.11.2
skip_verify: True
If ``True``, hash verification of remote file sources
(``http://``, ``https://``, ``ftp://``) will be skipped,
and the ``source_hash`` argument will be ignored.
.. versionadded:: 2016.11.2
test: False
Dry run? If set to ``True``, will apply the config,
discard and return the changes.
Default: ``False`` and will commit the changes on the device.
commit: True
Commit? (default: ``True``)
debug: False
Debug mode. Will insert a new key under the output dictionary,
as ``loaded_config`` containing the raw result after the template was rendered.
.. versionadded:: 2016.11.2
replace: False
Load and replace the configuration.
.. versionadded:: 2016.11.2
commit_in: ``None``
Commit the changes in a specific number of minutes / hours. Example of
accepted formats: ``5`` (commit in 5 minutes), ``2m`` (commit in 2
minutes), ``1h`` (commit the changes in 1 hour)`, ``5h30m`` (commit
the changes in 5 hours and 30 minutes).
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
commit_at: ``None``
Commit the changes at a specific time. Example of accepted formats:
``1am`` (will commit the changes at the next 1AM), ``13:20`` (will
commit at 13:20), ``1:20am``, etc.
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
revert_in: ``None``
Commit and revert the changes in a specific number of minutes / hours.
Example of accepted formats: ``5`` (revert in 5 minutes), ``2m`` (revert
in 2 minutes), ``1h`` (revert the changes in 1 hour)`, ``5h30m`` (revert
the changes in 5 hours and 30 minutes).
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
revert_at: ``None``
Commit and revert the changes at a specific time. Example of accepted
formats: ``1am`` (will commit and revert the changes at the next 1AM),
``13:20`` (will commit and revert at 13:20), ``1:20am``, etc.
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
defaults: None
Default variables/context passed to the template.
.. versionadded:: 2016.11.2
template_vars
Dictionary with the arguments/context to be used when the template is rendered.
.. note::
Do not explicitly specify this argument. This represents any other
variable that will be sent to the template rendering system.
Please see the examples below!
.. note::
It is more recommended to use the ``context`` argument to avoid
conflicts between CLI arguments and template variables.
:return: a dictionary having the following keys:
- result (bool): if the config was applied successfully. It is ``False``
only in case of failure. In case there are no changes to be applied and
successfully performs all operations it is still ``True`` and so will be
the ``already_configured`` flag (example below)
- comment (str): a message for the user
- already_configured (bool): flag to check if there were no changes applied
- loaded_config (str): the configuration loaded on the device, after
rendering the template. Requires ``debug`` to be set as ``True``
- diff (str): returns the config changes applied
The template can use variables from the ``grains``, ``pillar`` or ``opts``, for example:
.. code-block:: jinja
{% set router_model = grains.get('model') -%}
{% set router_vendor = grains.get('vendor') -%}
{% set os_version = grains.get('version') -%}
{% set hostname = pillar.get('proxy', {}).get('host') -%}
{% if router_vendor|lower == 'juniper' %}
system {
host-name {{hostname}};
}
{% elif router_vendor|lower == 'cisco' %}
hostname {{hostname}}
{% endif %}
CLI Examples:
.. code-block:: bash
salt '*' net.load_template set_ntp_peers peers=[192.168.0.1] # uses NAPALM default templates
# inline template:
salt -G 'os:junos' net.load_template template_source='system { host-name {{host_name}}; }' \
host_name='MX480.lab'
# inline template using grains info:
salt -G 'os:junos' net.load_template \
template_source='system { host-name {{grains.model}}.lab; }'
# if the device is a MX480, the command above will set the hostname as: MX480.lab
# inline template using pillar data:
salt -G 'os:junos' net.load_template template_source='system { host-name {{pillar.proxy.host}}; }'
salt '*' net.load_template https://bit.ly/2OhSgqP hostname=example # will commit
salt '*' net.load_template https://bit.ly/2OhSgqP hostname=example test=True # dry run
salt '*' net.load_template salt://templates/example.jinja debug=True # Using the salt:// URI
# render a mako template:
salt '*' net.load_template salt://templates/example.mako template_engine=mako debug=True
# render remote template
salt -G 'os:junos' net.load_template http://bit.ly/2fReJg7 test=True debug=True peers=['192.168.0.1']
salt -G 'os:ios' net.load_template http://bit.ly/2gKOj20 test=True debug=True peers=['192.168.0.1']
# render multiple templates at once
salt '*' net.load_template "['https://bit.ly/2OhSgqP', 'salt://templates/example.jinja']" context="{'hostname': 'example'}"
Example output:
.. code-block:: python
{
'comment': '',
'already_configured': False,
'result': True,
'diff': '[edit system]+ host-name edge01.bjm01',
'loaded_config': 'system { host-name edge01.bjm01; }''
}
'''
_rendered = ''
_loaded = {
'result': True,
'comment': '',
'out': None
}
loaded_config = None
# prechecks
deprecated_args = ('template_user', 'template_attrs', 'template_group', 'template_mode')
for deprecated_arg in deprecated_args:
if template_vars.get(deprecated_arg):
del template_vars[deprecated_arg]
salt.utils.versions.warn_until(
'Sodium',
('The \'{arg}\' argument to \'net.load_template\' is deprecated '
'and has been ignored').format(arg=deprecated_arg)
)
if template_engine not in salt.utils.templates.TEMPLATE_REGISTRY:
_loaded.update({
'result': False,
'comment': 'Invalid templating engine! Choose between: {tpl_eng_opts}'.format(
tpl_eng_opts=', '.join(list(salt.utils.templates.TEMPLATE_REGISTRY.keys()))
)
})
return _loaded # exit
# to check if will be rendered by salt or NAPALM
salt_render_prefixes = ('salt://', 'http://', 'https://', 'ftp://')
salt_render = False
file_exists = False
if not isinstance(template_name, (tuple, list)):
for salt_render_prefix in salt_render_prefixes:
if not salt_render:
salt_render = salt_render or template_name.startswith(salt_render_prefix)
file_exists = __salt__['file.file_exists'](template_name)
if template_source or file_exists or salt_render or isinstance(template_name, (tuple, list)):
# either inline template
# either template in a custom path
# either abs path send
# either starts with salt:// and
# then use Salt render system
if context is None:
context = {}
context.update(template_vars)
# if needed to render the template send as inline arg
if template_source:
# render the content
_rendered = __salt__['file.apply_template_on_contents'](
contents=template_source,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv
)
if not isinstance(_rendered, six.string_types):
if 'result' in _rendered:
_loaded['result'] = _rendered['result']
else:
_loaded['result'] = False
if 'comment' in _rendered:
_loaded['comment'] = _rendered['comment']
else:
_loaded['comment'] = 'Error while rendering the template.'
return _loaded
else:
# render the file - either local, either remote
if not isinstance(template_name, (list, tuple)):
template_name = [template_name]
if template_hash_name and not isinstance(template_hash_name, (list, tuple)):
template_hash_name = [template_hash_name]
elif not template_hash_name:
template_hash_name = [None] * len(template_name)
if template_hash and isinstance(template_hash, six.string_types) and not\
(template_hash.startswith('salt://') or template_hash.startswith('file://')):
# If the template hash is passed as string, and it's not a file
# (starts with the salt:// or file:// URI), then make it a list
# of 1 element (for the iteration below)
template_hash = [template_hash]
elif template_hash and isinstance(template_hash, six.string_types) and\
(template_hash.startswith('salt://') or template_hash.startswith('file://')):
# If the template hash is a file URI, then provide the same value
# for each of the templates in the list, as probably they all
# share the same hash file, otherwise the user should provide
# this as a list
template_hash = [template_hash] * len(template_name)
elif not template_hash:
template_hash = [None] * len(template_name)
for tpl_index, tpl_name in enumerate(template_name):
tpl_hash = template_hash[tpl_index]
tpl_hash_name = template_hash_name[tpl_index]
_rand_filename = __salt__['random.hash'](tpl_name, 'md5')
_temp_file = __salt__['file.join']('/tmp', _rand_filename)
_managed = __salt__['file.get_managed'](name=_temp_file,
source=tpl_name,
source_hash=tpl_hash,
source_hash_name=tpl_hash_name,
user=None,
group=None,
mode=None,
attrs=None,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv,
skip_verify=skip_verify)
if not isinstance(_managed, (list, tuple)) and isinstance(_managed, six.string_types):
_loaded['comment'] += _managed
_loaded['result'] = False
elif isinstance(_managed, (list, tuple)) and not _managed:
_loaded['result'] = False
_loaded['comment'] += 'Error while rendering the template.'
elif isinstance(_managed, (list, tuple)) and not _managed[0]:
_loaded['result'] = False
_loaded['comment'] += _managed[-1] # contains the error message
if _loaded['result']: # all good
_temp_tpl_file = _managed[0]
_temp_tpl_file_exists = __salt__['file.file_exists'](_temp_tpl_file)
if not _temp_tpl_file_exists:
_loaded['result'] = False
_loaded['comment'] += 'Error while rendering the template.'
return _loaded
_rendered += __salt__['file.read'](_temp_tpl_file)
__salt__['file.remove'](_temp_tpl_file)
else:
return _loaded # exit
loaded_config = _rendered
if _loaded['result']: # all good
fun = 'load_merge_candidate'
if replace: # replace requested
fun = 'load_replace_candidate'
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
fun,
**{
'config': _rendered
}
)
else:
salt.utils.versions.warn_until(
'Sodium',
'Native NAPALM templates support will be removed in the Sodium '
'release. Please consider using the Salt rendering pipeline instead.'
'If you are using the \'netntp\', \'netsnmp\', or \'netusers\' Salt '
'State modules, you can ignore this message'
)
# otherwise, use NAPALM render system, injecting pillar/grains/opts vars
load_templates_params = defaults if defaults else {}
load_templates_params.update(template_vars)
load_templates_params.update(
{
'template_name': template_name,
'template_source': template_source, # inline template
'pillar': __pillar__, # inject pillar content
'grains': __grains__, # inject grains content
'opts': __opts__ # inject opts content
}
)
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
# so we'll set the CLOSE global explicitly as False
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'load_template',
**load_templates_params
)
return _config_logic(napalm_device, # pylint: disable=undefined-variable
_loaded,
test=test,
debug=debug,
replace=replace,
commit_config=commit,
loaded_config=loaded_config,
commit_at=commit_at,
commit_in=commit_in,
revert_in=revert_in,
revert_at=revert_at,
**template_vars)
@salt.utils.napalm.proxy_napalm_wrap
def commit(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Commits the configuration changes made on the network device.
CLI Example:
.. code-block:: bash
salt '*' net.commit
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'commit_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def discard_config(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
"""
Discards the changes applied.
CLI Example:
.. code-block:: bash
salt '*' net.discard_config
"""
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'discard_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def compare_config(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Returns the difference between the running config and the candidate config.
CLI Example:
.. code-block:: bash
salt '*' net.compare_config
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'compare_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def rollback(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Rollbacks the configuration.
CLI Example:
.. code-block:: bash
salt '*' net.rollback
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'rollback',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def config_changed(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Will prompt if the configuration has been changed.
:return: A tuple with a boolean that specifies if the config was changed on the device.\
And a string that provides more details of the reason why the configuration was not changed.
CLI Example:
.. code-block:: bash
salt '*' net.config_changed
'''
is_config_changed = False
reason = ''
try_compare = compare_config(inherit_napalm_device=napalm_device) # pylint: disable=undefined-variable
if try_compare.get('result'):
if try_compare.get('out'):
is_config_changed = True
else:
reason = 'Configuration was not changed on the device.'
else:
reason = try_compare.get('comment')
return is_config_changed, reason
@salt.utils.napalm.proxy_napalm_wrap
def config_control(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Will check if the configuration was changed.
If differences found, will try to commit.
In case commit unsuccessful, will try to rollback.
:return: A tuple with a boolean that specifies if the config was changed/committed/rollbacked on the device.\
And a string that provides more details of the reason why the configuration was not committed properly.
CLI Example:
.. code-block:: bash
salt '*' net.config_control
'''
result = True
comment = ''
changed, not_changed_rsn = config_changed(inherit_napalm_device=napalm_device) # pylint: disable=undefined-variable
if not changed:
return (changed, not_changed_rsn)
# config changed, thus let's try to commit
try_commit = commit()
if not try_commit.get('result'):
result = False
comment = 'Unable to commit the changes: {reason}.\n\
Will try to rollback now!'.format(
reason=try_commit.get('comment')
)
try_rollback = rollback()
if not try_rollback.get('result'):
comment += '\nCannot rollback! {reason}'.format(
reason=try_rollback.get('comment')
)
return result, comment
def cancel_commit(jid):
'''
.. versionadded:: 2019.2.0
Cancel a commit scheduled to be executed via the ``commit_in`` and
``commit_at`` arguments from the
:py:func:`net.load_template <salt.modules.napalm_network.load_template>` or
:py:func:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit ID is displayed when the commit is scheduled
via the functions named above.
CLI Example:
.. code-block:: bash
salt '*' net.cancel_commit 20180726083540640360
'''
job_name = '__napalm_commit_{}'.format(jid)
removed = __salt__['schedule.delete'](job_name)
if removed['result']:
saved = __salt__['schedule.save']()
removed['comment'] = 'Commit #{jid} cancelled.'.format(jid=jid)
else:
removed['comment'] = 'Unable to find commit #{jid}.'.format(jid=jid)
return removed
def save_config(source=None,
path=None):
'''
.. versionadded:: 2019.2.0
Save the configuration to a file on the local file system.
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``,
``startup``. Default: ``running``.
path
Absolute path to file where to save the configuration.
To push the files to the Master, use
:mod:`cp.push <salt.modules.cp.push>` Execution function.
CLI Example:
.. code-block:: bash
salt '*' net.save_config source=running
'''
if not source:
source = 'running'
if not path:
path = salt.utils.files.mkstemp()
running_config = __salt__['net.config'](source=source)
if not running_config or not running_config['result']:
log.error('Unable to retrieve the config')
return running_config
with salt.utils.files.fopen(path, 'w') as fh_:
fh_.write(running_config['out'][source])
return {
'result': True,
'out': path,
'comment': '{source} config saved to {path}'.format(source=source, path=path)
}
def replace_pattern(pattern,
repl,
count=0,
flags=8,
bufsize=1,
append_if_not_found=False,
prepend_if_not_found=False,
not_found_content=None,
search_only=False,
show_changes=True,
backslash_literal=False,
source=None,
path=None,
test=False,
replace=True,
debug=False,
commit=True):
'''
.. versionadded:: 2019.2.0
Replace occurrences of a pattern in the configuration source. If
``show_changes`` is ``True``, then a diff of what changed will be returned,
otherwise a ``True`` will be returned when changes are made, and ``False``
when no changes are made.
This is a pure Python implementation that wraps Python's :py:func:`~re.sub`.
pattern
A regular expression, to be matched using Python's
:py:func:`~re.search`.
repl
The replacement text.
count: ``0``
Maximum number of pattern occurrences to be replaced. If count is a
positive integer ``n``, only ``n`` occurrences will be replaced,
otherwise all occurrences will be replaced.
flags (list or int): ``8``
A list of flags defined in the ``re`` module documentation from the
Python standard library. Each list item should be a string that will
correlate to the human-friendly flag name. E.g., ``['IGNORECASE',
'MULTILINE']``. Optionally, ``flags`` may be an int, with a value
corresponding to the XOR (``|``) of all the desired flags. Defaults to
8 (which supports 'MULTILINE').
bufsize (int or str): ``1``
How much of the configuration to buffer into memory at once. The
default value ``1`` processes one line at a time. The special value
``file`` may be specified which will read the entire file into memory
before processing.
append_if_not_found: ``False``
If set to ``True``, and pattern is not found, then the content will be
appended to the file.
prepend_if_not_found: ``False``
If set to ``True`` and pattern is not found, then the content will be
prepended to the file.
not_found_content
Content to use for append/prepend if not found. If None (default), uses
``repl``. Useful when ``repl`` uses references to group in pattern.
search_only: ``False``
If set to true, this no changes will be performed on the file, and this
function will simply return ``True`` if the pattern was matched, and
``False`` if not.
show_changes: ``True``
If ``True``, return a diff of changes made. Otherwise, return ``True``
if changes were made, and ``False`` if not.
backslash_literal: ``False``
Interpret backslashes as literal backslashes for the repl and not
escape characters. This will help when using append/prepend so that
the backslashes are not interpreted for the repl on the second run of
the state.
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path
Save the temporary configuration to a specific path, then read from
there.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' net.replace_pattern "bind-address\\s*=" "bind-address:"
CLI Example:
.. code-block:: bash
salt '*' net.replace_pattern PREFIX-LIST_NAME new-prefix-list-name
salt '*' net.replace_pattern bgp-group-name new-bgp-group-name count=1
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
replace_pattern = __salt__['file.replace'](path,
pattern,
repl,
count=count,
flags=flags,
bufsize=bufsize,
append_if_not_found=append_if_not_found,
prepend_if_not_found=prepend_if_not_found,
not_found_content=not_found_content,
search_only=search_only,
show_changes=show_changes,
backslash_literal=backslash_literal)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
def blockreplace(marker_start,
marker_end,
content='',
append_if_not_found=False,
prepend_if_not_found=False,
show_changes=True,
append_newline=False,
source='running',
path=None,
test=False,
commit=True,
debug=False,
replace=True):
'''
.. versionadded:: 2019.2.0
Replace content of the configuration source, delimited by the line markers.
A block of content delimited by comments can help you manage several lines
without worrying about old entries removal.
marker_start
The line content identifying a line as the start of the content block.
Note that the whole line containing this marker will be considered,
so whitespace or extra content before or after the marker is included
in final output.
marker_end
The line content identifying a line as the end of the content block.
Note that the whole line containing this marker will be considered,
so whitespace or extra content before or after the marker is included
in final output.
content
The content to be used between the two lines identified by
``marker_start`` and ``marker_stop``.
append_if_not_found: ``False``
If markers are not found and set to True then, the markers and content
will be appended to the file.
prepend_if_not_found: ``False``
If markers are not found and set to True then, the markers and content
will be prepended to the file.
append_newline: ``False``
Controls whether or not a newline is appended to the content block.
If the value of this argument is ``True`` then a newline will be added
to the content block. If it is ``False``, then a newline will not be
added to the content block. If it is ``None`` then a newline will only
be added to the content block if it does not already end in a newline.
show_changes: ``True``
Controls how changes are presented. If ``True``, this function will
return the of the changes made.
If ``False``, then it will return a boolean (``True`` if any changes
were made, otherwise False).
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path: ``None``
Save the temporary configuration to a specific path, then read from
there. This argument is optional, can be used when you prefers a
particular location of the temporary file.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
CLI Example:
.. code-block:: bash
salt '*' net.blockreplace 'ntp' 'interface' ''
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
replace_pattern = __salt__['file.blockreplace'](path,
marker_start=marker_start,
marker_end=marker_end,
content=content,
append_if_not_found=append_if_not_found,
prepend_if_not_found=prepend_if_not_found,
show_changes=show_changes,
append_newline=append_newline)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
def patch(patchfile,
options='',
saltenv='base',
source_hash=None,
show_changes=True,
source='running',
path=None,
test=False,
commit=True,
debug=False,
replace=True):
'''
.. versionadded:: 2019.2.0
Apply a patch to the configuration source, and load the result into the
running config of the device.
patchfile
A patch file to apply to the configuration source.
options
Options to pass to patch.
source_hash
If the patch file (specified via the ``patchfile`` argument) is an
HTTP(S) or FTP URL and the file exists in the minion's file cache, this
option can be passed to keep the minion from re-downloading the file if
the cached copy matches the specified hash.
show_changes: ``True``
Controls how changes are presented. If ``True``, this function will
return the of the changes made.
If ``False``, then it will return a boolean (``True`` if any changes
were made, otherwise False).
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path: ``None``
Save the temporary configuration to a specific path, then read from
there. This argument is optional, can the user prefers a particular
location of the temporary file.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
CLI Example:
.. code-block:: bash
salt '*' net.patch https://example.com/running_config.patch
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
patchfile_cache = __salt__['cp.cache_file'](patchfile)
if patchfile_cache is False:
return {
'out': None,
'result': False,
'comment': 'The file "{}" does not exist.'.format(patchfile)
}
replace_pattern = __salt__['file.patch'](path,
patchfile_cache,
options=options)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
# <---- Configuration specific functions -------------------------------------------------------------------------------
|
saltstack/salt
|
salt/modules/napalm_network.py
|
save_config
|
python
|
def save_config(source=None,
path=None):
'''
.. versionadded:: 2019.2.0
Save the configuration to a file on the local file system.
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``,
``startup``. Default: ``running``.
path
Absolute path to file where to save the configuration.
To push the files to the Master, use
:mod:`cp.push <salt.modules.cp.push>` Execution function.
CLI Example:
.. code-block:: bash
salt '*' net.save_config source=running
'''
if not source:
source = 'running'
if not path:
path = salt.utils.files.mkstemp()
running_config = __salt__['net.config'](source=source)
if not running_config or not running_config['result']:
log.error('Unable to retrieve the config')
return running_config
with salt.utils.files.fopen(path, 'w') as fh_:
fh_.write(running_config['out'][source])
return {
'result': True,
'out': path,
'comment': '{source} config saved to {path}'.format(source=source, path=path)
}
|
.. versionadded:: 2019.2.0
Save the configuration to a file on the local file system.
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``,
``startup``. Default: ``running``.
path
Absolute path to file where to save the configuration.
To push the files to the Master, use
:mod:`cp.push <salt.modules.cp.push>` Execution function.
CLI Example:
.. code-block:: bash
salt '*' net.save_config source=running
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_network.py#L2294-L2330
|
[
"def mkstemp(*args, **kwargs):\n '''\n Helper function which does exactly what ``tempfile.mkstemp()`` does but\n accepts another argument, ``close_fd``, which, by default, is true and closes\n the fd before returning the file path. Something commonly done throughout\n Salt's code.\n '''\n if 'prefix' not in kwargs:\n kwargs['prefix'] = '__salt.tmp.'\n close_fd = kwargs.pop('close_fd', True)\n fd_, f_path = tempfile.mkstemp(*args, **kwargs)\n if close_fd is False:\n return fd_, f_path\n os.close(fd_)\n del fd_\n return f_path\n",
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n"
] |
# -*- coding: utf-8 -*-
'''
NAPALM Network
==============
Basic methods for interaction with the network device through the virtual proxy 'napalm'.
:codeauthor: Mircea Ulinic <mircea@cloudflare.com> & Jerome Fleury <jf@cloudflare.com>
:maturity: new
:depends: napalm
:platform: unix
Dependencies
------------
- :mod:`napalm proxy minion <salt.proxy.napalm>`
.. versionadded:: 2016.11.0
.. versionchanged:: 2017.7.0
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import time
import logging
import datetime
log = logging.getLogger(__name__)
# Import Salt libs
from salt.ext import six
import salt.utils.files
import salt.utils.napalm
import salt.utils.versions
import salt.utils.templates
# Import 3rd-party libs
try:
import jxmlease # pylint: disable=unused-import
HAS_JXMLEASE = True
except ImportError:
HAS_JXMLEASE = False
# ----------------------------------------------------------------------------------------------------------------------
# module properties
# ----------------------------------------------------------------------------------------------------------------------
__virtualname__ = 'net'
__proxyenabled__ = ['*']
__virtual_aliases__ = ('napalm_net',)
# uses NAPALM-based proxy to interact with network devices
# ----------------------------------------------------------------------------------------------------------------------
# property functions
# ----------------------------------------------------------------------------------------------------------------------
def __virtual__():
'''
NAPALM library must be installed for this module to work and run in a (proxy) minion.
'''
return salt.utils.napalm.virtual(__opts__, __virtualname__, __file__)
# ----------------------------------------------------------------------------------------------------------------------
# helper functions -- will not be exported
# ----------------------------------------------------------------------------------------------------------------------
def _filter_list(input_list, search_key, search_value):
'''
Filters a list of dictionary by a set of key-value pair.
:param input_list: is a list of dictionaries
:param search_key: is the key we are looking for
:param search_value: is the value we are looking for the key specified in search_key
:return: filered list of dictionaries
'''
output_list = list()
for dictionary in input_list:
if dictionary.get(search_key) == search_value:
output_list.append(dictionary)
return output_list
def _filter_dict(input_dict, search_key, search_value):
'''
Filters a dictionary of dictionaries by a key-value pair.
:param input_dict: is a dictionary whose values are lists of dictionaries
:param search_key: is the key in the leaf dictionaries
:param search_values: is the value in the leaf dictionaries
:return: filtered dictionary
'''
output_dict = dict()
for key, key_list in six.iteritems(input_dict):
key_list_filtered = _filter_list(key_list, search_key, search_value)
if key_list_filtered:
output_dict[key] = key_list_filtered
return output_dict
def _safe_commit_config(loaded_result, napalm_device):
_commit = commit(inherit_napalm_device=napalm_device) # calls the function commit, defined below
if not _commit.get('result', False):
# if unable to commit
loaded_result['comment'] += _commit['comment'] if _commit.get('comment') else 'Unable to commit.'
loaded_result['result'] = False
# unable to commit, something went wrong
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
return _commit
def _safe_dicard_config(loaded_result, napalm_device):
'''
'''
log.debug('Discarding the config')
log.debug(loaded_result)
_discarded = discard_config(inherit_napalm_device=napalm_device)
if not _discarded.get('result', False):
loaded_result['comment'] += _discarded['comment'] if _discarded.get('comment') \
else 'Unable to discard config.'
loaded_result['result'] = False
# make sure it notifies
# that something went wrong
_explicit_close(napalm_device)
__context__['retcode'] = 1
return loaded_result
return _discarded
def _explicit_close(napalm_device):
'''
Will explicily close the config session with the network device,
when running in a now-always-alive proxy minion or regular minion.
This helper must be used in configuration-related functions,
as the session is preserved and not closed before making any changes.
'''
if salt.utils.napalm.not_always_alive(__opts__):
# force closing the configuration session
# when running in a non-always-alive proxy
# or regular minion
try:
napalm_device['DRIVER'].close()
except Exception as err:
log.error('Unable to close the temp connection with the device:')
log.error(err)
log.error('Please report.')
def _config_logic(napalm_device,
loaded_result,
test=False,
debug=False,
replace=False,
commit_config=True,
loaded_config=None,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
commit_jid=None,
**kwargs):
'''
Builds the config logic for `load_config` and `load_template` functions.
'''
# As the Salt logic is built around independent events
# when it comes to configuration changes in the
# candidate DB on the network devices, we need to
# make sure we're using the same session.
# Hence, we need to pass the same object around.
# the napalm_device object is inherited from
# the load_config or load_template functions
# and forwarded to compare, discard, commit etc.
# then the decorator will make sure that
# if not proxy (when the connection is always alive)
# and the `inherit_napalm_device` is set,
# `napalm_device` will be overridden.
# See `salt.utils.napalm.proxy_napalm_wrap` decorator.
current_jid = kwargs.get('__pub_jid')
if not current_jid:
current_jid = '{0:%Y%m%d%H%M%S%f}'.format(datetime.datetime.now())
loaded_result['already_configured'] = False
loaded_result['loaded_config'] = ''
if debug:
loaded_result['loaded_config'] = loaded_config
_compare = compare_config(inherit_napalm_device=napalm_device)
if _compare.get('result', False):
loaded_result['diff'] = _compare.get('out')
loaded_result.pop('out', '') # not needed
else:
loaded_result['diff'] = None
loaded_result['result'] = False
loaded_result['comment'] = _compare.get('comment')
__context__['retcode'] = 1
return loaded_result
_loaded_res = loaded_result.get('result', False)
if not _loaded_res or test:
# if unable to load the config (errors / warnings)
# or in testing mode,
# will discard the config
if loaded_result['comment']:
loaded_result['comment'] += '\n'
if not loaded_result.get('diff', ''):
loaded_result['already_configured'] = True
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
loaded_result['comment'] += 'Configuration discarded.'
# loaded_result['result'] = False not necessary
# as the result can be true when test=True
_explicit_close(napalm_device)
if not loaded_result['result']:
__context__['retcode'] = 1
return loaded_result
if not test and commit_config:
# if not in testing mode and trying to commit
if commit_jid:
log.info('Committing the JID: %s', str(commit_jid))
removed = cancel_commit(commit_jid)
log.debug('Cleaned up the commit from the schedule')
log.debug(removed['comment'])
if loaded_result.get('diff', ''):
# if not testing mode
# and also the user wants to commit (default)
# and there are changes to commit
if commit_in or commit_at:
commit_time = __utils__['timeutil.get_time_at'](time_in=commit_in,
time_at=commit_in)
# schedule job
scheduled_job_name = '__napalm_commit_{}'.format(current_jid)
temp_file = salt.utils.files.mkstemp()
with salt.utils.files.fopen(temp_file, 'w') as fp_:
fp_.write(loaded_config)
scheduled = __salt__['schedule.add'](scheduled_job_name,
function='net.load_config',
job_kwargs={
'filename': temp_file,
'commit_jid': current_jid,
'replace': replace
},
once=commit_time)
log.debug('Scheduling job')
log.debug(scheduled)
saved = __salt__['schedule.save']() # ensure the schedule is
# persistent cross Minion restart
discarded = _safe_dicard_config(loaded_result, napalm_device)
# discard the changes
if not discarded['result']:
discarded['comment'] += ('Scheduled the job to be executed at {schedule_ts}, '
'but was unable to discard the config: \n').format(schedule_ts=commit_time)
return discarded
loaded_result['comment'] = ('Changes discarded for now, and scheduled commit at: {schedule_ts}.\n'
'The commit ID is: {current_jid}.\n'
'To discard this commit, you can execute: \n\n'
'salt {min_id} net.cancel_commit {current_jid}').format(schedule_ts=commit_time,
min_id=__opts__['id'],
current_jid=current_jid)
loaded_result['commit_id'] = current_jid
return loaded_result
log.debug('About to commit:')
log.debug(loaded_result['diff'])
if revert_in or revert_at:
revert_time = __utils__['timeutil.get_time_at'](time_in=revert_in,
time_at=revert_at)
if __grains__['os'] == 'junos':
if not HAS_JXMLEASE:
loaded_result['comment'] = ('This feature requires the library jxmlease to be installed.\n'
'To install, please execute: ``pip install jxmlease``.')
loaded_result['result'] = False
return loaded_result
timestamp_at = __utils__['timeutil.get_timestamp_at'](time_in=revert_in,
time_at=revert_at)
minutes = int((timestamp_at - time.time())/60)
_comm = __salt__['napalm.junos_commit'](confirm=minutes)
if not _comm['out']:
# If unable to commit confirm, should try to bail out
loaded_result['comment'] = 'Unable to commit confirm: {}'.format(_comm['message'])
loaded_result['result'] = False
# But before exiting, we must gracefully discard the config
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
else:
temp_file = salt.utils.files.mkstemp()
running_config = __salt__['net.config'](source='running')['out']['running']
with salt.utils.files.fopen(temp_file, 'w') as fp_:
fp_.write(running_config)
committed = _safe_commit_config(loaded_result, napalm_device)
if not committed['result']:
# If unable to commit, dicard the config (which is
# already done by the _safe_commit_config function), and
# return with the command and other details.
return loaded_result
scheduled_job_name = '__napalm_commit_{}'.format(current_jid)
scheduled = __salt__['schedule.add'](scheduled_job_name,
function='net.load_config',
job_kwargs={
'filename': temp_file,
'commit_jid': current_jid,
'replace': True
},
once=revert_time)
log.debug('Scheduling commit confirmed')
log.debug(scheduled)
saved = __salt__['schedule.save']()
loaded_result['comment'] = ('The commit ID is: {current_jid}.\n'
'This commit will be reverted at: {schedule_ts}, unless confirmed.\n'
'To confirm the commit and avoid reverting, you can execute:\n\n'
'salt {min_id} net.confirm_commit {current_jid}').format(schedule_ts=revert_time,
min_id=__opts__['id'],
current_jid=current_jid)
loaded_result['commit_id'] = current_jid
return loaded_result
committed = _safe_commit_config(loaded_result, napalm_device)
if not committed['result']:
return loaded_result
else:
# would like to commit, but there's no change
# need to call discard_config() to release the config DB
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
loaded_result['already_configured'] = True
loaded_result['comment'] = 'Already configured.'
_explicit_close(napalm_device)
if not loaded_result['result']:
__context__['retcode'] = 1
return loaded_result
# ----------------------------------------------------------------------------------------------------------------------
# callable functions
# ----------------------------------------------------------------------------------------------------------------------
@salt.utils.napalm.proxy_napalm_wrap
def connected(**kwargs): # pylint: disable=unused-argument
'''
Specifies if the connection to the device succeeded.
CLI Example:
.. code-block:: bash
salt '*' net.connected
'''
return {
'out': napalm_device.get('UP', False) # pylint: disable=undefined-variable
}
@salt.utils.napalm.proxy_napalm_wrap
def facts(**kwargs): # pylint: disable=unused-argument
'''
Returns characteristics of the network device.
:return: a dictionary with the following keys:
* uptime - Uptime of the device in seconds.
* vendor - Manufacturer of the device.
* model - Device model.
* hostname - Hostname of the device
* fqdn - Fqdn of the device
* os_version - String with the OS version running on the device.
* serial_number - Serial number of the device
* interface_list - List of the interfaces of the device
CLI Example:
.. code-block:: bash
salt '*' net.facts
Example output:
.. code-block:: python
{
'os_version': '13.3R6.5',
'uptime': 10117140,
'interface_list': [
'lc-0/0/0',
'pfe-0/0/0',
'pfh-0/0/0',
'xe-0/0/0',
'xe-0/0/1',
'xe-0/0/2',
'xe-0/0/3',
'gr-0/0/10',
'ip-0/0/10'
],
'vendor': 'Juniper',
'serial_number': 'JN131356FBFA',
'model': 'MX480',
'hostname': 're0.edge05.syd01',
'fqdn': 're0.edge05.syd01'
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_facts',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def environment(**kwargs): # pylint: disable=unused-argument
'''
Returns the environment of the device.
CLI Example:
.. code-block:: bash
salt '*' net.environment
Example output:
.. code-block:: python
{
'fans': {
'Bottom Rear Fan': {
'status': True
},
'Bottom Middle Fan': {
'status': True
},
'Top Middle Fan': {
'status': True
},
'Bottom Front Fan': {
'status': True
},
'Top Front Fan': {
'status': True
},
'Top Rear Fan': {
'status': True
}
},
'memory': {
'available_ram': 16349,
'used_ram': 4934
},
'temperature': {
'FPC 0 Exhaust A': {
'is_alert': False,
'temperature': 35.0,
'is_critical': False
}
},
'cpu': {
'1': {
'%usage': 19.0
},
'0': {
'%usage': 35.0
}
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_environment',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def cli(*commands, **kwargs): # pylint: disable=unused-argument
'''
Returns a dictionary with the raw output of all commands passed as arguments.
commands
List of commands to be executed on the device.
textfsm_parse: ``False``
Try parsing the outputs using the TextFSM templates.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``napalm_cli_textfsm_parse``.
textfsm_path
The path where the TextFSM templates can be found. This option implies
the usage of the TextFSM index file.
``textfsm_path`` can be either absolute path on the server,
either specified using the following URL mschemes: ``file://``,
``salt://``, ``http://``, ``https://``, ``ftp://``,
``s3://``, ``swift://``.
.. versionadded:: 2018.3.0
.. note::
This needs to be a directory with a flat structure, having an
index file (whose name can be specified using the ``index_file`` option)
and a number of TextFSM templates.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_path``.
textfsm_template
The path to a certain the TextFSM template.
This can be specified using the absolute path
to the file, or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
.. versionadded:: 2018.3.0
textfsm_template_dict
A dictionary with the mapping between a command
and the corresponding TextFSM path to use to extract the data.
The TextFSM paths can be specified as in ``textfsm_template``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``napalm_cli_textfsm_template_dict``.
platform_grain_name: ``os``
The name of the grain used to identify the platform name
in the TextFSM index file. Default: ``os``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_grain``.
platform_column_name: ``Platform``
The column name used to identify the platform,
exactly as specified in the TextFSM index file.
Default: ``Platform``.
.. versionadded:: 2018.3.0
.. note::
This is field is case sensitive, make sure
to assign the correct value to this option,
exactly as defined in the index file.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_column_name``.
index_file: ``index``
The name of the TextFSM index file, under the ``textfsm_path``. Default: ``index``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_index_file``.
saltenv: ``base``
Salt fileserver envrionment from which to retrieve the file.
Ignored if ``textfsm_path`` is not a ``salt://`` URL.
.. versionadded:: 2018.3.0
include_empty: ``False``
Include empty files under the ``textfsm_path``.
.. versionadded:: 2018.3.0
include_pat
Glob or regex to narrow down the files cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. versionadded:: 2018.3.0
exclude_pat
Glob or regex to exclude certain files from being cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. versionadded:: 2018.3.0
.. note::
If used with ``include_pat``, files matching this pattern will be
excluded from the subset of files defined by ``include_pat``.
CLI Example:
.. code-block:: bash
salt '*' net.cli "show version" "show chassis fan"
CLI Example with TextFSM template:
.. code-block:: bash
salt '*' net.cli textfsm_parse=True textfsm_path=salt://textfsm/
Example output:
.. code-block:: python
{
'show version and haiku': 'Hostname: re0.edge01.arn01
Model: mx480
Junos: 13.3R6.5
Help me, Obi-Wan
I just saw Episode Two
You're my only hope
',
'show chassis fan' : 'Item Status RPM Measurement
Top Rear Fan OK 3840 Spinning at intermediate-speed
Bottom Rear Fan OK 3840 Spinning at intermediate-speed
Top Middle Fan OK 3900 Spinning at intermediate-speed
Bottom Middle Fan OK 3840 Spinning at intermediate-speed
Top Front Fan OK 3810 Spinning at intermediate-speed
Bottom Front Fan OK 3840 Spinning at intermediate-speed
'
}
Example output with TextFSM parsing:
.. code-block:: json
{
"comment": "",
"result": true,
"out": {
"sh ver": [
{
"kernel": "9.1S3.5",
"documentation": "9.1S3.5",
"boot": "9.1S3.5",
"crypto": "9.1S3.5",
"chassis": "",
"routing": "9.1S3.5",
"base": "9.1S3.5",
"model": "mx960"
}
]
}
}
'''
raw_cli_outputs = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'cli',
**{
'commands': list(commands)
}
)
# thus we can display the output as is
# in case of errors, they'll be catched in the proxy
if not raw_cli_outputs['result']:
# Error -> dispaly the output as-is.
return raw_cli_outputs
textfsm_parse = kwargs.get('textfsm_parse') or __opts__.get('napalm_cli_textfsm_parse') or\
__pillar__.get('napalm_cli_textfsm_parse', False)
if not textfsm_parse:
# No TextFSM parsing required, return raw commands.
log.debug('No TextFSM parsing requested.')
return raw_cli_outputs
if 'textfsm.extract' not in __salt__ or 'textfsm.index' not in __salt__:
raw_cli_outputs['comment'] += 'Unable to process: is TextFSM installed?'
log.error(raw_cli_outputs['comment'])
return raw_cli_outputs
textfsm_template = kwargs.get('textfsm_template')
log.debug('textfsm_template: %s', textfsm_template)
textfsm_path = kwargs.get('textfsm_path') or __opts__.get('textfsm_path') or\
__pillar__.get('textfsm_path')
log.debug('textfsm_path: %s', textfsm_path)
textfsm_template_dict = kwargs.get('textfsm_template_dict') or __opts__.get('napalm_cli_textfsm_template_dict') or\
__pillar__.get('napalm_cli_textfsm_template_dict', {})
log.debug('TextFSM command-template mapping: %s', textfsm_template_dict)
index_file = kwargs.get('index_file') or __opts__.get('textfsm_index_file') or\
__pillar__.get('textfsm_index_file')
log.debug('index_file: %s', index_file)
platform_grain_name = kwargs.get('platform_grain_name') or __opts__.get('textfsm_platform_grain') or\
__pillar__.get('textfsm_platform_grain', 'os')
log.debug('platform_grain_name: %s', platform_grain_name)
platform_column_name = kwargs.get('platform_column_name') or __opts__.get('textfsm_platform_column_name') or\
__pillar__.get('textfsm_platform_column_name', 'Platform')
log.debug('platform_column_name: %s', platform_column_name)
saltenv = kwargs.get('saltenv', 'base')
include_empty = kwargs.get('include_empty', False)
include_pat = kwargs.get('include_pat')
exclude_pat = kwargs.get('exclude_pat')
processed_cli_outputs = {
'comment': raw_cli_outputs.get('comment', ''),
'result': raw_cli_outputs['result'],
'out': {}
}
log.debug('Starting to analyse the raw outputs')
for command in list(commands):
command_output = raw_cli_outputs['out'][command]
log.debug('Output from command: %s', command)
log.debug(command_output)
processed_command_output = None
if textfsm_path:
log.debug('Using the templates under %s', textfsm_path)
processed_cli_output = __salt__['textfsm.index'](command,
platform_grain_name=platform_grain_name,
platform_column_name=platform_column_name,
output=command_output.strip(),
textfsm_path=textfsm_path,
saltenv=saltenv,
include_empty=include_empty,
include_pat=include_pat,
exclude_pat=exclude_pat)
log.debug('Processed CLI output:')
log.debug(processed_cli_output)
if not processed_cli_output['result']:
log.debug('Apparently this didnt work, returnin the raw output')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {0}: {1}.'.format(command,
processed_cli_output['comment'])
log.error(processed_cli_outputs['comment'])
elif processed_cli_output['out']:
log.debug('All good, %s has a nice output!', command)
processed_command_output = processed_cli_output['out']
else:
comment = '''\nProcessing "{}" didn't fail, but didn't return anything either. Dumping raw.'''.format(
command)
processed_cli_outputs['comment'] += comment
log.error(comment)
processed_command_output = command_output
elif textfsm_template or command in textfsm_template_dict:
if command in textfsm_template_dict:
textfsm_template = textfsm_template_dict[command]
log.debug('Using %s to process the command: %s', textfsm_template, command)
processed_cli_output = __salt__['textfsm.extract'](textfsm_template,
raw_text=command_output,
saltenv=saltenv)
log.debug('Processed CLI output:')
log.debug(processed_cli_output)
if not processed_cli_output['result']:
log.debug('Apparently this didnt work, returning '
'the raw output')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {0}: {1}'.format(command,
processed_cli_output['comment'])
log.error(processed_cli_outputs['comment'])
elif processed_cli_output['out']:
log.debug('All good, %s has a nice output!', command)
processed_command_output = processed_cli_output['out']
else:
log.debug('Processing %s didnt fail, but didnt return'
' anything either. Dumping raw.', command)
processed_command_output = command_output
else:
log.error('No TextFSM template specified, or no TextFSM path defined')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {}.'.format(command)
processed_cli_outputs['out'][command] = processed_command_output
processed_cli_outputs['comment'] = processed_cli_outputs['comment'].strip()
return processed_cli_outputs
@salt.utils.napalm.proxy_napalm_wrap
def traceroute(destination, source=None, ttl=None, timeout=None, vrf=None, **kwargs): # pylint: disable=unused-argument
'''
Calls the method traceroute from the NAPALM driver object and returns a dictionary with the result of the traceroute
command executed on the device.
destination
Hostname or address of remote host
source
Source address to use in outgoing traceroute packets
ttl
IP maximum time-to-live value (or IPv6 maximum hop-limit value)
timeout
Number of seconds to wait for response (seconds)
vrf
VRF (routing instance) for traceroute attempt
.. versionadded:: 2016.11.4
CLI Example:
.. code-block:: bash
salt '*' net.traceroute 8.8.8.8
salt '*' net.traceroute 8.8.8.8 source=127.0.0.1 ttl=5 timeout=1
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'traceroute',
**{
'destination': destination,
'source': source,
'ttl': ttl,
'timeout': timeout,
'vrf': vrf
}
)
@salt.utils.napalm.proxy_napalm_wrap
def ping(destination, source=None, ttl=None, timeout=None, size=None, count=None, vrf=None, **kwargs): # pylint: disable=unused-argument
'''
Executes a ping on the network device and returns a dictionary as a result.
destination
Hostname or IP address of remote host
source
Source address of echo request
ttl
IP time-to-live value (IPv6 hop-limit value) (1..255 hops)
timeout
Maximum wait time after sending final packet (seconds)
size
Size of request packets (0..65468 bytes)
count
Number of ping requests to send (1..2000000000 packets)
vrf
VRF (routing instance) for ping attempt
.. versionadded:: 2016.11.4
CLI Example:
.. code-block:: bash
salt '*' net.ping 8.8.8.8
salt '*' net.ping 8.8.8.8 ttl=3 size=65468
salt '*' net.ping 8.8.8.8 source=127.0.0.1 timeout=1 count=100
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'ping',
**{
'destination': destination,
'source': source,
'ttl': ttl,
'timeout': timeout,
'size': size,
'count': count,
'vrf': vrf
}
)
@salt.utils.napalm.proxy_napalm_wrap
def arp(interface='', ipaddr='', macaddr='', **kwargs): # pylint: disable=unused-argument
'''
NAPALM returns a list of dictionaries with details of the ARP entries.
:param interface: interface name to filter on
:param ipaddr: IP address to filter on
:param macaddr: MAC address to filter on
:return: List of the entries in the ARP table
CLI Example:
.. code-block:: bash
salt '*' net.arp
salt '*' net.arp macaddr='5c:5e:ab:da:3c:f0'
Example output:
.. code-block:: python
[
{
'interface' : 'MgmtEth0/RSP0/CPU0/0',
'mac' : '5c:5e:ab:da:3c:f0',
'ip' : '172.17.17.1',
'age' : 1454496274.84
},
{
'interface': 'MgmtEth0/RSP0/CPU0/0',
'mac' : '66:0e:94:96:e0:ff',
'ip' : '172.17.17.2',
'age' : 1435641582.49
}
]
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_arp_table',
**{
}
)
if not proxy_output.get('result'):
return proxy_output
arp_table = proxy_output.get('out')
if interface:
arp_table = _filter_list(arp_table, 'interface', interface)
if ipaddr:
arp_table = _filter_list(arp_table, 'ip', ipaddr)
if macaddr:
arp_table = _filter_list(arp_table, 'mac', macaddr)
proxy_output.update({
'out': arp_table
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def ipaddrs(**kwargs): # pylint: disable=unused-argument
'''
Returns IP addresses configured on the device.
:return: A dictionary with the IPv4 and IPv6 addresses of the interfaces.
Returns all configured IP addresses on all interfaces as a dictionary
of dictionaries. Keys of the main dictionary represent the name of the
interface. Values of the main dictionary represent are dictionaries
that may consist of two keys 'ipv4' and 'ipv6' (one, both or none)
which are themselvs dictionaries with the IP addresses as keys.
CLI Example:
.. code-block:: bash
salt '*' net.ipaddrs
Example output:
.. code-block:: python
{
'FastEthernet8': {
'ipv4': {
'10.66.43.169': {
'prefix_length': 22
}
}
},
'Loopback555': {
'ipv4': {
'192.168.1.1': {
'prefix_length': 24
}
},
'ipv6': {
'1::1': {
'prefix_length': 64
},
'2001:DB8:1::1': {
'prefix_length': 64
},
'FE80::3': {
'prefix_length': 'N/A'
}
}
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_interfaces_ip',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def interfaces(**kwargs): # pylint: disable=unused-argument
'''
Returns details of the interfaces on the device.
:return: Returns a dictionary of dictionaries. The keys for the first
dictionary will be the interfaces in the devices.
CLI Example:
.. code-block:: bash
salt '*' net.interfaces
Example output:
.. code-block:: python
{
'Management1': {
'is_up': False,
'is_enabled': False,
'description': '',
'last_flapped': -1,
'speed': 1000,
'mac_address': 'dead:beef:dead',
},
'Ethernet1':{
'is_up': True,
'is_enabled': True,
'description': 'foo',
'last_flapped': 1429978575.1554043,
'speed': 1000,
'mac_address': 'beef:dead:beef',
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_interfaces',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def lldp(interface='', **kwargs): # pylint: disable=unused-argument
'''
Returns a detailed view of the LLDP neighbors.
:param interface: interface name to filter on
:return: A dictionary with the LLDL neighbors. The keys are the
interfaces with LLDP activated on.
CLI Example:
.. code-block:: bash
salt '*' net.lldp
salt '*' net.lldp interface='TenGigE0/0/0/8'
Example output:
.. code-block:: python
{
'TenGigE0/0/0/8': [
{
'parent_interface': 'Bundle-Ether8',
'interface_description': 'TenGigE0/0/0/8',
'remote_chassis_id': '8c60.4f69.e96c',
'remote_system_name': 'switch',
'remote_port': 'Eth2/2/1',
'remote_port_description': 'Ethernet2/2/1',
'remote_system_description': 'Cisco Nexus Operating System (NX-OS) Software 7.1(0)N1(1a)
TAC support: http://www.cisco.com/tac
Copyright (c) 2002-2015, Cisco Systems, Inc. All rights reserved.',
'remote_system_capab': 'B, R',
'remote_system_enable_capab': 'B'
}
]
}
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_lldp_neighbors_detail',
**{
}
)
if not proxy_output.get('result'):
return proxy_output
lldp_neighbors = proxy_output.get('out')
if interface:
lldp_neighbors = {interface: lldp_neighbors.get(interface)}
proxy_output.update({
'out': lldp_neighbors
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def mac(address='', interface='', vlan=0, **kwargs): # pylint: disable=unused-argument
'''
Returns the MAC Address Table on the device.
:param address: MAC address to filter on
:param interface: Interface name to filter on
:param vlan: VLAN identifier
:return: A list of dictionaries representing the entries in the MAC Address Table
CLI Example:
.. code-block:: bash
salt '*' net.mac
salt '*' net.mac vlan=10
Example output:
.. code-block:: python
[
{
'mac' : '00:1c:58:29:4a:71',
'interface' : 'xe-3/0/2',
'static' : False,
'active' : True,
'moves' : 1,
'vlan' : 10,
'last_move' : 1454417742.58
},
{
'mac' : '8c:60:4f:58:e1:c1',
'interface' : 'xe-1/0/1',
'static' : False,
'active' : True,
'moves' : 2,
'vlan' : 42,
'last_move' : 1453191948.11
}
]
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_mac_address_table',
**{
}
)
if not proxy_output.get('result'):
# if negative, leave the output unchanged
return proxy_output
mac_address_table = proxy_output.get('out')
if vlan and isinstance(vlan, int):
mac_address_table = _filter_list(mac_address_table, 'vlan', vlan)
if address:
mac_address_table = _filter_list(mac_address_table, 'mac', address)
if interface:
mac_address_table = _filter_list(mac_address_table, 'interface', interface)
proxy_output.update({
'out': mac_address_table
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def config(source=None, **kwargs): # pylint: disable=unused-argument
'''
.. versionadded:: 2017.7.0
Return the whole configuration of the network device. By default, it will
return all possible configuration sources supported by the network device.
At most, there will be:
- running config
- startup config
- candidate config
To return only one of the configurations, you can use the ``source``
argument.
source
Which configuration type you want to display, default is all of them.
Options:
- running
- candidate
- startup
:return:
The object returned is a dictionary with the following keys:
- running (string): Representation of the native running configuration.
- candidate (string): Representation of the native candidate configuration.
If the device doesn't differentiate between running and startup
configuration this will an empty string.
- startup (string): Representation of the native startup configuration.
If the device doesn't differentiate between running and startup
configuration this will an empty string.
CLI Example:
.. code-block:: bash
salt '*' net.config
salt '*' net.config source=candidate
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_config',
**{
'retrieve': source
}
)
@salt.utils.napalm.proxy_napalm_wrap
def optics(**kwargs): # pylint: disable=unused-argument
'''
.. versionadded:: 2017.7.0
Fetches the power usage on the various transceivers installed
on the network device (in dBm), and returns a view that conforms with the
OpenConfig model openconfig-platform-transceiver.yang.
:return:
Returns a dictionary where the keys are as listed below:
* intf_name (unicode)
* physical_channels
* channels (list of dicts)
* index (int)
* state
* input_power
* instant (float)
* avg (float)
* min (float)
* max (float)
* output_power
* instant (float)
* avg (float)
* min (float)
* max (float)
* laser_bias_current
* instant (float)
* avg (float)
* min (float)
* max (float)
CLI Example:
.. code-block:: bash
salt '*' net.optics
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_optics',
**{
}
)
# <---- Call NAPALM getters --------------------------------------------------------------------------------------------
# ----- Configuration specific functions ------------------------------------------------------------------------------>
@salt.utils.napalm.proxy_napalm_wrap
def load_config(filename=None,
text=None,
test=False,
commit=True,
debug=False,
replace=False,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
commit_jid=None,
inherit_napalm_device=None,
saltenv='base',
**kwargs): # pylint: disable=unused-argument
'''
Applies configuration changes on the device. It can be loaded from a file or from inline string.
If you send both a filename and a string containing the configuration, the file has higher precedence.
By default this function will commit the changes. If there are no changes, it does not commit and
the flag ``already_configured`` will be set as ``True`` to point this out.
To avoid committing the configuration, set the argument ``test`` to ``True`` and will discard (dry run).
To keep the changes but not commit, set ``commit`` to ``False``.
To replace the config, set ``replace`` to ``True``.
filename
Path to the file containing the desired configuration.
This can be specified using the absolute path to the file,
or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
.. versionchanged:: 2018.3.0
text
String containing the desired configuration.
This argument is ignored when ``filename`` is specified.
test: False
Dry run? If set as ``True``, will apply the config, discard and return the changes. Default: ``False``
and will commit the changes on the device.
commit: True
Commit? Default: ``True``.
debug: False
Debug mode. Will insert a new key under the output dictionary, as ``loaded_config`` containing the raw
configuration loaded on the device.
.. versionadded:: 2016.11.2
replace: False
Load and replace the configuration. Default: ``False``.
.. versionadded:: 2016.11.2
commit_in: ``None``
Commit the changes in a specific number of minutes / hours. Example of
accepted formats: ``5`` (commit in 5 minutes), ``2m`` (commit in 2
minutes), ``1h`` (commit the changes in 1 hour)`, ``5h30m`` (commit
the changes in 5 hours and 30 minutes).
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
commit_at: ``None``
Commit the changes at a specific time. Example of accepted formats:
``1am`` (will commit the changes at the next 1AM), ``13:20`` (will
commit at 13:20), ``1:20am``, etc.
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
revert_in: ``None``
Commit and revert the changes in a specific number of minutes / hours.
Example of accepted formats: ``5`` (revert in 5 minutes), ``2m`` (revert
in 2 minutes), ``1h`` (revert the changes in 1 hour)`, ``5h30m`` (revert
the changes in 5 hours and 30 minutes).
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
revert_at: ``None``
Commit and revert the changes at a specific time. Example of accepted
formats: ``1am`` (will commit and revert the changes at the next 1AM),
``13:20`` (will commit and revert at 13:20), ``1:20am``, etc.
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
saltenv: ``base``
Specifies the Salt environment name.
.. versionadded:: 2018.3.0
:return: a dictionary having the following keys:
* result (bool): if the config was applied successfully. It is ``False`` only in case of failure. In case \
there are no changes to be applied and successfully performs all operations it is still ``True`` and so will be \
the ``already_configured`` flag (example below)
* comment (str): a message for the user
* already_configured (bool): flag to check if there were no changes applied
* loaded_config (str): the configuration loaded on the device. Requires ``debug`` to be set as ``True``
* diff (str): returns the config changes applied
CLI Example:
.. code-block:: bash
salt '*' net.load_config text='ntp peer 192.168.0.1'
salt '*' net.load_config filename='/absolute/path/to/your/file'
salt '*' net.load_config filename='/absolute/path/to/your/file' test=True
salt '*' net.load_config filename='/absolute/path/to/your/file' commit=False
Example output:
.. code-block:: python
{
'comment': 'Configuration discarded.',
'already_configured': False,
'result': True,
'diff': '[edit interfaces xe-0/0/5]+ description "Adding a description";'
}
'''
fun = 'load_merge_candidate'
if replace:
fun = 'load_replace_candidate'
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
if filename:
text = __salt__['cp.get_file_str'](filename, saltenv=saltenv)
if text is False:
# When using salt:// or https://, if the resource is not available,
# it will either raise an exception, or return False.
ret = {
'result': False,
'out': None
}
ret['comment'] = 'Unable to read from {}. Please specify a valid file or text.'.format(filename)
log.error(ret['comment'])
return ret
if commit_jid:
# When the commit_jid argument is passed, it probably is a scheduled
# commit to be executed, and filename is a temporary file which
# can be removed after reading it.
salt.utils.files.safe_rm(filename)
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
fun,
**{
'config': text
}
)
return _config_logic(napalm_device, # pylint: disable=undefined-variable
_loaded,
test=test,
debug=debug,
replace=replace,
commit_config=commit,
loaded_config=text,
commit_at=commit_at,
commit_in=commit_in,
revert_in=revert_in,
revert_at=revert_at,
commit_jid=commit_jid,
**kwargs)
@salt.utils.napalm.proxy_napalm_wrap
def load_template(template_name=None,
template_source=None,
context=None,
defaults=None,
template_engine='jinja',
saltenv='base',
template_hash=None,
template_hash_name=None,
skip_verify=False,
test=False,
commit=True,
debug=False,
replace=False,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
inherit_napalm_device=None, # pylint: disable=unused-argument
**template_vars):
'''
Renders a configuration template (default: Jinja) and loads the result on the device.
By default this function will commit the changes. If there are no changes,
it does not commit, discards he config and the flag ``already_configured``
will be set as ``True`` to point this out.
To avoid committing the configuration, set the argument ``test`` to ``True``
and will discard (dry run).
To preserve the changes, set ``commit`` to ``False``.
However, this is recommended to be used only in exceptional cases
when there are applied few consecutive states
and/or configuration changes.
Otherwise the user might forget that the config DB is locked
and the candidate config buffer is not cleared/merged in the running config.
To replace the config, set ``replace`` to ``True``.
template_name
Identifies path to the template source.
The template can be either stored on the local machine, either remotely.
The recommended location is under the ``file_roots``
as specified in the master config file.
For example, let's suppose the ``file_roots`` is configured as:
.. code-block:: yaml
file_roots:
base:
- /etc/salt/states
Placing the template under ``/etc/salt/states/templates/example.jinja``,
it can be used as ``salt://templates/example.jinja``.
Alternatively, for local files, the user can specify the absolute path.
If remotely, the source can be retrieved via ``http``, ``https`` or ``ftp``.
Examples:
- ``salt://my_template.jinja``
- ``/absolute/path/to/my_template.jinja``
- ``http://example.com/template.cheetah``
- ``https:/example.com/template.mako``
- ``ftp://example.com/template.py``
.. versionchanged:: 2019.2.0
This argument can now support a list of templates to be rendered.
The resulting configuration text is loaded at once, as a single
configuration chunk.
template_source: None
Inline config template to be rendered and loaded on the device.
template_hash: None
Hash of the template file. Format: ``{hash_type: 'md5', 'hsum': <md5sum>}``
.. versionadded:: 2016.11.2
context: None
Overrides default context variables passed to the template.
.. versionadded:: 2019.2.0
template_hash_name: None
When ``template_hash`` refers to a remote file,
this specifies the filename to look for in that file.
.. versionadded:: 2016.11.2
saltenv: ``base``
Specifies the template environment.
This will influence the relative imports inside the templates.
.. versionadded:: 2016.11.2
template_engine: jinja
The following templates engines are supported:
- :mod:`cheetah<salt.renderers.cheetah>`
- :mod:`genshi<salt.renderers.genshi>`
- :mod:`jinja<salt.renderers.jinja>`
- :mod:`mako<salt.renderers.mako>`
- :mod:`py<salt.renderers.py>`
- :mod:`wempy<salt.renderers.wempy>`
.. versionadded:: 2016.11.2
skip_verify: True
If ``True``, hash verification of remote file sources
(``http://``, ``https://``, ``ftp://``) will be skipped,
and the ``source_hash`` argument will be ignored.
.. versionadded:: 2016.11.2
test: False
Dry run? If set to ``True``, will apply the config,
discard and return the changes.
Default: ``False`` and will commit the changes on the device.
commit: True
Commit? (default: ``True``)
debug: False
Debug mode. Will insert a new key under the output dictionary,
as ``loaded_config`` containing the raw result after the template was rendered.
.. versionadded:: 2016.11.2
replace: False
Load and replace the configuration.
.. versionadded:: 2016.11.2
commit_in: ``None``
Commit the changes in a specific number of minutes / hours. Example of
accepted formats: ``5`` (commit in 5 minutes), ``2m`` (commit in 2
minutes), ``1h`` (commit the changes in 1 hour)`, ``5h30m`` (commit
the changes in 5 hours and 30 minutes).
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
commit_at: ``None``
Commit the changes at a specific time. Example of accepted formats:
``1am`` (will commit the changes at the next 1AM), ``13:20`` (will
commit at 13:20), ``1:20am``, etc.
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
revert_in: ``None``
Commit and revert the changes in a specific number of minutes / hours.
Example of accepted formats: ``5`` (revert in 5 minutes), ``2m`` (revert
in 2 minutes), ``1h`` (revert the changes in 1 hour)`, ``5h30m`` (revert
the changes in 5 hours and 30 minutes).
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
revert_at: ``None``
Commit and revert the changes at a specific time. Example of accepted
formats: ``1am`` (will commit and revert the changes at the next 1AM),
``13:20`` (will commit and revert at 13:20), ``1:20am``, etc.
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
defaults: None
Default variables/context passed to the template.
.. versionadded:: 2016.11.2
template_vars
Dictionary with the arguments/context to be used when the template is rendered.
.. note::
Do not explicitly specify this argument. This represents any other
variable that will be sent to the template rendering system.
Please see the examples below!
.. note::
It is more recommended to use the ``context`` argument to avoid
conflicts between CLI arguments and template variables.
:return: a dictionary having the following keys:
- result (bool): if the config was applied successfully. It is ``False``
only in case of failure. In case there are no changes to be applied and
successfully performs all operations it is still ``True`` and so will be
the ``already_configured`` flag (example below)
- comment (str): a message for the user
- already_configured (bool): flag to check if there were no changes applied
- loaded_config (str): the configuration loaded on the device, after
rendering the template. Requires ``debug`` to be set as ``True``
- diff (str): returns the config changes applied
The template can use variables from the ``grains``, ``pillar`` or ``opts``, for example:
.. code-block:: jinja
{% set router_model = grains.get('model') -%}
{% set router_vendor = grains.get('vendor') -%}
{% set os_version = grains.get('version') -%}
{% set hostname = pillar.get('proxy', {}).get('host') -%}
{% if router_vendor|lower == 'juniper' %}
system {
host-name {{hostname}};
}
{% elif router_vendor|lower == 'cisco' %}
hostname {{hostname}}
{% endif %}
CLI Examples:
.. code-block:: bash
salt '*' net.load_template set_ntp_peers peers=[192.168.0.1] # uses NAPALM default templates
# inline template:
salt -G 'os:junos' net.load_template template_source='system { host-name {{host_name}}; }' \
host_name='MX480.lab'
# inline template using grains info:
salt -G 'os:junos' net.load_template \
template_source='system { host-name {{grains.model}}.lab; }'
# if the device is a MX480, the command above will set the hostname as: MX480.lab
# inline template using pillar data:
salt -G 'os:junos' net.load_template template_source='system { host-name {{pillar.proxy.host}}; }'
salt '*' net.load_template https://bit.ly/2OhSgqP hostname=example # will commit
salt '*' net.load_template https://bit.ly/2OhSgqP hostname=example test=True # dry run
salt '*' net.load_template salt://templates/example.jinja debug=True # Using the salt:// URI
# render a mako template:
salt '*' net.load_template salt://templates/example.mako template_engine=mako debug=True
# render remote template
salt -G 'os:junos' net.load_template http://bit.ly/2fReJg7 test=True debug=True peers=['192.168.0.1']
salt -G 'os:ios' net.load_template http://bit.ly/2gKOj20 test=True debug=True peers=['192.168.0.1']
# render multiple templates at once
salt '*' net.load_template "['https://bit.ly/2OhSgqP', 'salt://templates/example.jinja']" context="{'hostname': 'example'}"
Example output:
.. code-block:: python
{
'comment': '',
'already_configured': False,
'result': True,
'diff': '[edit system]+ host-name edge01.bjm01',
'loaded_config': 'system { host-name edge01.bjm01; }''
}
'''
_rendered = ''
_loaded = {
'result': True,
'comment': '',
'out': None
}
loaded_config = None
# prechecks
deprecated_args = ('template_user', 'template_attrs', 'template_group', 'template_mode')
for deprecated_arg in deprecated_args:
if template_vars.get(deprecated_arg):
del template_vars[deprecated_arg]
salt.utils.versions.warn_until(
'Sodium',
('The \'{arg}\' argument to \'net.load_template\' is deprecated '
'and has been ignored').format(arg=deprecated_arg)
)
if template_engine not in salt.utils.templates.TEMPLATE_REGISTRY:
_loaded.update({
'result': False,
'comment': 'Invalid templating engine! Choose between: {tpl_eng_opts}'.format(
tpl_eng_opts=', '.join(list(salt.utils.templates.TEMPLATE_REGISTRY.keys()))
)
})
return _loaded # exit
# to check if will be rendered by salt or NAPALM
salt_render_prefixes = ('salt://', 'http://', 'https://', 'ftp://')
salt_render = False
file_exists = False
if not isinstance(template_name, (tuple, list)):
for salt_render_prefix in salt_render_prefixes:
if not salt_render:
salt_render = salt_render or template_name.startswith(salt_render_prefix)
file_exists = __salt__['file.file_exists'](template_name)
if template_source or file_exists or salt_render or isinstance(template_name, (tuple, list)):
# either inline template
# either template in a custom path
# either abs path send
# either starts with salt:// and
# then use Salt render system
if context is None:
context = {}
context.update(template_vars)
# if needed to render the template send as inline arg
if template_source:
# render the content
_rendered = __salt__['file.apply_template_on_contents'](
contents=template_source,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv
)
if not isinstance(_rendered, six.string_types):
if 'result' in _rendered:
_loaded['result'] = _rendered['result']
else:
_loaded['result'] = False
if 'comment' in _rendered:
_loaded['comment'] = _rendered['comment']
else:
_loaded['comment'] = 'Error while rendering the template.'
return _loaded
else:
# render the file - either local, either remote
if not isinstance(template_name, (list, tuple)):
template_name = [template_name]
if template_hash_name and not isinstance(template_hash_name, (list, tuple)):
template_hash_name = [template_hash_name]
elif not template_hash_name:
template_hash_name = [None] * len(template_name)
if template_hash and isinstance(template_hash, six.string_types) and not\
(template_hash.startswith('salt://') or template_hash.startswith('file://')):
# If the template hash is passed as string, and it's not a file
# (starts with the salt:// or file:// URI), then make it a list
# of 1 element (for the iteration below)
template_hash = [template_hash]
elif template_hash and isinstance(template_hash, six.string_types) and\
(template_hash.startswith('salt://') or template_hash.startswith('file://')):
# If the template hash is a file URI, then provide the same value
# for each of the templates in the list, as probably they all
# share the same hash file, otherwise the user should provide
# this as a list
template_hash = [template_hash] * len(template_name)
elif not template_hash:
template_hash = [None] * len(template_name)
for tpl_index, tpl_name in enumerate(template_name):
tpl_hash = template_hash[tpl_index]
tpl_hash_name = template_hash_name[tpl_index]
_rand_filename = __salt__['random.hash'](tpl_name, 'md5')
_temp_file = __salt__['file.join']('/tmp', _rand_filename)
_managed = __salt__['file.get_managed'](name=_temp_file,
source=tpl_name,
source_hash=tpl_hash,
source_hash_name=tpl_hash_name,
user=None,
group=None,
mode=None,
attrs=None,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv,
skip_verify=skip_verify)
if not isinstance(_managed, (list, tuple)) and isinstance(_managed, six.string_types):
_loaded['comment'] += _managed
_loaded['result'] = False
elif isinstance(_managed, (list, tuple)) and not _managed:
_loaded['result'] = False
_loaded['comment'] += 'Error while rendering the template.'
elif isinstance(_managed, (list, tuple)) and not _managed[0]:
_loaded['result'] = False
_loaded['comment'] += _managed[-1] # contains the error message
if _loaded['result']: # all good
_temp_tpl_file = _managed[0]
_temp_tpl_file_exists = __salt__['file.file_exists'](_temp_tpl_file)
if not _temp_tpl_file_exists:
_loaded['result'] = False
_loaded['comment'] += 'Error while rendering the template.'
return _loaded
_rendered += __salt__['file.read'](_temp_tpl_file)
__salt__['file.remove'](_temp_tpl_file)
else:
return _loaded # exit
loaded_config = _rendered
if _loaded['result']: # all good
fun = 'load_merge_candidate'
if replace: # replace requested
fun = 'load_replace_candidate'
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
fun,
**{
'config': _rendered
}
)
else:
salt.utils.versions.warn_until(
'Sodium',
'Native NAPALM templates support will be removed in the Sodium '
'release. Please consider using the Salt rendering pipeline instead.'
'If you are using the \'netntp\', \'netsnmp\', or \'netusers\' Salt '
'State modules, you can ignore this message'
)
# otherwise, use NAPALM render system, injecting pillar/grains/opts vars
load_templates_params = defaults if defaults else {}
load_templates_params.update(template_vars)
load_templates_params.update(
{
'template_name': template_name,
'template_source': template_source, # inline template
'pillar': __pillar__, # inject pillar content
'grains': __grains__, # inject grains content
'opts': __opts__ # inject opts content
}
)
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
# so we'll set the CLOSE global explicitly as False
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'load_template',
**load_templates_params
)
return _config_logic(napalm_device, # pylint: disable=undefined-variable
_loaded,
test=test,
debug=debug,
replace=replace,
commit_config=commit,
loaded_config=loaded_config,
commit_at=commit_at,
commit_in=commit_in,
revert_in=revert_in,
revert_at=revert_at,
**template_vars)
@salt.utils.napalm.proxy_napalm_wrap
def commit(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Commits the configuration changes made on the network device.
CLI Example:
.. code-block:: bash
salt '*' net.commit
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'commit_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def discard_config(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
"""
Discards the changes applied.
CLI Example:
.. code-block:: bash
salt '*' net.discard_config
"""
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'discard_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def compare_config(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Returns the difference between the running config and the candidate config.
CLI Example:
.. code-block:: bash
salt '*' net.compare_config
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'compare_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def rollback(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Rollbacks the configuration.
CLI Example:
.. code-block:: bash
salt '*' net.rollback
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'rollback',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def config_changed(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Will prompt if the configuration has been changed.
:return: A tuple with a boolean that specifies if the config was changed on the device.\
And a string that provides more details of the reason why the configuration was not changed.
CLI Example:
.. code-block:: bash
salt '*' net.config_changed
'''
is_config_changed = False
reason = ''
try_compare = compare_config(inherit_napalm_device=napalm_device) # pylint: disable=undefined-variable
if try_compare.get('result'):
if try_compare.get('out'):
is_config_changed = True
else:
reason = 'Configuration was not changed on the device.'
else:
reason = try_compare.get('comment')
return is_config_changed, reason
@salt.utils.napalm.proxy_napalm_wrap
def config_control(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Will check if the configuration was changed.
If differences found, will try to commit.
In case commit unsuccessful, will try to rollback.
:return: A tuple with a boolean that specifies if the config was changed/committed/rollbacked on the device.\
And a string that provides more details of the reason why the configuration was not committed properly.
CLI Example:
.. code-block:: bash
salt '*' net.config_control
'''
result = True
comment = ''
changed, not_changed_rsn = config_changed(inherit_napalm_device=napalm_device) # pylint: disable=undefined-variable
if not changed:
return (changed, not_changed_rsn)
# config changed, thus let's try to commit
try_commit = commit()
if not try_commit.get('result'):
result = False
comment = 'Unable to commit the changes: {reason}.\n\
Will try to rollback now!'.format(
reason=try_commit.get('comment')
)
try_rollback = rollback()
if not try_rollback.get('result'):
comment += '\nCannot rollback! {reason}'.format(
reason=try_rollback.get('comment')
)
return result, comment
def cancel_commit(jid):
'''
.. versionadded:: 2019.2.0
Cancel a commit scheduled to be executed via the ``commit_in`` and
``commit_at`` arguments from the
:py:func:`net.load_template <salt.modules.napalm_network.load_template>` or
:py:func:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit ID is displayed when the commit is scheduled
via the functions named above.
CLI Example:
.. code-block:: bash
salt '*' net.cancel_commit 20180726083540640360
'''
job_name = '__napalm_commit_{}'.format(jid)
removed = __salt__['schedule.delete'](job_name)
if removed['result']:
saved = __salt__['schedule.save']()
removed['comment'] = 'Commit #{jid} cancelled.'.format(jid=jid)
else:
removed['comment'] = 'Unable to find commit #{jid}.'.format(jid=jid)
return removed
def confirm_commit(jid):
'''
.. versionadded:: 2019.2.0
Confirm a commit scheduled to be reverted via the ``revert_in`` and
``revert_at`` arguments from the
:mod:`net.load_template <salt.modules.napalm_network.load_template>` or
:mod:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit ID is displayed when the commit confirmed
is scheduled via the functions named above.
CLI Example:
.. code-block:: bash
salt '*' net.confirm_commit 20180726083540640360
'''
if __grains__['os'] == 'junos':
# Confirm the commit, by committing (i.e., invoking the RPC call)
confirmed = __salt__['napalm.junos_commit']()
confirmed['result'] = confirmed.pop('out')
confirmed['comment'] = confirmed.pop('message')
else:
confirmed = cancel_commit(jid)
if confirmed['result']:
confirmed['comment'] = 'Commit #{jid} confirmed.'.format(jid=jid)
return confirmed
def replace_pattern(pattern,
repl,
count=0,
flags=8,
bufsize=1,
append_if_not_found=False,
prepend_if_not_found=False,
not_found_content=None,
search_only=False,
show_changes=True,
backslash_literal=False,
source=None,
path=None,
test=False,
replace=True,
debug=False,
commit=True):
'''
.. versionadded:: 2019.2.0
Replace occurrences of a pattern in the configuration source. If
``show_changes`` is ``True``, then a diff of what changed will be returned,
otherwise a ``True`` will be returned when changes are made, and ``False``
when no changes are made.
This is a pure Python implementation that wraps Python's :py:func:`~re.sub`.
pattern
A regular expression, to be matched using Python's
:py:func:`~re.search`.
repl
The replacement text.
count: ``0``
Maximum number of pattern occurrences to be replaced. If count is a
positive integer ``n``, only ``n`` occurrences will be replaced,
otherwise all occurrences will be replaced.
flags (list or int): ``8``
A list of flags defined in the ``re`` module documentation from the
Python standard library. Each list item should be a string that will
correlate to the human-friendly flag name. E.g., ``['IGNORECASE',
'MULTILINE']``. Optionally, ``flags`` may be an int, with a value
corresponding to the XOR (``|``) of all the desired flags. Defaults to
8 (which supports 'MULTILINE').
bufsize (int or str): ``1``
How much of the configuration to buffer into memory at once. The
default value ``1`` processes one line at a time. The special value
``file`` may be specified which will read the entire file into memory
before processing.
append_if_not_found: ``False``
If set to ``True``, and pattern is not found, then the content will be
appended to the file.
prepend_if_not_found: ``False``
If set to ``True`` and pattern is not found, then the content will be
prepended to the file.
not_found_content
Content to use for append/prepend if not found. If None (default), uses
``repl``. Useful when ``repl`` uses references to group in pattern.
search_only: ``False``
If set to true, this no changes will be performed on the file, and this
function will simply return ``True`` if the pattern was matched, and
``False`` if not.
show_changes: ``True``
If ``True``, return a diff of changes made. Otherwise, return ``True``
if changes were made, and ``False`` if not.
backslash_literal: ``False``
Interpret backslashes as literal backslashes for the repl and not
escape characters. This will help when using append/prepend so that
the backslashes are not interpreted for the repl on the second run of
the state.
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path
Save the temporary configuration to a specific path, then read from
there.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' net.replace_pattern "bind-address\\s*=" "bind-address:"
CLI Example:
.. code-block:: bash
salt '*' net.replace_pattern PREFIX-LIST_NAME new-prefix-list-name
salt '*' net.replace_pattern bgp-group-name new-bgp-group-name count=1
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
replace_pattern = __salt__['file.replace'](path,
pattern,
repl,
count=count,
flags=flags,
bufsize=bufsize,
append_if_not_found=append_if_not_found,
prepend_if_not_found=prepend_if_not_found,
not_found_content=not_found_content,
search_only=search_only,
show_changes=show_changes,
backslash_literal=backslash_literal)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
def blockreplace(marker_start,
marker_end,
content='',
append_if_not_found=False,
prepend_if_not_found=False,
show_changes=True,
append_newline=False,
source='running',
path=None,
test=False,
commit=True,
debug=False,
replace=True):
'''
.. versionadded:: 2019.2.0
Replace content of the configuration source, delimited by the line markers.
A block of content delimited by comments can help you manage several lines
without worrying about old entries removal.
marker_start
The line content identifying a line as the start of the content block.
Note that the whole line containing this marker will be considered,
so whitespace or extra content before or after the marker is included
in final output.
marker_end
The line content identifying a line as the end of the content block.
Note that the whole line containing this marker will be considered,
so whitespace or extra content before or after the marker is included
in final output.
content
The content to be used between the two lines identified by
``marker_start`` and ``marker_stop``.
append_if_not_found: ``False``
If markers are not found and set to True then, the markers and content
will be appended to the file.
prepend_if_not_found: ``False``
If markers are not found and set to True then, the markers and content
will be prepended to the file.
append_newline: ``False``
Controls whether or not a newline is appended to the content block.
If the value of this argument is ``True`` then a newline will be added
to the content block. If it is ``False``, then a newline will not be
added to the content block. If it is ``None`` then a newline will only
be added to the content block if it does not already end in a newline.
show_changes: ``True``
Controls how changes are presented. If ``True``, this function will
return the of the changes made.
If ``False``, then it will return a boolean (``True`` if any changes
were made, otherwise False).
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path: ``None``
Save the temporary configuration to a specific path, then read from
there. This argument is optional, can be used when you prefers a
particular location of the temporary file.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
CLI Example:
.. code-block:: bash
salt '*' net.blockreplace 'ntp' 'interface' ''
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
replace_pattern = __salt__['file.blockreplace'](path,
marker_start=marker_start,
marker_end=marker_end,
content=content,
append_if_not_found=append_if_not_found,
prepend_if_not_found=prepend_if_not_found,
show_changes=show_changes,
append_newline=append_newline)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
def patch(patchfile,
options='',
saltenv='base',
source_hash=None,
show_changes=True,
source='running',
path=None,
test=False,
commit=True,
debug=False,
replace=True):
'''
.. versionadded:: 2019.2.0
Apply a patch to the configuration source, and load the result into the
running config of the device.
patchfile
A patch file to apply to the configuration source.
options
Options to pass to patch.
source_hash
If the patch file (specified via the ``patchfile`` argument) is an
HTTP(S) or FTP URL and the file exists in the minion's file cache, this
option can be passed to keep the minion from re-downloading the file if
the cached copy matches the specified hash.
show_changes: ``True``
Controls how changes are presented. If ``True``, this function will
return the of the changes made.
If ``False``, then it will return a boolean (``True`` if any changes
were made, otherwise False).
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path: ``None``
Save the temporary configuration to a specific path, then read from
there. This argument is optional, can the user prefers a particular
location of the temporary file.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
CLI Example:
.. code-block:: bash
salt '*' net.patch https://example.com/running_config.patch
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
patchfile_cache = __salt__['cp.cache_file'](patchfile)
if patchfile_cache is False:
return {
'out': None,
'result': False,
'comment': 'The file "{}" does not exist.'.format(patchfile)
}
replace_pattern = __salt__['file.patch'](path,
patchfile_cache,
options=options)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
# <---- Configuration specific functions -------------------------------------------------------------------------------
|
saltstack/salt
|
salt/modules/napalm_network.py
|
replace_pattern
|
python
|
def replace_pattern(pattern,
repl,
count=0,
flags=8,
bufsize=1,
append_if_not_found=False,
prepend_if_not_found=False,
not_found_content=None,
search_only=False,
show_changes=True,
backslash_literal=False,
source=None,
path=None,
test=False,
replace=True,
debug=False,
commit=True):
'''
.. versionadded:: 2019.2.0
Replace occurrences of a pattern in the configuration source. If
``show_changes`` is ``True``, then a diff of what changed will be returned,
otherwise a ``True`` will be returned when changes are made, and ``False``
when no changes are made.
This is a pure Python implementation that wraps Python's :py:func:`~re.sub`.
pattern
A regular expression, to be matched using Python's
:py:func:`~re.search`.
repl
The replacement text.
count: ``0``
Maximum number of pattern occurrences to be replaced. If count is a
positive integer ``n``, only ``n`` occurrences will be replaced,
otherwise all occurrences will be replaced.
flags (list or int): ``8``
A list of flags defined in the ``re`` module documentation from the
Python standard library. Each list item should be a string that will
correlate to the human-friendly flag name. E.g., ``['IGNORECASE',
'MULTILINE']``. Optionally, ``flags`` may be an int, with a value
corresponding to the XOR (``|``) of all the desired flags. Defaults to
8 (which supports 'MULTILINE').
bufsize (int or str): ``1``
How much of the configuration to buffer into memory at once. The
default value ``1`` processes one line at a time. The special value
``file`` may be specified which will read the entire file into memory
before processing.
append_if_not_found: ``False``
If set to ``True``, and pattern is not found, then the content will be
appended to the file.
prepend_if_not_found: ``False``
If set to ``True`` and pattern is not found, then the content will be
prepended to the file.
not_found_content
Content to use for append/prepend if not found. If None (default), uses
``repl``. Useful when ``repl`` uses references to group in pattern.
search_only: ``False``
If set to true, this no changes will be performed on the file, and this
function will simply return ``True`` if the pattern was matched, and
``False`` if not.
show_changes: ``True``
If ``True``, return a diff of changes made. Otherwise, return ``True``
if changes were made, and ``False`` if not.
backslash_literal: ``False``
Interpret backslashes as literal backslashes for the repl and not
escape characters. This will help when using append/prepend so that
the backslashes are not interpreted for the repl on the second run of
the state.
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path
Save the temporary configuration to a specific path, then read from
there.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' net.replace_pattern "bind-address\\s*=" "bind-address:"
CLI Example:
.. code-block:: bash
salt '*' net.replace_pattern PREFIX-LIST_NAME new-prefix-list-name
salt '*' net.replace_pattern bgp-group-name new-bgp-group-name count=1
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
replace_pattern = __salt__['file.replace'](path,
pattern,
repl,
count=count,
flags=flags,
bufsize=bufsize,
append_if_not_found=append_if_not_found,
prepend_if_not_found=prepend_if_not_found,
not_found_content=not_found_content,
search_only=search_only,
show_changes=show_changes,
backslash_literal=backslash_literal)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
|
.. versionadded:: 2019.2.0
Replace occurrences of a pattern in the configuration source. If
``show_changes`` is ``True``, then a diff of what changed will be returned,
otherwise a ``True`` will be returned when changes are made, and ``False``
when no changes are made.
This is a pure Python implementation that wraps Python's :py:func:`~re.sub`.
pattern
A regular expression, to be matched using Python's
:py:func:`~re.search`.
repl
The replacement text.
count: ``0``
Maximum number of pattern occurrences to be replaced. If count is a
positive integer ``n``, only ``n`` occurrences will be replaced,
otherwise all occurrences will be replaced.
flags (list or int): ``8``
A list of flags defined in the ``re`` module documentation from the
Python standard library. Each list item should be a string that will
correlate to the human-friendly flag name. E.g., ``['IGNORECASE',
'MULTILINE']``. Optionally, ``flags`` may be an int, with a value
corresponding to the XOR (``|``) of all the desired flags. Defaults to
8 (which supports 'MULTILINE').
bufsize (int or str): ``1``
How much of the configuration to buffer into memory at once. The
default value ``1`` processes one line at a time. The special value
``file`` may be specified which will read the entire file into memory
before processing.
append_if_not_found: ``False``
If set to ``True``, and pattern is not found, then the content will be
appended to the file.
prepend_if_not_found: ``False``
If set to ``True`` and pattern is not found, then the content will be
prepended to the file.
not_found_content
Content to use for append/prepend if not found. If None (default), uses
``repl``. Useful when ``repl`` uses references to group in pattern.
search_only: ``False``
If set to true, this no changes will be performed on the file, and this
function will simply return ``True`` if the pattern was matched, and
``False`` if not.
show_changes: ``True``
If ``True``, return a diff of changes made. Otherwise, return ``True``
if changes were made, and ``False`` if not.
backslash_literal: ``False``
Interpret backslashes as literal backslashes for the repl and not
escape characters. This will help when using append/prepend so that
the backslashes are not interpreted for the repl on the second run of
the state.
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path
Save the temporary configuration to a specific path, then read from
there.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' net.replace_pattern "bind-address\\s*=" "bind-address:"
CLI Example:
.. code-block:: bash
salt '*' net.replace_pattern PREFIX-LIST_NAME new-prefix-list-name
salt '*' net.replace_pattern bgp-group-name new-bgp-group-name count=1
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_network.py#L2333-L2473
|
[
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n",
"def save_config(source=None,\n path=None):\n '''\n .. versionadded:: 2019.2.0\n\n Save the configuration to a file on the local file system.\n\n source: ``running``\n The configuration source. Choose from: ``running``, ``candidate``,\n ``startup``. Default: ``running``.\n\n path\n Absolute path to file where to save the configuration.\n To push the files to the Master, use\n :mod:`cp.push <salt.modules.cp.push>` Execution function.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' net.save_config source=running\n '''\n if not source:\n source = 'running'\n if not path:\n path = salt.utils.files.mkstemp()\n running_config = __salt__['net.config'](source=source)\n if not running_config or not running_config['result']:\n log.error('Unable to retrieve the config')\n return running_config\n with salt.utils.files.fopen(path, 'w') as fh_:\n fh_.write(running_config['out'][source])\n return {\n 'result': True,\n 'out': path,\n 'comment': '{source} config saved to {path}'.format(source=source, path=path)\n }\n"
] |
# -*- coding: utf-8 -*-
'''
NAPALM Network
==============
Basic methods for interaction with the network device through the virtual proxy 'napalm'.
:codeauthor: Mircea Ulinic <mircea@cloudflare.com> & Jerome Fleury <jf@cloudflare.com>
:maturity: new
:depends: napalm
:platform: unix
Dependencies
------------
- :mod:`napalm proxy minion <salt.proxy.napalm>`
.. versionadded:: 2016.11.0
.. versionchanged:: 2017.7.0
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import time
import logging
import datetime
log = logging.getLogger(__name__)
# Import Salt libs
from salt.ext import six
import salt.utils.files
import salt.utils.napalm
import salt.utils.versions
import salt.utils.templates
# Import 3rd-party libs
try:
import jxmlease # pylint: disable=unused-import
HAS_JXMLEASE = True
except ImportError:
HAS_JXMLEASE = False
# ----------------------------------------------------------------------------------------------------------------------
# module properties
# ----------------------------------------------------------------------------------------------------------------------
__virtualname__ = 'net'
__proxyenabled__ = ['*']
__virtual_aliases__ = ('napalm_net',)
# uses NAPALM-based proxy to interact with network devices
# ----------------------------------------------------------------------------------------------------------------------
# property functions
# ----------------------------------------------------------------------------------------------------------------------
def __virtual__():
'''
NAPALM library must be installed for this module to work and run in a (proxy) minion.
'''
return salt.utils.napalm.virtual(__opts__, __virtualname__, __file__)
# ----------------------------------------------------------------------------------------------------------------------
# helper functions -- will not be exported
# ----------------------------------------------------------------------------------------------------------------------
def _filter_list(input_list, search_key, search_value):
'''
Filters a list of dictionary by a set of key-value pair.
:param input_list: is a list of dictionaries
:param search_key: is the key we are looking for
:param search_value: is the value we are looking for the key specified in search_key
:return: filered list of dictionaries
'''
output_list = list()
for dictionary in input_list:
if dictionary.get(search_key) == search_value:
output_list.append(dictionary)
return output_list
def _filter_dict(input_dict, search_key, search_value):
'''
Filters a dictionary of dictionaries by a key-value pair.
:param input_dict: is a dictionary whose values are lists of dictionaries
:param search_key: is the key in the leaf dictionaries
:param search_values: is the value in the leaf dictionaries
:return: filtered dictionary
'''
output_dict = dict()
for key, key_list in six.iteritems(input_dict):
key_list_filtered = _filter_list(key_list, search_key, search_value)
if key_list_filtered:
output_dict[key] = key_list_filtered
return output_dict
def _safe_commit_config(loaded_result, napalm_device):
_commit = commit(inherit_napalm_device=napalm_device) # calls the function commit, defined below
if not _commit.get('result', False):
# if unable to commit
loaded_result['comment'] += _commit['comment'] if _commit.get('comment') else 'Unable to commit.'
loaded_result['result'] = False
# unable to commit, something went wrong
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
return _commit
def _safe_dicard_config(loaded_result, napalm_device):
'''
'''
log.debug('Discarding the config')
log.debug(loaded_result)
_discarded = discard_config(inherit_napalm_device=napalm_device)
if not _discarded.get('result', False):
loaded_result['comment'] += _discarded['comment'] if _discarded.get('comment') \
else 'Unable to discard config.'
loaded_result['result'] = False
# make sure it notifies
# that something went wrong
_explicit_close(napalm_device)
__context__['retcode'] = 1
return loaded_result
return _discarded
def _explicit_close(napalm_device):
'''
Will explicily close the config session with the network device,
when running in a now-always-alive proxy minion or regular minion.
This helper must be used in configuration-related functions,
as the session is preserved and not closed before making any changes.
'''
if salt.utils.napalm.not_always_alive(__opts__):
# force closing the configuration session
# when running in a non-always-alive proxy
# or regular minion
try:
napalm_device['DRIVER'].close()
except Exception as err:
log.error('Unable to close the temp connection with the device:')
log.error(err)
log.error('Please report.')
def _config_logic(napalm_device,
loaded_result,
test=False,
debug=False,
replace=False,
commit_config=True,
loaded_config=None,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
commit_jid=None,
**kwargs):
'''
Builds the config logic for `load_config` and `load_template` functions.
'''
# As the Salt logic is built around independent events
# when it comes to configuration changes in the
# candidate DB on the network devices, we need to
# make sure we're using the same session.
# Hence, we need to pass the same object around.
# the napalm_device object is inherited from
# the load_config or load_template functions
# and forwarded to compare, discard, commit etc.
# then the decorator will make sure that
# if not proxy (when the connection is always alive)
# and the `inherit_napalm_device` is set,
# `napalm_device` will be overridden.
# See `salt.utils.napalm.proxy_napalm_wrap` decorator.
current_jid = kwargs.get('__pub_jid')
if not current_jid:
current_jid = '{0:%Y%m%d%H%M%S%f}'.format(datetime.datetime.now())
loaded_result['already_configured'] = False
loaded_result['loaded_config'] = ''
if debug:
loaded_result['loaded_config'] = loaded_config
_compare = compare_config(inherit_napalm_device=napalm_device)
if _compare.get('result', False):
loaded_result['diff'] = _compare.get('out')
loaded_result.pop('out', '') # not needed
else:
loaded_result['diff'] = None
loaded_result['result'] = False
loaded_result['comment'] = _compare.get('comment')
__context__['retcode'] = 1
return loaded_result
_loaded_res = loaded_result.get('result', False)
if not _loaded_res or test:
# if unable to load the config (errors / warnings)
# or in testing mode,
# will discard the config
if loaded_result['comment']:
loaded_result['comment'] += '\n'
if not loaded_result.get('diff', ''):
loaded_result['already_configured'] = True
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
loaded_result['comment'] += 'Configuration discarded.'
# loaded_result['result'] = False not necessary
# as the result can be true when test=True
_explicit_close(napalm_device)
if not loaded_result['result']:
__context__['retcode'] = 1
return loaded_result
if not test and commit_config:
# if not in testing mode and trying to commit
if commit_jid:
log.info('Committing the JID: %s', str(commit_jid))
removed = cancel_commit(commit_jid)
log.debug('Cleaned up the commit from the schedule')
log.debug(removed['comment'])
if loaded_result.get('diff', ''):
# if not testing mode
# and also the user wants to commit (default)
# and there are changes to commit
if commit_in or commit_at:
commit_time = __utils__['timeutil.get_time_at'](time_in=commit_in,
time_at=commit_in)
# schedule job
scheduled_job_name = '__napalm_commit_{}'.format(current_jid)
temp_file = salt.utils.files.mkstemp()
with salt.utils.files.fopen(temp_file, 'w') as fp_:
fp_.write(loaded_config)
scheduled = __salt__['schedule.add'](scheduled_job_name,
function='net.load_config',
job_kwargs={
'filename': temp_file,
'commit_jid': current_jid,
'replace': replace
},
once=commit_time)
log.debug('Scheduling job')
log.debug(scheduled)
saved = __salt__['schedule.save']() # ensure the schedule is
# persistent cross Minion restart
discarded = _safe_dicard_config(loaded_result, napalm_device)
# discard the changes
if not discarded['result']:
discarded['comment'] += ('Scheduled the job to be executed at {schedule_ts}, '
'but was unable to discard the config: \n').format(schedule_ts=commit_time)
return discarded
loaded_result['comment'] = ('Changes discarded for now, and scheduled commit at: {schedule_ts}.\n'
'The commit ID is: {current_jid}.\n'
'To discard this commit, you can execute: \n\n'
'salt {min_id} net.cancel_commit {current_jid}').format(schedule_ts=commit_time,
min_id=__opts__['id'],
current_jid=current_jid)
loaded_result['commit_id'] = current_jid
return loaded_result
log.debug('About to commit:')
log.debug(loaded_result['diff'])
if revert_in or revert_at:
revert_time = __utils__['timeutil.get_time_at'](time_in=revert_in,
time_at=revert_at)
if __grains__['os'] == 'junos':
if not HAS_JXMLEASE:
loaded_result['comment'] = ('This feature requires the library jxmlease to be installed.\n'
'To install, please execute: ``pip install jxmlease``.')
loaded_result['result'] = False
return loaded_result
timestamp_at = __utils__['timeutil.get_timestamp_at'](time_in=revert_in,
time_at=revert_at)
minutes = int((timestamp_at - time.time())/60)
_comm = __salt__['napalm.junos_commit'](confirm=minutes)
if not _comm['out']:
# If unable to commit confirm, should try to bail out
loaded_result['comment'] = 'Unable to commit confirm: {}'.format(_comm['message'])
loaded_result['result'] = False
# But before exiting, we must gracefully discard the config
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
else:
temp_file = salt.utils.files.mkstemp()
running_config = __salt__['net.config'](source='running')['out']['running']
with salt.utils.files.fopen(temp_file, 'w') as fp_:
fp_.write(running_config)
committed = _safe_commit_config(loaded_result, napalm_device)
if not committed['result']:
# If unable to commit, dicard the config (which is
# already done by the _safe_commit_config function), and
# return with the command and other details.
return loaded_result
scheduled_job_name = '__napalm_commit_{}'.format(current_jid)
scheduled = __salt__['schedule.add'](scheduled_job_name,
function='net.load_config',
job_kwargs={
'filename': temp_file,
'commit_jid': current_jid,
'replace': True
},
once=revert_time)
log.debug('Scheduling commit confirmed')
log.debug(scheduled)
saved = __salt__['schedule.save']()
loaded_result['comment'] = ('The commit ID is: {current_jid}.\n'
'This commit will be reverted at: {schedule_ts}, unless confirmed.\n'
'To confirm the commit and avoid reverting, you can execute:\n\n'
'salt {min_id} net.confirm_commit {current_jid}').format(schedule_ts=revert_time,
min_id=__opts__['id'],
current_jid=current_jid)
loaded_result['commit_id'] = current_jid
return loaded_result
committed = _safe_commit_config(loaded_result, napalm_device)
if not committed['result']:
return loaded_result
else:
# would like to commit, but there's no change
# need to call discard_config() to release the config DB
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
loaded_result['already_configured'] = True
loaded_result['comment'] = 'Already configured.'
_explicit_close(napalm_device)
if not loaded_result['result']:
__context__['retcode'] = 1
return loaded_result
# ----------------------------------------------------------------------------------------------------------------------
# callable functions
# ----------------------------------------------------------------------------------------------------------------------
@salt.utils.napalm.proxy_napalm_wrap
def connected(**kwargs): # pylint: disable=unused-argument
'''
Specifies if the connection to the device succeeded.
CLI Example:
.. code-block:: bash
salt '*' net.connected
'''
return {
'out': napalm_device.get('UP', False) # pylint: disable=undefined-variable
}
@salt.utils.napalm.proxy_napalm_wrap
def facts(**kwargs): # pylint: disable=unused-argument
'''
Returns characteristics of the network device.
:return: a dictionary with the following keys:
* uptime - Uptime of the device in seconds.
* vendor - Manufacturer of the device.
* model - Device model.
* hostname - Hostname of the device
* fqdn - Fqdn of the device
* os_version - String with the OS version running on the device.
* serial_number - Serial number of the device
* interface_list - List of the interfaces of the device
CLI Example:
.. code-block:: bash
salt '*' net.facts
Example output:
.. code-block:: python
{
'os_version': '13.3R6.5',
'uptime': 10117140,
'interface_list': [
'lc-0/0/0',
'pfe-0/0/0',
'pfh-0/0/0',
'xe-0/0/0',
'xe-0/0/1',
'xe-0/0/2',
'xe-0/0/3',
'gr-0/0/10',
'ip-0/0/10'
],
'vendor': 'Juniper',
'serial_number': 'JN131356FBFA',
'model': 'MX480',
'hostname': 're0.edge05.syd01',
'fqdn': 're0.edge05.syd01'
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_facts',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def environment(**kwargs): # pylint: disable=unused-argument
'''
Returns the environment of the device.
CLI Example:
.. code-block:: bash
salt '*' net.environment
Example output:
.. code-block:: python
{
'fans': {
'Bottom Rear Fan': {
'status': True
},
'Bottom Middle Fan': {
'status': True
},
'Top Middle Fan': {
'status': True
},
'Bottom Front Fan': {
'status': True
},
'Top Front Fan': {
'status': True
},
'Top Rear Fan': {
'status': True
}
},
'memory': {
'available_ram': 16349,
'used_ram': 4934
},
'temperature': {
'FPC 0 Exhaust A': {
'is_alert': False,
'temperature': 35.0,
'is_critical': False
}
},
'cpu': {
'1': {
'%usage': 19.0
},
'0': {
'%usage': 35.0
}
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_environment',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def cli(*commands, **kwargs): # pylint: disable=unused-argument
'''
Returns a dictionary with the raw output of all commands passed as arguments.
commands
List of commands to be executed on the device.
textfsm_parse: ``False``
Try parsing the outputs using the TextFSM templates.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``napalm_cli_textfsm_parse``.
textfsm_path
The path where the TextFSM templates can be found. This option implies
the usage of the TextFSM index file.
``textfsm_path`` can be either absolute path on the server,
either specified using the following URL mschemes: ``file://``,
``salt://``, ``http://``, ``https://``, ``ftp://``,
``s3://``, ``swift://``.
.. versionadded:: 2018.3.0
.. note::
This needs to be a directory with a flat structure, having an
index file (whose name can be specified using the ``index_file`` option)
and a number of TextFSM templates.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_path``.
textfsm_template
The path to a certain the TextFSM template.
This can be specified using the absolute path
to the file, or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
.. versionadded:: 2018.3.0
textfsm_template_dict
A dictionary with the mapping between a command
and the corresponding TextFSM path to use to extract the data.
The TextFSM paths can be specified as in ``textfsm_template``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``napalm_cli_textfsm_template_dict``.
platform_grain_name: ``os``
The name of the grain used to identify the platform name
in the TextFSM index file. Default: ``os``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_grain``.
platform_column_name: ``Platform``
The column name used to identify the platform,
exactly as specified in the TextFSM index file.
Default: ``Platform``.
.. versionadded:: 2018.3.0
.. note::
This is field is case sensitive, make sure
to assign the correct value to this option,
exactly as defined in the index file.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_column_name``.
index_file: ``index``
The name of the TextFSM index file, under the ``textfsm_path``. Default: ``index``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_index_file``.
saltenv: ``base``
Salt fileserver envrionment from which to retrieve the file.
Ignored if ``textfsm_path`` is not a ``salt://`` URL.
.. versionadded:: 2018.3.0
include_empty: ``False``
Include empty files under the ``textfsm_path``.
.. versionadded:: 2018.3.0
include_pat
Glob or regex to narrow down the files cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. versionadded:: 2018.3.0
exclude_pat
Glob or regex to exclude certain files from being cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. versionadded:: 2018.3.0
.. note::
If used with ``include_pat``, files matching this pattern will be
excluded from the subset of files defined by ``include_pat``.
CLI Example:
.. code-block:: bash
salt '*' net.cli "show version" "show chassis fan"
CLI Example with TextFSM template:
.. code-block:: bash
salt '*' net.cli textfsm_parse=True textfsm_path=salt://textfsm/
Example output:
.. code-block:: python
{
'show version and haiku': 'Hostname: re0.edge01.arn01
Model: mx480
Junos: 13.3R6.5
Help me, Obi-Wan
I just saw Episode Two
You're my only hope
',
'show chassis fan' : 'Item Status RPM Measurement
Top Rear Fan OK 3840 Spinning at intermediate-speed
Bottom Rear Fan OK 3840 Spinning at intermediate-speed
Top Middle Fan OK 3900 Spinning at intermediate-speed
Bottom Middle Fan OK 3840 Spinning at intermediate-speed
Top Front Fan OK 3810 Spinning at intermediate-speed
Bottom Front Fan OK 3840 Spinning at intermediate-speed
'
}
Example output with TextFSM parsing:
.. code-block:: json
{
"comment": "",
"result": true,
"out": {
"sh ver": [
{
"kernel": "9.1S3.5",
"documentation": "9.1S3.5",
"boot": "9.1S3.5",
"crypto": "9.1S3.5",
"chassis": "",
"routing": "9.1S3.5",
"base": "9.1S3.5",
"model": "mx960"
}
]
}
}
'''
raw_cli_outputs = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'cli',
**{
'commands': list(commands)
}
)
# thus we can display the output as is
# in case of errors, they'll be catched in the proxy
if not raw_cli_outputs['result']:
# Error -> dispaly the output as-is.
return raw_cli_outputs
textfsm_parse = kwargs.get('textfsm_parse') or __opts__.get('napalm_cli_textfsm_parse') or\
__pillar__.get('napalm_cli_textfsm_parse', False)
if not textfsm_parse:
# No TextFSM parsing required, return raw commands.
log.debug('No TextFSM parsing requested.')
return raw_cli_outputs
if 'textfsm.extract' not in __salt__ or 'textfsm.index' not in __salt__:
raw_cli_outputs['comment'] += 'Unable to process: is TextFSM installed?'
log.error(raw_cli_outputs['comment'])
return raw_cli_outputs
textfsm_template = kwargs.get('textfsm_template')
log.debug('textfsm_template: %s', textfsm_template)
textfsm_path = kwargs.get('textfsm_path') or __opts__.get('textfsm_path') or\
__pillar__.get('textfsm_path')
log.debug('textfsm_path: %s', textfsm_path)
textfsm_template_dict = kwargs.get('textfsm_template_dict') or __opts__.get('napalm_cli_textfsm_template_dict') or\
__pillar__.get('napalm_cli_textfsm_template_dict', {})
log.debug('TextFSM command-template mapping: %s', textfsm_template_dict)
index_file = kwargs.get('index_file') or __opts__.get('textfsm_index_file') or\
__pillar__.get('textfsm_index_file')
log.debug('index_file: %s', index_file)
platform_grain_name = kwargs.get('platform_grain_name') or __opts__.get('textfsm_platform_grain') or\
__pillar__.get('textfsm_platform_grain', 'os')
log.debug('platform_grain_name: %s', platform_grain_name)
platform_column_name = kwargs.get('platform_column_name') or __opts__.get('textfsm_platform_column_name') or\
__pillar__.get('textfsm_platform_column_name', 'Platform')
log.debug('platform_column_name: %s', platform_column_name)
saltenv = kwargs.get('saltenv', 'base')
include_empty = kwargs.get('include_empty', False)
include_pat = kwargs.get('include_pat')
exclude_pat = kwargs.get('exclude_pat')
processed_cli_outputs = {
'comment': raw_cli_outputs.get('comment', ''),
'result': raw_cli_outputs['result'],
'out': {}
}
log.debug('Starting to analyse the raw outputs')
for command in list(commands):
command_output = raw_cli_outputs['out'][command]
log.debug('Output from command: %s', command)
log.debug(command_output)
processed_command_output = None
if textfsm_path:
log.debug('Using the templates under %s', textfsm_path)
processed_cli_output = __salt__['textfsm.index'](command,
platform_grain_name=platform_grain_name,
platform_column_name=platform_column_name,
output=command_output.strip(),
textfsm_path=textfsm_path,
saltenv=saltenv,
include_empty=include_empty,
include_pat=include_pat,
exclude_pat=exclude_pat)
log.debug('Processed CLI output:')
log.debug(processed_cli_output)
if not processed_cli_output['result']:
log.debug('Apparently this didnt work, returnin the raw output')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {0}: {1}.'.format(command,
processed_cli_output['comment'])
log.error(processed_cli_outputs['comment'])
elif processed_cli_output['out']:
log.debug('All good, %s has a nice output!', command)
processed_command_output = processed_cli_output['out']
else:
comment = '''\nProcessing "{}" didn't fail, but didn't return anything either. Dumping raw.'''.format(
command)
processed_cli_outputs['comment'] += comment
log.error(comment)
processed_command_output = command_output
elif textfsm_template or command in textfsm_template_dict:
if command in textfsm_template_dict:
textfsm_template = textfsm_template_dict[command]
log.debug('Using %s to process the command: %s', textfsm_template, command)
processed_cli_output = __salt__['textfsm.extract'](textfsm_template,
raw_text=command_output,
saltenv=saltenv)
log.debug('Processed CLI output:')
log.debug(processed_cli_output)
if not processed_cli_output['result']:
log.debug('Apparently this didnt work, returning '
'the raw output')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {0}: {1}'.format(command,
processed_cli_output['comment'])
log.error(processed_cli_outputs['comment'])
elif processed_cli_output['out']:
log.debug('All good, %s has a nice output!', command)
processed_command_output = processed_cli_output['out']
else:
log.debug('Processing %s didnt fail, but didnt return'
' anything either. Dumping raw.', command)
processed_command_output = command_output
else:
log.error('No TextFSM template specified, or no TextFSM path defined')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {}.'.format(command)
processed_cli_outputs['out'][command] = processed_command_output
processed_cli_outputs['comment'] = processed_cli_outputs['comment'].strip()
return processed_cli_outputs
@salt.utils.napalm.proxy_napalm_wrap
def traceroute(destination, source=None, ttl=None, timeout=None, vrf=None, **kwargs): # pylint: disable=unused-argument
'''
Calls the method traceroute from the NAPALM driver object and returns a dictionary with the result of the traceroute
command executed on the device.
destination
Hostname or address of remote host
source
Source address to use in outgoing traceroute packets
ttl
IP maximum time-to-live value (or IPv6 maximum hop-limit value)
timeout
Number of seconds to wait for response (seconds)
vrf
VRF (routing instance) for traceroute attempt
.. versionadded:: 2016.11.4
CLI Example:
.. code-block:: bash
salt '*' net.traceroute 8.8.8.8
salt '*' net.traceroute 8.8.8.8 source=127.0.0.1 ttl=5 timeout=1
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'traceroute',
**{
'destination': destination,
'source': source,
'ttl': ttl,
'timeout': timeout,
'vrf': vrf
}
)
@salt.utils.napalm.proxy_napalm_wrap
def ping(destination, source=None, ttl=None, timeout=None, size=None, count=None, vrf=None, **kwargs): # pylint: disable=unused-argument
'''
Executes a ping on the network device and returns a dictionary as a result.
destination
Hostname or IP address of remote host
source
Source address of echo request
ttl
IP time-to-live value (IPv6 hop-limit value) (1..255 hops)
timeout
Maximum wait time after sending final packet (seconds)
size
Size of request packets (0..65468 bytes)
count
Number of ping requests to send (1..2000000000 packets)
vrf
VRF (routing instance) for ping attempt
.. versionadded:: 2016.11.4
CLI Example:
.. code-block:: bash
salt '*' net.ping 8.8.8.8
salt '*' net.ping 8.8.8.8 ttl=3 size=65468
salt '*' net.ping 8.8.8.8 source=127.0.0.1 timeout=1 count=100
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'ping',
**{
'destination': destination,
'source': source,
'ttl': ttl,
'timeout': timeout,
'size': size,
'count': count,
'vrf': vrf
}
)
@salt.utils.napalm.proxy_napalm_wrap
def arp(interface='', ipaddr='', macaddr='', **kwargs): # pylint: disable=unused-argument
'''
NAPALM returns a list of dictionaries with details of the ARP entries.
:param interface: interface name to filter on
:param ipaddr: IP address to filter on
:param macaddr: MAC address to filter on
:return: List of the entries in the ARP table
CLI Example:
.. code-block:: bash
salt '*' net.arp
salt '*' net.arp macaddr='5c:5e:ab:da:3c:f0'
Example output:
.. code-block:: python
[
{
'interface' : 'MgmtEth0/RSP0/CPU0/0',
'mac' : '5c:5e:ab:da:3c:f0',
'ip' : '172.17.17.1',
'age' : 1454496274.84
},
{
'interface': 'MgmtEth0/RSP0/CPU0/0',
'mac' : '66:0e:94:96:e0:ff',
'ip' : '172.17.17.2',
'age' : 1435641582.49
}
]
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_arp_table',
**{
}
)
if not proxy_output.get('result'):
return proxy_output
arp_table = proxy_output.get('out')
if interface:
arp_table = _filter_list(arp_table, 'interface', interface)
if ipaddr:
arp_table = _filter_list(arp_table, 'ip', ipaddr)
if macaddr:
arp_table = _filter_list(arp_table, 'mac', macaddr)
proxy_output.update({
'out': arp_table
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def ipaddrs(**kwargs): # pylint: disable=unused-argument
'''
Returns IP addresses configured on the device.
:return: A dictionary with the IPv4 and IPv6 addresses of the interfaces.
Returns all configured IP addresses on all interfaces as a dictionary
of dictionaries. Keys of the main dictionary represent the name of the
interface. Values of the main dictionary represent are dictionaries
that may consist of two keys 'ipv4' and 'ipv6' (one, both or none)
which are themselvs dictionaries with the IP addresses as keys.
CLI Example:
.. code-block:: bash
salt '*' net.ipaddrs
Example output:
.. code-block:: python
{
'FastEthernet8': {
'ipv4': {
'10.66.43.169': {
'prefix_length': 22
}
}
},
'Loopback555': {
'ipv4': {
'192.168.1.1': {
'prefix_length': 24
}
},
'ipv6': {
'1::1': {
'prefix_length': 64
},
'2001:DB8:1::1': {
'prefix_length': 64
},
'FE80::3': {
'prefix_length': 'N/A'
}
}
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_interfaces_ip',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def interfaces(**kwargs): # pylint: disable=unused-argument
'''
Returns details of the interfaces on the device.
:return: Returns a dictionary of dictionaries. The keys for the first
dictionary will be the interfaces in the devices.
CLI Example:
.. code-block:: bash
salt '*' net.interfaces
Example output:
.. code-block:: python
{
'Management1': {
'is_up': False,
'is_enabled': False,
'description': '',
'last_flapped': -1,
'speed': 1000,
'mac_address': 'dead:beef:dead',
},
'Ethernet1':{
'is_up': True,
'is_enabled': True,
'description': 'foo',
'last_flapped': 1429978575.1554043,
'speed': 1000,
'mac_address': 'beef:dead:beef',
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_interfaces',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def lldp(interface='', **kwargs): # pylint: disable=unused-argument
'''
Returns a detailed view of the LLDP neighbors.
:param interface: interface name to filter on
:return: A dictionary with the LLDL neighbors. The keys are the
interfaces with LLDP activated on.
CLI Example:
.. code-block:: bash
salt '*' net.lldp
salt '*' net.lldp interface='TenGigE0/0/0/8'
Example output:
.. code-block:: python
{
'TenGigE0/0/0/8': [
{
'parent_interface': 'Bundle-Ether8',
'interface_description': 'TenGigE0/0/0/8',
'remote_chassis_id': '8c60.4f69.e96c',
'remote_system_name': 'switch',
'remote_port': 'Eth2/2/1',
'remote_port_description': 'Ethernet2/2/1',
'remote_system_description': 'Cisco Nexus Operating System (NX-OS) Software 7.1(0)N1(1a)
TAC support: http://www.cisco.com/tac
Copyright (c) 2002-2015, Cisco Systems, Inc. All rights reserved.',
'remote_system_capab': 'B, R',
'remote_system_enable_capab': 'B'
}
]
}
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_lldp_neighbors_detail',
**{
}
)
if not proxy_output.get('result'):
return proxy_output
lldp_neighbors = proxy_output.get('out')
if interface:
lldp_neighbors = {interface: lldp_neighbors.get(interface)}
proxy_output.update({
'out': lldp_neighbors
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def mac(address='', interface='', vlan=0, **kwargs): # pylint: disable=unused-argument
'''
Returns the MAC Address Table on the device.
:param address: MAC address to filter on
:param interface: Interface name to filter on
:param vlan: VLAN identifier
:return: A list of dictionaries representing the entries in the MAC Address Table
CLI Example:
.. code-block:: bash
salt '*' net.mac
salt '*' net.mac vlan=10
Example output:
.. code-block:: python
[
{
'mac' : '00:1c:58:29:4a:71',
'interface' : 'xe-3/0/2',
'static' : False,
'active' : True,
'moves' : 1,
'vlan' : 10,
'last_move' : 1454417742.58
},
{
'mac' : '8c:60:4f:58:e1:c1',
'interface' : 'xe-1/0/1',
'static' : False,
'active' : True,
'moves' : 2,
'vlan' : 42,
'last_move' : 1453191948.11
}
]
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_mac_address_table',
**{
}
)
if not proxy_output.get('result'):
# if negative, leave the output unchanged
return proxy_output
mac_address_table = proxy_output.get('out')
if vlan and isinstance(vlan, int):
mac_address_table = _filter_list(mac_address_table, 'vlan', vlan)
if address:
mac_address_table = _filter_list(mac_address_table, 'mac', address)
if interface:
mac_address_table = _filter_list(mac_address_table, 'interface', interface)
proxy_output.update({
'out': mac_address_table
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def config(source=None, **kwargs): # pylint: disable=unused-argument
'''
.. versionadded:: 2017.7.0
Return the whole configuration of the network device. By default, it will
return all possible configuration sources supported by the network device.
At most, there will be:
- running config
- startup config
- candidate config
To return only one of the configurations, you can use the ``source``
argument.
source
Which configuration type you want to display, default is all of them.
Options:
- running
- candidate
- startup
:return:
The object returned is a dictionary with the following keys:
- running (string): Representation of the native running configuration.
- candidate (string): Representation of the native candidate configuration.
If the device doesn't differentiate between running and startup
configuration this will an empty string.
- startup (string): Representation of the native startup configuration.
If the device doesn't differentiate between running and startup
configuration this will an empty string.
CLI Example:
.. code-block:: bash
salt '*' net.config
salt '*' net.config source=candidate
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_config',
**{
'retrieve': source
}
)
@salt.utils.napalm.proxy_napalm_wrap
def optics(**kwargs): # pylint: disable=unused-argument
'''
.. versionadded:: 2017.7.0
Fetches the power usage on the various transceivers installed
on the network device (in dBm), and returns a view that conforms with the
OpenConfig model openconfig-platform-transceiver.yang.
:return:
Returns a dictionary where the keys are as listed below:
* intf_name (unicode)
* physical_channels
* channels (list of dicts)
* index (int)
* state
* input_power
* instant (float)
* avg (float)
* min (float)
* max (float)
* output_power
* instant (float)
* avg (float)
* min (float)
* max (float)
* laser_bias_current
* instant (float)
* avg (float)
* min (float)
* max (float)
CLI Example:
.. code-block:: bash
salt '*' net.optics
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_optics',
**{
}
)
# <---- Call NAPALM getters --------------------------------------------------------------------------------------------
# ----- Configuration specific functions ------------------------------------------------------------------------------>
@salt.utils.napalm.proxy_napalm_wrap
def load_config(filename=None,
text=None,
test=False,
commit=True,
debug=False,
replace=False,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
commit_jid=None,
inherit_napalm_device=None,
saltenv='base',
**kwargs): # pylint: disable=unused-argument
'''
Applies configuration changes on the device. It can be loaded from a file or from inline string.
If you send both a filename and a string containing the configuration, the file has higher precedence.
By default this function will commit the changes. If there are no changes, it does not commit and
the flag ``already_configured`` will be set as ``True`` to point this out.
To avoid committing the configuration, set the argument ``test`` to ``True`` and will discard (dry run).
To keep the changes but not commit, set ``commit`` to ``False``.
To replace the config, set ``replace`` to ``True``.
filename
Path to the file containing the desired configuration.
This can be specified using the absolute path to the file,
or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
.. versionchanged:: 2018.3.0
text
String containing the desired configuration.
This argument is ignored when ``filename`` is specified.
test: False
Dry run? If set as ``True``, will apply the config, discard and return the changes. Default: ``False``
and will commit the changes on the device.
commit: True
Commit? Default: ``True``.
debug: False
Debug mode. Will insert a new key under the output dictionary, as ``loaded_config`` containing the raw
configuration loaded on the device.
.. versionadded:: 2016.11.2
replace: False
Load and replace the configuration. Default: ``False``.
.. versionadded:: 2016.11.2
commit_in: ``None``
Commit the changes in a specific number of minutes / hours. Example of
accepted formats: ``5`` (commit in 5 minutes), ``2m`` (commit in 2
minutes), ``1h`` (commit the changes in 1 hour)`, ``5h30m`` (commit
the changes in 5 hours and 30 minutes).
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
commit_at: ``None``
Commit the changes at a specific time. Example of accepted formats:
``1am`` (will commit the changes at the next 1AM), ``13:20`` (will
commit at 13:20), ``1:20am``, etc.
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
revert_in: ``None``
Commit and revert the changes in a specific number of minutes / hours.
Example of accepted formats: ``5`` (revert in 5 minutes), ``2m`` (revert
in 2 minutes), ``1h`` (revert the changes in 1 hour)`, ``5h30m`` (revert
the changes in 5 hours and 30 minutes).
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
revert_at: ``None``
Commit and revert the changes at a specific time. Example of accepted
formats: ``1am`` (will commit and revert the changes at the next 1AM),
``13:20`` (will commit and revert at 13:20), ``1:20am``, etc.
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
saltenv: ``base``
Specifies the Salt environment name.
.. versionadded:: 2018.3.0
:return: a dictionary having the following keys:
* result (bool): if the config was applied successfully. It is ``False`` only in case of failure. In case \
there are no changes to be applied and successfully performs all operations it is still ``True`` and so will be \
the ``already_configured`` flag (example below)
* comment (str): a message for the user
* already_configured (bool): flag to check if there were no changes applied
* loaded_config (str): the configuration loaded on the device. Requires ``debug`` to be set as ``True``
* diff (str): returns the config changes applied
CLI Example:
.. code-block:: bash
salt '*' net.load_config text='ntp peer 192.168.0.1'
salt '*' net.load_config filename='/absolute/path/to/your/file'
salt '*' net.load_config filename='/absolute/path/to/your/file' test=True
salt '*' net.load_config filename='/absolute/path/to/your/file' commit=False
Example output:
.. code-block:: python
{
'comment': 'Configuration discarded.',
'already_configured': False,
'result': True,
'diff': '[edit interfaces xe-0/0/5]+ description "Adding a description";'
}
'''
fun = 'load_merge_candidate'
if replace:
fun = 'load_replace_candidate'
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
if filename:
text = __salt__['cp.get_file_str'](filename, saltenv=saltenv)
if text is False:
# When using salt:// or https://, if the resource is not available,
# it will either raise an exception, or return False.
ret = {
'result': False,
'out': None
}
ret['comment'] = 'Unable to read from {}. Please specify a valid file or text.'.format(filename)
log.error(ret['comment'])
return ret
if commit_jid:
# When the commit_jid argument is passed, it probably is a scheduled
# commit to be executed, and filename is a temporary file which
# can be removed after reading it.
salt.utils.files.safe_rm(filename)
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
fun,
**{
'config': text
}
)
return _config_logic(napalm_device, # pylint: disable=undefined-variable
_loaded,
test=test,
debug=debug,
replace=replace,
commit_config=commit,
loaded_config=text,
commit_at=commit_at,
commit_in=commit_in,
revert_in=revert_in,
revert_at=revert_at,
commit_jid=commit_jid,
**kwargs)
@salt.utils.napalm.proxy_napalm_wrap
def load_template(template_name=None,
template_source=None,
context=None,
defaults=None,
template_engine='jinja',
saltenv='base',
template_hash=None,
template_hash_name=None,
skip_verify=False,
test=False,
commit=True,
debug=False,
replace=False,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
inherit_napalm_device=None, # pylint: disable=unused-argument
**template_vars):
'''
Renders a configuration template (default: Jinja) and loads the result on the device.
By default this function will commit the changes. If there are no changes,
it does not commit, discards he config and the flag ``already_configured``
will be set as ``True`` to point this out.
To avoid committing the configuration, set the argument ``test`` to ``True``
and will discard (dry run).
To preserve the changes, set ``commit`` to ``False``.
However, this is recommended to be used only in exceptional cases
when there are applied few consecutive states
and/or configuration changes.
Otherwise the user might forget that the config DB is locked
and the candidate config buffer is not cleared/merged in the running config.
To replace the config, set ``replace`` to ``True``.
template_name
Identifies path to the template source.
The template can be either stored on the local machine, either remotely.
The recommended location is under the ``file_roots``
as specified in the master config file.
For example, let's suppose the ``file_roots`` is configured as:
.. code-block:: yaml
file_roots:
base:
- /etc/salt/states
Placing the template under ``/etc/salt/states/templates/example.jinja``,
it can be used as ``salt://templates/example.jinja``.
Alternatively, for local files, the user can specify the absolute path.
If remotely, the source can be retrieved via ``http``, ``https`` or ``ftp``.
Examples:
- ``salt://my_template.jinja``
- ``/absolute/path/to/my_template.jinja``
- ``http://example.com/template.cheetah``
- ``https:/example.com/template.mako``
- ``ftp://example.com/template.py``
.. versionchanged:: 2019.2.0
This argument can now support a list of templates to be rendered.
The resulting configuration text is loaded at once, as a single
configuration chunk.
template_source: None
Inline config template to be rendered and loaded on the device.
template_hash: None
Hash of the template file. Format: ``{hash_type: 'md5', 'hsum': <md5sum>}``
.. versionadded:: 2016.11.2
context: None
Overrides default context variables passed to the template.
.. versionadded:: 2019.2.0
template_hash_name: None
When ``template_hash`` refers to a remote file,
this specifies the filename to look for in that file.
.. versionadded:: 2016.11.2
saltenv: ``base``
Specifies the template environment.
This will influence the relative imports inside the templates.
.. versionadded:: 2016.11.2
template_engine: jinja
The following templates engines are supported:
- :mod:`cheetah<salt.renderers.cheetah>`
- :mod:`genshi<salt.renderers.genshi>`
- :mod:`jinja<salt.renderers.jinja>`
- :mod:`mako<salt.renderers.mako>`
- :mod:`py<salt.renderers.py>`
- :mod:`wempy<salt.renderers.wempy>`
.. versionadded:: 2016.11.2
skip_verify: True
If ``True``, hash verification of remote file sources
(``http://``, ``https://``, ``ftp://``) will be skipped,
and the ``source_hash`` argument will be ignored.
.. versionadded:: 2016.11.2
test: False
Dry run? If set to ``True``, will apply the config,
discard and return the changes.
Default: ``False`` and will commit the changes on the device.
commit: True
Commit? (default: ``True``)
debug: False
Debug mode. Will insert a new key under the output dictionary,
as ``loaded_config`` containing the raw result after the template was rendered.
.. versionadded:: 2016.11.2
replace: False
Load and replace the configuration.
.. versionadded:: 2016.11.2
commit_in: ``None``
Commit the changes in a specific number of minutes / hours. Example of
accepted formats: ``5`` (commit in 5 minutes), ``2m`` (commit in 2
minutes), ``1h`` (commit the changes in 1 hour)`, ``5h30m`` (commit
the changes in 5 hours and 30 minutes).
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
commit_at: ``None``
Commit the changes at a specific time. Example of accepted formats:
``1am`` (will commit the changes at the next 1AM), ``13:20`` (will
commit at 13:20), ``1:20am``, etc.
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
revert_in: ``None``
Commit and revert the changes in a specific number of minutes / hours.
Example of accepted formats: ``5`` (revert in 5 minutes), ``2m`` (revert
in 2 minutes), ``1h`` (revert the changes in 1 hour)`, ``5h30m`` (revert
the changes in 5 hours and 30 minutes).
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
revert_at: ``None``
Commit and revert the changes at a specific time. Example of accepted
formats: ``1am`` (will commit and revert the changes at the next 1AM),
``13:20`` (will commit and revert at 13:20), ``1:20am``, etc.
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
defaults: None
Default variables/context passed to the template.
.. versionadded:: 2016.11.2
template_vars
Dictionary with the arguments/context to be used when the template is rendered.
.. note::
Do not explicitly specify this argument. This represents any other
variable that will be sent to the template rendering system.
Please see the examples below!
.. note::
It is more recommended to use the ``context`` argument to avoid
conflicts between CLI arguments and template variables.
:return: a dictionary having the following keys:
- result (bool): if the config was applied successfully. It is ``False``
only in case of failure. In case there are no changes to be applied and
successfully performs all operations it is still ``True`` and so will be
the ``already_configured`` flag (example below)
- comment (str): a message for the user
- already_configured (bool): flag to check if there were no changes applied
- loaded_config (str): the configuration loaded on the device, after
rendering the template. Requires ``debug`` to be set as ``True``
- diff (str): returns the config changes applied
The template can use variables from the ``grains``, ``pillar`` or ``opts``, for example:
.. code-block:: jinja
{% set router_model = grains.get('model') -%}
{% set router_vendor = grains.get('vendor') -%}
{% set os_version = grains.get('version') -%}
{% set hostname = pillar.get('proxy', {}).get('host') -%}
{% if router_vendor|lower == 'juniper' %}
system {
host-name {{hostname}};
}
{% elif router_vendor|lower == 'cisco' %}
hostname {{hostname}}
{% endif %}
CLI Examples:
.. code-block:: bash
salt '*' net.load_template set_ntp_peers peers=[192.168.0.1] # uses NAPALM default templates
# inline template:
salt -G 'os:junos' net.load_template template_source='system { host-name {{host_name}}; }' \
host_name='MX480.lab'
# inline template using grains info:
salt -G 'os:junos' net.load_template \
template_source='system { host-name {{grains.model}}.lab; }'
# if the device is a MX480, the command above will set the hostname as: MX480.lab
# inline template using pillar data:
salt -G 'os:junos' net.load_template template_source='system { host-name {{pillar.proxy.host}}; }'
salt '*' net.load_template https://bit.ly/2OhSgqP hostname=example # will commit
salt '*' net.load_template https://bit.ly/2OhSgqP hostname=example test=True # dry run
salt '*' net.load_template salt://templates/example.jinja debug=True # Using the salt:// URI
# render a mako template:
salt '*' net.load_template salt://templates/example.mako template_engine=mako debug=True
# render remote template
salt -G 'os:junos' net.load_template http://bit.ly/2fReJg7 test=True debug=True peers=['192.168.0.1']
salt -G 'os:ios' net.load_template http://bit.ly/2gKOj20 test=True debug=True peers=['192.168.0.1']
# render multiple templates at once
salt '*' net.load_template "['https://bit.ly/2OhSgqP', 'salt://templates/example.jinja']" context="{'hostname': 'example'}"
Example output:
.. code-block:: python
{
'comment': '',
'already_configured': False,
'result': True,
'diff': '[edit system]+ host-name edge01.bjm01',
'loaded_config': 'system { host-name edge01.bjm01; }''
}
'''
_rendered = ''
_loaded = {
'result': True,
'comment': '',
'out': None
}
loaded_config = None
# prechecks
deprecated_args = ('template_user', 'template_attrs', 'template_group', 'template_mode')
for deprecated_arg in deprecated_args:
if template_vars.get(deprecated_arg):
del template_vars[deprecated_arg]
salt.utils.versions.warn_until(
'Sodium',
('The \'{arg}\' argument to \'net.load_template\' is deprecated '
'and has been ignored').format(arg=deprecated_arg)
)
if template_engine not in salt.utils.templates.TEMPLATE_REGISTRY:
_loaded.update({
'result': False,
'comment': 'Invalid templating engine! Choose between: {tpl_eng_opts}'.format(
tpl_eng_opts=', '.join(list(salt.utils.templates.TEMPLATE_REGISTRY.keys()))
)
})
return _loaded # exit
# to check if will be rendered by salt or NAPALM
salt_render_prefixes = ('salt://', 'http://', 'https://', 'ftp://')
salt_render = False
file_exists = False
if not isinstance(template_name, (tuple, list)):
for salt_render_prefix in salt_render_prefixes:
if not salt_render:
salt_render = salt_render or template_name.startswith(salt_render_prefix)
file_exists = __salt__['file.file_exists'](template_name)
if template_source or file_exists or salt_render or isinstance(template_name, (tuple, list)):
# either inline template
# either template in a custom path
# either abs path send
# either starts with salt:// and
# then use Salt render system
if context is None:
context = {}
context.update(template_vars)
# if needed to render the template send as inline arg
if template_source:
# render the content
_rendered = __salt__['file.apply_template_on_contents'](
contents=template_source,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv
)
if not isinstance(_rendered, six.string_types):
if 'result' in _rendered:
_loaded['result'] = _rendered['result']
else:
_loaded['result'] = False
if 'comment' in _rendered:
_loaded['comment'] = _rendered['comment']
else:
_loaded['comment'] = 'Error while rendering the template.'
return _loaded
else:
# render the file - either local, either remote
if not isinstance(template_name, (list, tuple)):
template_name = [template_name]
if template_hash_name and not isinstance(template_hash_name, (list, tuple)):
template_hash_name = [template_hash_name]
elif not template_hash_name:
template_hash_name = [None] * len(template_name)
if template_hash and isinstance(template_hash, six.string_types) and not\
(template_hash.startswith('salt://') or template_hash.startswith('file://')):
# If the template hash is passed as string, and it's not a file
# (starts with the salt:// or file:// URI), then make it a list
# of 1 element (for the iteration below)
template_hash = [template_hash]
elif template_hash and isinstance(template_hash, six.string_types) and\
(template_hash.startswith('salt://') or template_hash.startswith('file://')):
# If the template hash is a file URI, then provide the same value
# for each of the templates in the list, as probably they all
# share the same hash file, otherwise the user should provide
# this as a list
template_hash = [template_hash] * len(template_name)
elif not template_hash:
template_hash = [None] * len(template_name)
for tpl_index, tpl_name in enumerate(template_name):
tpl_hash = template_hash[tpl_index]
tpl_hash_name = template_hash_name[tpl_index]
_rand_filename = __salt__['random.hash'](tpl_name, 'md5')
_temp_file = __salt__['file.join']('/tmp', _rand_filename)
_managed = __salt__['file.get_managed'](name=_temp_file,
source=tpl_name,
source_hash=tpl_hash,
source_hash_name=tpl_hash_name,
user=None,
group=None,
mode=None,
attrs=None,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv,
skip_verify=skip_verify)
if not isinstance(_managed, (list, tuple)) and isinstance(_managed, six.string_types):
_loaded['comment'] += _managed
_loaded['result'] = False
elif isinstance(_managed, (list, tuple)) and not _managed:
_loaded['result'] = False
_loaded['comment'] += 'Error while rendering the template.'
elif isinstance(_managed, (list, tuple)) and not _managed[0]:
_loaded['result'] = False
_loaded['comment'] += _managed[-1] # contains the error message
if _loaded['result']: # all good
_temp_tpl_file = _managed[0]
_temp_tpl_file_exists = __salt__['file.file_exists'](_temp_tpl_file)
if not _temp_tpl_file_exists:
_loaded['result'] = False
_loaded['comment'] += 'Error while rendering the template.'
return _loaded
_rendered += __salt__['file.read'](_temp_tpl_file)
__salt__['file.remove'](_temp_tpl_file)
else:
return _loaded # exit
loaded_config = _rendered
if _loaded['result']: # all good
fun = 'load_merge_candidate'
if replace: # replace requested
fun = 'load_replace_candidate'
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
fun,
**{
'config': _rendered
}
)
else:
salt.utils.versions.warn_until(
'Sodium',
'Native NAPALM templates support will be removed in the Sodium '
'release. Please consider using the Salt rendering pipeline instead.'
'If you are using the \'netntp\', \'netsnmp\', or \'netusers\' Salt '
'State modules, you can ignore this message'
)
# otherwise, use NAPALM render system, injecting pillar/grains/opts vars
load_templates_params = defaults if defaults else {}
load_templates_params.update(template_vars)
load_templates_params.update(
{
'template_name': template_name,
'template_source': template_source, # inline template
'pillar': __pillar__, # inject pillar content
'grains': __grains__, # inject grains content
'opts': __opts__ # inject opts content
}
)
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
# so we'll set the CLOSE global explicitly as False
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'load_template',
**load_templates_params
)
return _config_logic(napalm_device, # pylint: disable=undefined-variable
_loaded,
test=test,
debug=debug,
replace=replace,
commit_config=commit,
loaded_config=loaded_config,
commit_at=commit_at,
commit_in=commit_in,
revert_in=revert_in,
revert_at=revert_at,
**template_vars)
@salt.utils.napalm.proxy_napalm_wrap
def commit(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Commits the configuration changes made on the network device.
CLI Example:
.. code-block:: bash
salt '*' net.commit
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'commit_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def discard_config(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
"""
Discards the changes applied.
CLI Example:
.. code-block:: bash
salt '*' net.discard_config
"""
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'discard_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def compare_config(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Returns the difference between the running config and the candidate config.
CLI Example:
.. code-block:: bash
salt '*' net.compare_config
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'compare_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def rollback(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Rollbacks the configuration.
CLI Example:
.. code-block:: bash
salt '*' net.rollback
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'rollback',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def config_changed(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Will prompt if the configuration has been changed.
:return: A tuple with a boolean that specifies if the config was changed on the device.\
And a string that provides more details of the reason why the configuration was not changed.
CLI Example:
.. code-block:: bash
salt '*' net.config_changed
'''
is_config_changed = False
reason = ''
try_compare = compare_config(inherit_napalm_device=napalm_device) # pylint: disable=undefined-variable
if try_compare.get('result'):
if try_compare.get('out'):
is_config_changed = True
else:
reason = 'Configuration was not changed on the device.'
else:
reason = try_compare.get('comment')
return is_config_changed, reason
@salt.utils.napalm.proxy_napalm_wrap
def config_control(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Will check if the configuration was changed.
If differences found, will try to commit.
In case commit unsuccessful, will try to rollback.
:return: A tuple with a boolean that specifies if the config was changed/committed/rollbacked on the device.\
And a string that provides more details of the reason why the configuration was not committed properly.
CLI Example:
.. code-block:: bash
salt '*' net.config_control
'''
result = True
comment = ''
changed, not_changed_rsn = config_changed(inherit_napalm_device=napalm_device) # pylint: disable=undefined-variable
if not changed:
return (changed, not_changed_rsn)
# config changed, thus let's try to commit
try_commit = commit()
if not try_commit.get('result'):
result = False
comment = 'Unable to commit the changes: {reason}.\n\
Will try to rollback now!'.format(
reason=try_commit.get('comment')
)
try_rollback = rollback()
if not try_rollback.get('result'):
comment += '\nCannot rollback! {reason}'.format(
reason=try_rollback.get('comment')
)
return result, comment
def cancel_commit(jid):
'''
.. versionadded:: 2019.2.0
Cancel a commit scheduled to be executed via the ``commit_in`` and
``commit_at`` arguments from the
:py:func:`net.load_template <salt.modules.napalm_network.load_template>` or
:py:func:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit ID is displayed when the commit is scheduled
via the functions named above.
CLI Example:
.. code-block:: bash
salt '*' net.cancel_commit 20180726083540640360
'''
job_name = '__napalm_commit_{}'.format(jid)
removed = __salt__['schedule.delete'](job_name)
if removed['result']:
saved = __salt__['schedule.save']()
removed['comment'] = 'Commit #{jid} cancelled.'.format(jid=jid)
else:
removed['comment'] = 'Unable to find commit #{jid}.'.format(jid=jid)
return removed
def confirm_commit(jid):
'''
.. versionadded:: 2019.2.0
Confirm a commit scheduled to be reverted via the ``revert_in`` and
``revert_at`` arguments from the
:mod:`net.load_template <salt.modules.napalm_network.load_template>` or
:mod:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit ID is displayed when the commit confirmed
is scheduled via the functions named above.
CLI Example:
.. code-block:: bash
salt '*' net.confirm_commit 20180726083540640360
'''
if __grains__['os'] == 'junos':
# Confirm the commit, by committing (i.e., invoking the RPC call)
confirmed = __salt__['napalm.junos_commit']()
confirmed['result'] = confirmed.pop('out')
confirmed['comment'] = confirmed.pop('message')
else:
confirmed = cancel_commit(jid)
if confirmed['result']:
confirmed['comment'] = 'Commit #{jid} confirmed.'.format(jid=jid)
return confirmed
def save_config(source=None,
path=None):
'''
.. versionadded:: 2019.2.0
Save the configuration to a file on the local file system.
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``,
``startup``. Default: ``running``.
path
Absolute path to file where to save the configuration.
To push the files to the Master, use
:mod:`cp.push <salt.modules.cp.push>` Execution function.
CLI Example:
.. code-block:: bash
salt '*' net.save_config source=running
'''
if not source:
source = 'running'
if not path:
path = salt.utils.files.mkstemp()
running_config = __salt__['net.config'](source=source)
if not running_config or not running_config['result']:
log.error('Unable to retrieve the config')
return running_config
with salt.utils.files.fopen(path, 'w') as fh_:
fh_.write(running_config['out'][source])
return {
'result': True,
'out': path,
'comment': '{source} config saved to {path}'.format(source=source, path=path)
}
def blockreplace(marker_start,
marker_end,
content='',
append_if_not_found=False,
prepend_if_not_found=False,
show_changes=True,
append_newline=False,
source='running',
path=None,
test=False,
commit=True,
debug=False,
replace=True):
'''
.. versionadded:: 2019.2.0
Replace content of the configuration source, delimited by the line markers.
A block of content delimited by comments can help you manage several lines
without worrying about old entries removal.
marker_start
The line content identifying a line as the start of the content block.
Note that the whole line containing this marker will be considered,
so whitespace or extra content before or after the marker is included
in final output.
marker_end
The line content identifying a line as the end of the content block.
Note that the whole line containing this marker will be considered,
so whitespace or extra content before or after the marker is included
in final output.
content
The content to be used between the two lines identified by
``marker_start`` and ``marker_stop``.
append_if_not_found: ``False``
If markers are not found and set to True then, the markers and content
will be appended to the file.
prepend_if_not_found: ``False``
If markers are not found and set to True then, the markers and content
will be prepended to the file.
append_newline: ``False``
Controls whether or not a newline is appended to the content block.
If the value of this argument is ``True`` then a newline will be added
to the content block. If it is ``False``, then a newline will not be
added to the content block. If it is ``None`` then a newline will only
be added to the content block if it does not already end in a newline.
show_changes: ``True``
Controls how changes are presented. If ``True``, this function will
return the of the changes made.
If ``False``, then it will return a boolean (``True`` if any changes
were made, otherwise False).
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path: ``None``
Save the temporary configuration to a specific path, then read from
there. This argument is optional, can be used when you prefers a
particular location of the temporary file.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
CLI Example:
.. code-block:: bash
salt '*' net.blockreplace 'ntp' 'interface' ''
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
replace_pattern = __salt__['file.blockreplace'](path,
marker_start=marker_start,
marker_end=marker_end,
content=content,
append_if_not_found=append_if_not_found,
prepend_if_not_found=prepend_if_not_found,
show_changes=show_changes,
append_newline=append_newline)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
def patch(patchfile,
options='',
saltenv='base',
source_hash=None,
show_changes=True,
source='running',
path=None,
test=False,
commit=True,
debug=False,
replace=True):
'''
.. versionadded:: 2019.2.0
Apply a patch to the configuration source, and load the result into the
running config of the device.
patchfile
A patch file to apply to the configuration source.
options
Options to pass to patch.
source_hash
If the patch file (specified via the ``patchfile`` argument) is an
HTTP(S) or FTP URL and the file exists in the minion's file cache, this
option can be passed to keep the minion from re-downloading the file if
the cached copy matches the specified hash.
show_changes: ``True``
Controls how changes are presented. If ``True``, this function will
return the of the changes made.
If ``False``, then it will return a boolean (``True`` if any changes
were made, otherwise False).
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path: ``None``
Save the temporary configuration to a specific path, then read from
there. This argument is optional, can the user prefers a particular
location of the temporary file.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
CLI Example:
.. code-block:: bash
salt '*' net.patch https://example.com/running_config.patch
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
patchfile_cache = __salt__['cp.cache_file'](patchfile)
if patchfile_cache is False:
return {
'out': None,
'result': False,
'comment': 'The file "{}" does not exist.'.format(patchfile)
}
replace_pattern = __salt__['file.patch'](path,
patchfile_cache,
options=options)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
# <---- Configuration specific functions -------------------------------------------------------------------------------
|
saltstack/salt
|
salt/modules/napalm_network.py
|
blockreplace
|
python
|
def blockreplace(marker_start,
marker_end,
content='',
append_if_not_found=False,
prepend_if_not_found=False,
show_changes=True,
append_newline=False,
source='running',
path=None,
test=False,
commit=True,
debug=False,
replace=True):
'''
.. versionadded:: 2019.2.0
Replace content of the configuration source, delimited by the line markers.
A block of content delimited by comments can help you manage several lines
without worrying about old entries removal.
marker_start
The line content identifying a line as the start of the content block.
Note that the whole line containing this marker will be considered,
so whitespace or extra content before or after the marker is included
in final output.
marker_end
The line content identifying a line as the end of the content block.
Note that the whole line containing this marker will be considered,
so whitespace or extra content before or after the marker is included
in final output.
content
The content to be used between the two lines identified by
``marker_start`` and ``marker_stop``.
append_if_not_found: ``False``
If markers are not found and set to True then, the markers and content
will be appended to the file.
prepend_if_not_found: ``False``
If markers are not found and set to True then, the markers and content
will be prepended to the file.
append_newline: ``False``
Controls whether or not a newline is appended to the content block.
If the value of this argument is ``True`` then a newline will be added
to the content block. If it is ``False``, then a newline will not be
added to the content block. If it is ``None`` then a newline will only
be added to the content block if it does not already end in a newline.
show_changes: ``True``
Controls how changes are presented. If ``True``, this function will
return the of the changes made.
If ``False``, then it will return a boolean (``True`` if any changes
were made, otherwise False).
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path: ``None``
Save the temporary configuration to a specific path, then read from
there. This argument is optional, can be used when you prefers a
particular location of the temporary file.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
CLI Example:
.. code-block:: bash
salt '*' net.blockreplace 'ntp' 'interface' ''
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
replace_pattern = __salt__['file.blockreplace'](path,
marker_start=marker_start,
marker_end=marker_end,
content=content,
append_if_not_found=append_if_not_found,
prepend_if_not_found=prepend_if_not_found,
show_changes=show_changes,
append_newline=append_newline)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
|
.. versionadded:: 2019.2.0
Replace content of the configuration source, delimited by the line markers.
A block of content delimited by comments can help you manage several lines
without worrying about old entries removal.
marker_start
The line content identifying a line as the start of the content block.
Note that the whole line containing this marker will be considered,
so whitespace or extra content before or after the marker is included
in final output.
marker_end
The line content identifying a line as the end of the content block.
Note that the whole line containing this marker will be considered,
so whitespace or extra content before or after the marker is included
in final output.
content
The content to be used between the two lines identified by
``marker_start`` and ``marker_stop``.
append_if_not_found: ``False``
If markers are not found and set to True then, the markers and content
will be appended to the file.
prepend_if_not_found: ``False``
If markers are not found and set to True then, the markers and content
will be prepended to the file.
append_newline: ``False``
Controls whether or not a newline is appended to the content block.
If the value of this argument is ``True`` then a newline will be added
to the content block. If it is ``False``, then a newline will not be
added to the content block. If it is ``None`` then a newline will only
be added to the content block if it does not already end in a newline.
show_changes: ``True``
Controls how changes are presented. If ``True``, this function will
return the of the changes made.
If ``False``, then it will return a boolean (``True`` if any changes
were made, otherwise False).
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path: ``None``
Save the temporary configuration to a specific path, then read from
there. This argument is optional, can be used when you prefers a
particular location of the temporary file.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
CLI Example:
.. code-block:: bash
salt '*' net.blockreplace 'ntp' 'interface' ''
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_network.py#L2476-L2582
|
[
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n",
"def save_config(source=None,\n path=None):\n '''\n .. versionadded:: 2019.2.0\n\n Save the configuration to a file on the local file system.\n\n source: ``running``\n The configuration source. Choose from: ``running``, ``candidate``,\n ``startup``. Default: ``running``.\n\n path\n Absolute path to file where to save the configuration.\n To push the files to the Master, use\n :mod:`cp.push <salt.modules.cp.push>` Execution function.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' net.save_config source=running\n '''\n if not source:\n source = 'running'\n if not path:\n path = salt.utils.files.mkstemp()\n running_config = __salt__['net.config'](source=source)\n if not running_config or not running_config['result']:\n log.error('Unable to retrieve the config')\n return running_config\n with salt.utils.files.fopen(path, 'w') as fh_:\n fh_.write(running_config['out'][source])\n return {\n 'result': True,\n 'out': path,\n 'comment': '{source} config saved to {path}'.format(source=source, path=path)\n }\n"
] |
# -*- coding: utf-8 -*-
'''
NAPALM Network
==============
Basic methods for interaction with the network device through the virtual proxy 'napalm'.
:codeauthor: Mircea Ulinic <mircea@cloudflare.com> & Jerome Fleury <jf@cloudflare.com>
:maturity: new
:depends: napalm
:platform: unix
Dependencies
------------
- :mod:`napalm proxy minion <salt.proxy.napalm>`
.. versionadded:: 2016.11.0
.. versionchanged:: 2017.7.0
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import time
import logging
import datetime
log = logging.getLogger(__name__)
# Import Salt libs
from salt.ext import six
import salt.utils.files
import salt.utils.napalm
import salt.utils.versions
import salt.utils.templates
# Import 3rd-party libs
try:
import jxmlease # pylint: disable=unused-import
HAS_JXMLEASE = True
except ImportError:
HAS_JXMLEASE = False
# ----------------------------------------------------------------------------------------------------------------------
# module properties
# ----------------------------------------------------------------------------------------------------------------------
__virtualname__ = 'net'
__proxyenabled__ = ['*']
__virtual_aliases__ = ('napalm_net',)
# uses NAPALM-based proxy to interact with network devices
# ----------------------------------------------------------------------------------------------------------------------
# property functions
# ----------------------------------------------------------------------------------------------------------------------
def __virtual__():
'''
NAPALM library must be installed for this module to work and run in a (proxy) minion.
'''
return salt.utils.napalm.virtual(__opts__, __virtualname__, __file__)
# ----------------------------------------------------------------------------------------------------------------------
# helper functions -- will not be exported
# ----------------------------------------------------------------------------------------------------------------------
def _filter_list(input_list, search_key, search_value):
'''
Filters a list of dictionary by a set of key-value pair.
:param input_list: is a list of dictionaries
:param search_key: is the key we are looking for
:param search_value: is the value we are looking for the key specified in search_key
:return: filered list of dictionaries
'''
output_list = list()
for dictionary in input_list:
if dictionary.get(search_key) == search_value:
output_list.append(dictionary)
return output_list
def _filter_dict(input_dict, search_key, search_value):
'''
Filters a dictionary of dictionaries by a key-value pair.
:param input_dict: is a dictionary whose values are lists of dictionaries
:param search_key: is the key in the leaf dictionaries
:param search_values: is the value in the leaf dictionaries
:return: filtered dictionary
'''
output_dict = dict()
for key, key_list in six.iteritems(input_dict):
key_list_filtered = _filter_list(key_list, search_key, search_value)
if key_list_filtered:
output_dict[key] = key_list_filtered
return output_dict
def _safe_commit_config(loaded_result, napalm_device):
_commit = commit(inherit_napalm_device=napalm_device) # calls the function commit, defined below
if not _commit.get('result', False):
# if unable to commit
loaded_result['comment'] += _commit['comment'] if _commit.get('comment') else 'Unable to commit.'
loaded_result['result'] = False
# unable to commit, something went wrong
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
return _commit
def _safe_dicard_config(loaded_result, napalm_device):
'''
'''
log.debug('Discarding the config')
log.debug(loaded_result)
_discarded = discard_config(inherit_napalm_device=napalm_device)
if not _discarded.get('result', False):
loaded_result['comment'] += _discarded['comment'] if _discarded.get('comment') \
else 'Unable to discard config.'
loaded_result['result'] = False
# make sure it notifies
# that something went wrong
_explicit_close(napalm_device)
__context__['retcode'] = 1
return loaded_result
return _discarded
def _explicit_close(napalm_device):
'''
Will explicily close the config session with the network device,
when running in a now-always-alive proxy minion or regular minion.
This helper must be used in configuration-related functions,
as the session is preserved and not closed before making any changes.
'''
if salt.utils.napalm.not_always_alive(__opts__):
# force closing the configuration session
# when running in a non-always-alive proxy
# or regular minion
try:
napalm_device['DRIVER'].close()
except Exception as err:
log.error('Unable to close the temp connection with the device:')
log.error(err)
log.error('Please report.')
def _config_logic(napalm_device,
loaded_result,
test=False,
debug=False,
replace=False,
commit_config=True,
loaded_config=None,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
commit_jid=None,
**kwargs):
'''
Builds the config logic for `load_config` and `load_template` functions.
'''
# As the Salt logic is built around independent events
# when it comes to configuration changes in the
# candidate DB on the network devices, we need to
# make sure we're using the same session.
# Hence, we need to pass the same object around.
# the napalm_device object is inherited from
# the load_config or load_template functions
# and forwarded to compare, discard, commit etc.
# then the decorator will make sure that
# if not proxy (when the connection is always alive)
# and the `inherit_napalm_device` is set,
# `napalm_device` will be overridden.
# See `salt.utils.napalm.proxy_napalm_wrap` decorator.
current_jid = kwargs.get('__pub_jid')
if not current_jid:
current_jid = '{0:%Y%m%d%H%M%S%f}'.format(datetime.datetime.now())
loaded_result['already_configured'] = False
loaded_result['loaded_config'] = ''
if debug:
loaded_result['loaded_config'] = loaded_config
_compare = compare_config(inherit_napalm_device=napalm_device)
if _compare.get('result', False):
loaded_result['diff'] = _compare.get('out')
loaded_result.pop('out', '') # not needed
else:
loaded_result['diff'] = None
loaded_result['result'] = False
loaded_result['comment'] = _compare.get('comment')
__context__['retcode'] = 1
return loaded_result
_loaded_res = loaded_result.get('result', False)
if not _loaded_res or test:
# if unable to load the config (errors / warnings)
# or in testing mode,
# will discard the config
if loaded_result['comment']:
loaded_result['comment'] += '\n'
if not loaded_result.get('diff', ''):
loaded_result['already_configured'] = True
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
loaded_result['comment'] += 'Configuration discarded.'
# loaded_result['result'] = False not necessary
# as the result can be true when test=True
_explicit_close(napalm_device)
if not loaded_result['result']:
__context__['retcode'] = 1
return loaded_result
if not test and commit_config:
# if not in testing mode and trying to commit
if commit_jid:
log.info('Committing the JID: %s', str(commit_jid))
removed = cancel_commit(commit_jid)
log.debug('Cleaned up the commit from the schedule')
log.debug(removed['comment'])
if loaded_result.get('diff', ''):
# if not testing mode
# and also the user wants to commit (default)
# and there are changes to commit
if commit_in or commit_at:
commit_time = __utils__['timeutil.get_time_at'](time_in=commit_in,
time_at=commit_in)
# schedule job
scheduled_job_name = '__napalm_commit_{}'.format(current_jid)
temp_file = salt.utils.files.mkstemp()
with salt.utils.files.fopen(temp_file, 'w') as fp_:
fp_.write(loaded_config)
scheduled = __salt__['schedule.add'](scheduled_job_name,
function='net.load_config',
job_kwargs={
'filename': temp_file,
'commit_jid': current_jid,
'replace': replace
},
once=commit_time)
log.debug('Scheduling job')
log.debug(scheduled)
saved = __salt__['schedule.save']() # ensure the schedule is
# persistent cross Minion restart
discarded = _safe_dicard_config(loaded_result, napalm_device)
# discard the changes
if not discarded['result']:
discarded['comment'] += ('Scheduled the job to be executed at {schedule_ts}, '
'but was unable to discard the config: \n').format(schedule_ts=commit_time)
return discarded
loaded_result['comment'] = ('Changes discarded for now, and scheduled commit at: {schedule_ts}.\n'
'The commit ID is: {current_jid}.\n'
'To discard this commit, you can execute: \n\n'
'salt {min_id} net.cancel_commit {current_jid}').format(schedule_ts=commit_time,
min_id=__opts__['id'],
current_jid=current_jid)
loaded_result['commit_id'] = current_jid
return loaded_result
log.debug('About to commit:')
log.debug(loaded_result['diff'])
if revert_in or revert_at:
revert_time = __utils__['timeutil.get_time_at'](time_in=revert_in,
time_at=revert_at)
if __grains__['os'] == 'junos':
if not HAS_JXMLEASE:
loaded_result['comment'] = ('This feature requires the library jxmlease to be installed.\n'
'To install, please execute: ``pip install jxmlease``.')
loaded_result['result'] = False
return loaded_result
timestamp_at = __utils__['timeutil.get_timestamp_at'](time_in=revert_in,
time_at=revert_at)
minutes = int((timestamp_at - time.time())/60)
_comm = __salt__['napalm.junos_commit'](confirm=minutes)
if not _comm['out']:
# If unable to commit confirm, should try to bail out
loaded_result['comment'] = 'Unable to commit confirm: {}'.format(_comm['message'])
loaded_result['result'] = False
# But before exiting, we must gracefully discard the config
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
else:
temp_file = salt.utils.files.mkstemp()
running_config = __salt__['net.config'](source='running')['out']['running']
with salt.utils.files.fopen(temp_file, 'w') as fp_:
fp_.write(running_config)
committed = _safe_commit_config(loaded_result, napalm_device)
if not committed['result']:
# If unable to commit, dicard the config (which is
# already done by the _safe_commit_config function), and
# return with the command and other details.
return loaded_result
scheduled_job_name = '__napalm_commit_{}'.format(current_jid)
scheduled = __salt__['schedule.add'](scheduled_job_name,
function='net.load_config',
job_kwargs={
'filename': temp_file,
'commit_jid': current_jid,
'replace': True
},
once=revert_time)
log.debug('Scheduling commit confirmed')
log.debug(scheduled)
saved = __salt__['schedule.save']()
loaded_result['comment'] = ('The commit ID is: {current_jid}.\n'
'This commit will be reverted at: {schedule_ts}, unless confirmed.\n'
'To confirm the commit and avoid reverting, you can execute:\n\n'
'salt {min_id} net.confirm_commit {current_jid}').format(schedule_ts=revert_time,
min_id=__opts__['id'],
current_jid=current_jid)
loaded_result['commit_id'] = current_jid
return loaded_result
committed = _safe_commit_config(loaded_result, napalm_device)
if not committed['result']:
return loaded_result
else:
# would like to commit, but there's no change
# need to call discard_config() to release the config DB
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
loaded_result['already_configured'] = True
loaded_result['comment'] = 'Already configured.'
_explicit_close(napalm_device)
if not loaded_result['result']:
__context__['retcode'] = 1
return loaded_result
# ----------------------------------------------------------------------------------------------------------------------
# callable functions
# ----------------------------------------------------------------------------------------------------------------------
@salt.utils.napalm.proxy_napalm_wrap
def connected(**kwargs): # pylint: disable=unused-argument
'''
Specifies if the connection to the device succeeded.
CLI Example:
.. code-block:: bash
salt '*' net.connected
'''
return {
'out': napalm_device.get('UP', False) # pylint: disable=undefined-variable
}
@salt.utils.napalm.proxy_napalm_wrap
def facts(**kwargs): # pylint: disable=unused-argument
'''
Returns characteristics of the network device.
:return: a dictionary with the following keys:
* uptime - Uptime of the device in seconds.
* vendor - Manufacturer of the device.
* model - Device model.
* hostname - Hostname of the device
* fqdn - Fqdn of the device
* os_version - String with the OS version running on the device.
* serial_number - Serial number of the device
* interface_list - List of the interfaces of the device
CLI Example:
.. code-block:: bash
salt '*' net.facts
Example output:
.. code-block:: python
{
'os_version': '13.3R6.5',
'uptime': 10117140,
'interface_list': [
'lc-0/0/0',
'pfe-0/0/0',
'pfh-0/0/0',
'xe-0/0/0',
'xe-0/0/1',
'xe-0/0/2',
'xe-0/0/3',
'gr-0/0/10',
'ip-0/0/10'
],
'vendor': 'Juniper',
'serial_number': 'JN131356FBFA',
'model': 'MX480',
'hostname': 're0.edge05.syd01',
'fqdn': 're0.edge05.syd01'
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_facts',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def environment(**kwargs): # pylint: disable=unused-argument
'''
Returns the environment of the device.
CLI Example:
.. code-block:: bash
salt '*' net.environment
Example output:
.. code-block:: python
{
'fans': {
'Bottom Rear Fan': {
'status': True
},
'Bottom Middle Fan': {
'status': True
},
'Top Middle Fan': {
'status': True
},
'Bottom Front Fan': {
'status': True
},
'Top Front Fan': {
'status': True
},
'Top Rear Fan': {
'status': True
}
},
'memory': {
'available_ram': 16349,
'used_ram': 4934
},
'temperature': {
'FPC 0 Exhaust A': {
'is_alert': False,
'temperature': 35.0,
'is_critical': False
}
},
'cpu': {
'1': {
'%usage': 19.0
},
'0': {
'%usage': 35.0
}
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_environment',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def cli(*commands, **kwargs): # pylint: disable=unused-argument
'''
Returns a dictionary with the raw output of all commands passed as arguments.
commands
List of commands to be executed on the device.
textfsm_parse: ``False``
Try parsing the outputs using the TextFSM templates.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``napalm_cli_textfsm_parse``.
textfsm_path
The path where the TextFSM templates can be found. This option implies
the usage of the TextFSM index file.
``textfsm_path`` can be either absolute path on the server,
either specified using the following URL mschemes: ``file://``,
``salt://``, ``http://``, ``https://``, ``ftp://``,
``s3://``, ``swift://``.
.. versionadded:: 2018.3.0
.. note::
This needs to be a directory with a flat structure, having an
index file (whose name can be specified using the ``index_file`` option)
and a number of TextFSM templates.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_path``.
textfsm_template
The path to a certain the TextFSM template.
This can be specified using the absolute path
to the file, or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
.. versionadded:: 2018.3.0
textfsm_template_dict
A dictionary with the mapping between a command
and the corresponding TextFSM path to use to extract the data.
The TextFSM paths can be specified as in ``textfsm_template``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``napalm_cli_textfsm_template_dict``.
platform_grain_name: ``os``
The name of the grain used to identify the platform name
in the TextFSM index file. Default: ``os``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_grain``.
platform_column_name: ``Platform``
The column name used to identify the platform,
exactly as specified in the TextFSM index file.
Default: ``Platform``.
.. versionadded:: 2018.3.0
.. note::
This is field is case sensitive, make sure
to assign the correct value to this option,
exactly as defined in the index file.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_column_name``.
index_file: ``index``
The name of the TextFSM index file, under the ``textfsm_path``. Default: ``index``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_index_file``.
saltenv: ``base``
Salt fileserver envrionment from which to retrieve the file.
Ignored if ``textfsm_path`` is not a ``salt://`` URL.
.. versionadded:: 2018.3.0
include_empty: ``False``
Include empty files under the ``textfsm_path``.
.. versionadded:: 2018.3.0
include_pat
Glob or regex to narrow down the files cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. versionadded:: 2018.3.0
exclude_pat
Glob or regex to exclude certain files from being cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. versionadded:: 2018.3.0
.. note::
If used with ``include_pat``, files matching this pattern will be
excluded from the subset of files defined by ``include_pat``.
CLI Example:
.. code-block:: bash
salt '*' net.cli "show version" "show chassis fan"
CLI Example with TextFSM template:
.. code-block:: bash
salt '*' net.cli textfsm_parse=True textfsm_path=salt://textfsm/
Example output:
.. code-block:: python
{
'show version and haiku': 'Hostname: re0.edge01.arn01
Model: mx480
Junos: 13.3R6.5
Help me, Obi-Wan
I just saw Episode Two
You're my only hope
',
'show chassis fan' : 'Item Status RPM Measurement
Top Rear Fan OK 3840 Spinning at intermediate-speed
Bottom Rear Fan OK 3840 Spinning at intermediate-speed
Top Middle Fan OK 3900 Spinning at intermediate-speed
Bottom Middle Fan OK 3840 Spinning at intermediate-speed
Top Front Fan OK 3810 Spinning at intermediate-speed
Bottom Front Fan OK 3840 Spinning at intermediate-speed
'
}
Example output with TextFSM parsing:
.. code-block:: json
{
"comment": "",
"result": true,
"out": {
"sh ver": [
{
"kernel": "9.1S3.5",
"documentation": "9.1S3.5",
"boot": "9.1S3.5",
"crypto": "9.1S3.5",
"chassis": "",
"routing": "9.1S3.5",
"base": "9.1S3.5",
"model": "mx960"
}
]
}
}
'''
raw_cli_outputs = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'cli',
**{
'commands': list(commands)
}
)
# thus we can display the output as is
# in case of errors, they'll be catched in the proxy
if not raw_cli_outputs['result']:
# Error -> dispaly the output as-is.
return raw_cli_outputs
textfsm_parse = kwargs.get('textfsm_parse') or __opts__.get('napalm_cli_textfsm_parse') or\
__pillar__.get('napalm_cli_textfsm_parse', False)
if not textfsm_parse:
# No TextFSM parsing required, return raw commands.
log.debug('No TextFSM parsing requested.')
return raw_cli_outputs
if 'textfsm.extract' not in __salt__ or 'textfsm.index' not in __salt__:
raw_cli_outputs['comment'] += 'Unable to process: is TextFSM installed?'
log.error(raw_cli_outputs['comment'])
return raw_cli_outputs
textfsm_template = kwargs.get('textfsm_template')
log.debug('textfsm_template: %s', textfsm_template)
textfsm_path = kwargs.get('textfsm_path') or __opts__.get('textfsm_path') or\
__pillar__.get('textfsm_path')
log.debug('textfsm_path: %s', textfsm_path)
textfsm_template_dict = kwargs.get('textfsm_template_dict') or __opts__.get('napalm_cli_textfsm_template_dict') or\
__pillar__.get('napalm_cli_textfsm_template_dict', {})
log.debug('TextFSM command-template mapping: %s', textfsm_template_dict)
index_file = kwargs.get('index_file') or __opts__.get('textfsm_index_file') or\
__pillar__.get('textfsm_index_file')
log.debug('index_file: %s', index_file)
platform_grain_name = kwargs.get('platform_grain_name') or __opts__.get('textfsm_platform_grain') or\
__pillar__.get('textfsm_platform_grain', 'os')
log.debug('platform_grain_name: %s', platform_grain_name)
platform_column_name = kwargs.get('platform_column_name') or __opts__.get('textfsm_platform_column_name') or\
__pillar__.get('textfsm_platform_column_name', 'Platform')
log.debug('platform_column_name: %s', platform_column_name)
saltenv = kwargs.get('saltenv', 'base')
include_empty = kwargs.get('include_empty', False)
include_pat = kwargs.get('include_pat')
exclude_pat = kwargs.get('exclude_pat')
processed_cli_outputs = {
'comment': raw_cli_outputs.get('comment', ''),
'result': raw_cli_outputs['result'],
'out': {}
}
log.debug('Starting to analyse the raw outputs')
for command in list(commands):
command_output = raw_cli_outputs['out'][command]
log.debug('Output from command: %s', command)
log.debug(command_output)
processed_command_output = None
if textfsm_path:
log.debug('Using the templates under %s', textfsm_path)
processed_cli_output = __salt__['textfsm.index'](command,
platform_grain_name=platform_grain_name,
platform_column_name=platform_column_name,
output=command_output.strip(),
textfsm_path=textfsm_path,
saltenv=saltenv,
include_empty=include_empty,
include_pat=include_pat,
exclude_pat=exclude_pat)
log.debug('Processed CLI output:')
log.debug(processed_cli_output)
if not processed_cli_output['result']:
log.debug('Apparently this didnt work, returnin the raw output')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {0}: {1}.'.format(command,
processed_cli_output['comment'])
log.error(processed_cli_outputs['comment'])
elif processed_cli_output['out']:
log.debug('All good, %s has a nice output!', command)
processed_command_output = processed_cli_output['out']
else:
comment = '''\nProcessing "{}" didn't fail, but didn't return anything either. Dumping raw.'''.format(
command)
processed_cli_outputs['comment'] += comment
log.error(comment)
processed_command_output = command_output
elif textfsm_template or command in textfsm_template_dict:
if command in textfsm_template_dict:
textfsm_template = textfsm_template_dict[command]
log.debug('Using %s to process the command: %s', textfsm_template, command)
processed_cli_output = __salt__['textfsm.extract'](textfsm_template,
raw_text=command_output,
saltenv=saltenv)
log.debug('Processed CLI output:')
log.debug(processed_cli_output)
if not processed_cli_output['result']:
log.debug('Apparently this didnt work, returning '
'the raw output')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {0}: {1}'.format(command,
processed_cli_output['comment'])
log.error(processed_cli_outputs['comment'])
elif processed_cli_output['out']:
log.debug('All good, %s has a nice output!', command)
processed_command_output = processed_cli_output['out']
else:
log.debug('Processing %s didnt fail, but didnt return'
' anything either. Dumping raw.', command)
processed_command_output = command_output
else:
log.error('No TextFSM template specified, or no TextFSM path defined')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {}.'.format(command)
processed_cli_outputs['out'][command] = processed_command_output
processed_cli_outputs['comment'] = processed_cli_outputs['comment'].strip()
return processed_cli_outputs
@salt.utils.napalm.proxy_napalm_wrap
def traceroute(destination, source=None, ttl=None, timeout=None, vrf=None, **kwargs): # pylint: disable=unused-argument
'''
Calls the method traceroute from the NAPALM driver object and returns a dictionary with the result of the traceroute
command executed on the device.
destination
Hostname or address of remote host
source
Source address to use in outgoing traceroute packets
ttl
IP maximum time-to-live value (or IPv6 maximum hop-limit value)
timeout
Number of seconds to wait for response (seconds)
vrf
VRF (routing instance) for traceroute attempt
.. versionadded:: 2016.11.4
CLI Example:
.. code-block:: bash
salt '*' net.traceroute 8.8.8.8
salt '*' net.traceroute 8.8.8.8 source=127.0.0.1 ttl=5 timeout=1
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'traceroute',
**{
'destination': destination,
'source': source,
'ttl': ttl,
'timeout': timeout,
'vrf': vrf
}
)
@salt.utils.napalm.proxy_napalm_wrap
def ping(destination, source=None, ttl=None, timeout=None, size=None, count=None, vrf=None, **kwargs): # pylint: disable=unused-argument
'''
Executes a ping on the network device and returns a dictionary as a result.
destination
Hostname or IP address of remote host
source
Source address of echo request
ttl
IP time-to-live value (IPv6 hop-limit value) (1..255 hops)
timeout
Maximum wait time after sending final packet (seconds)
size
Size of request packets (0..65468 bytes)
count
Number of ping requests to send (1..2000000000 packets)
vrf
VRF (routing instance) for ping attempt
.. versionadded:: 2016.11.4
CLI Example:
.. code-block:: bash
salt '*' net.ping 8.8.8.8
salt '*' net.ping 8.8.8.8 ttl=3 size=65468
salt '*' net.ping 8.8.8.8 source=127.0.0.1 timeout=1 count=100
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'ping',
**{
'destination': destination,
'source': source,
'ttl': ttl,
'timeout': timeout,
'size': size,
'count': count,
'vrf': vrf
}
)
@salt.utils.napalm.proxy_napalm_wrap
def arp(interface='', ipaddr='', macaddr='', **kwargs): # pylint: disable=unused-argument
'''
NAPALM returns a list of dictionaries with details of the ARP entries.
:param interface: interface name to filter on
:param ipaddr: IP address to filter on
:param macaddr: MAC address to filter on
:return: List of the entries in the ARP table
CLI Example:
.. code-block:: bash
salt '*' net.arp
salt '*' net.arp macaddr='5c:5e:ab:da:3c:f0'
Example output:
.. code-block:: python
[
{
'interface' : 'MgmtEth0/RSP0/CPU0/0',
'mac' : '5c:5e:ab:da:3c:f0',
'ip' : '172.17.17.1',
'age' : 1454496274.84
},
{
'interface': 'MgmtEth0/RSP0/CPU0/0',
'mac' : '66:0e:94:96:e0:ff',
'ip' : '172.17.17.2',
'age' : 1435641582.49
}
]
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_arp_table',
**{
}
)
if not proxy_output.get('result'):
return proxy_output
arp_table = proxy_output.get('out')
if interface:
arp_table = _filter_list(arp_table, 'interface', interface)
if ipaddr:
arp_table = _filter_list(arp_table, 'ip', ipaddr)
if macaddr:
arp_table = _filter_list(arp_table, 'mac', macaddr)
proxy_output.update({
'out': arp_table
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def ipaddrs(**kwargs): # pylint: disable=unused-argument
'''
Returns IP addresses configured on the device.
:return: A dictionary with the IPv4 and IPv6 addresses of the interfaces.
Returns all configured IP addresses on all interfaces as a dictionary
of dictionaries. Keys of the main dictionary represent the name of the
interface. Values of the main dictionary represent are dictionaries
that may consist of two keys 'ipv4' and 'ipv6' (one, both or none)
which are themselvs dictionaries with the IP addresses as keys.
CLI Example:
.. code-block:: bash
salt '*' net.ipaddrs
Example output:
.. code-block:: python
{
'FastEthernet8': {
'ipv4': {
'10.66.43.169': {
'prefix_length': 22
}
}
},
'Loopback555': {
'ipv4': {
'192.168.1.1': {
'prefix_length': 24
}
},
'ipv6': {
'1::1': {
'prefix_length': 64
},
'2001:DB8:1::1': {
'prefix_length': 64
},
'FE80::3': {
'prefix_length': 'N/A'
}
}
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_interfaces_ip',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def interfaces(**kwargs): # pylint: disable=unused-argument
'''
Returns details of the interfaces on the device.
:return: Returns a dictionary of dictionaries. The keys for the first
dictionary will be the interfaces in the devices.
CLI Example:
.. code-block:: bash
salt '*' net.interfaces
Example output:
.. code-block:: python
{
'Management1': {
'is_up': False,
'is_enabled': False,
'description': '',
'last_flapped': -1,
'speed': 1000,
'mac_address': 'dead:beef:dead',
},
'Ethernet1':{
'is_up': True,
'is_enabled': True,
'description': 'foo',
'last_flapped': 1429978575.1554043,
'speed': 1000,
'mac_address': 'beef:dead:beef',
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_interfaces',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def lldp(interface='', **kwargs): # pylint: disable=unused-argument
'''
Returns a detailed view of the LLDP neighbors.
:param interface: interface name to filter on
:return: A dictionary with the LLDL neighbors. The keys are the
interfaces with LLDP activated on.
CLI Example:
.. code-block:: bash
salt '*' net.lldp
salt '*' net.lldp interface='TenGigE0/0/0/8'
Example output:
.. code-block:: python
{
'TenGigE0/0/0/8': [
{
'parent_interface': 'Bundle-Ether8',
'interface_description': 'TenGigE0/0/0/8',
'remote_chassis_id': '8c60.4f69.e96c',
'remote_system_name': 'switch',
'remote_port': 'Eth2/2/1',
'remote_port_description': 'Ethernet2/2/1',
'remote_system_description': 'Cisco Nexus Operating System (NX-OS) Software 7.1(0)N1(1a)
TAC support: http://www.cisco.com/tac
Copyright (c) 2002-2015, Cisco Systems, Inc. All rights reserved.',
'remote_system_capab': 'B, R',
'remote_system_enable_capab': 'B'
}
]
}
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_lldp_neighbors_detail',
**{
}
)
if not proxy_output.get('result'):
return proxy_output
lldp_neighbors = proxy_output.get('out')
if interface:
lldp_neighbors = {interface: lldp_neighbors.get(interface)}
proxy_output.update({
'out': lldp_neighbors
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def mac(address='', interface='', vlan=0, **kwargs): # pylint: disable=unused-argument
'''
Returns the MAC Address Table on the device.
:param address: MAC address to filter on
:param interface: Interface name to filter on
:param vlan: VLAN identifier
:return: A list of dictionaries representing the entries in the MAC Address Table
CLI Example:
.. code-block:: bash
salt '*' net.mac
salt '*' net.mac vlan=10
Example output:
.. code-block:: python
[
{
'mac' : '00:1c:58:29:4a:71',
'interface' : 'xe-3/0/2',
'static' : False,
'active' : True,
'moves' : 1,
'vlan' : 10,
'last_move' : 1454417742.58
},
{
'mac' : '8c:60:4f:58:e1:c1',
'interface' : 'xe-1/0/1',
'static' : False,
'active' : True,
'moves' : 2,
'vlan' : 42,
'last_move' : 1453191948.11
}
]
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_mac_address_table',
**{
}
)
if not proxy_output.get('result'):
# if negative, leave the output unchanged
return proxy_output
mac_address_table = proxy_output.get('out')
if vlan and isinstance(vlan, int):
mac_address_table = _filter_list(mac_address_table, 'vlan', vlan)
if address:
mac_address_table = _filter_list(mac_address_table, 'mac', address)
if interface:
mac_address_table = _filter_list(mac_address_table, 'interface', interface)
proxy_output.update({
'out': mac_address_table
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def config(source=None, **kwargs): # pylint: disable=unused-argument
'''
.. versionadded:: 2017.7.0
Return the whole configuration of the network device. By default, it will
return all possible configuration sources supported by the network device.
At most, there will be:
- running config
- startup config
- candidate config
To return only one of the configurations, you can use the ``source``
argument.
source
Which configuration type you want to display, default is all of them.
Options:
- running
- candidate
- startup
:return:
The object returned is a dictionary with the following keys:
- running (string): Representation of the native running configuration.
- candidate (string): Representation of the native candidate configuration.
If the device doesn't differentiate between running and startup
configuration this will an empty string.
- startup (string): Representation of the native startup configuration.
If the device doesn't differentiate between running and startup
configuration this will an empty string.
CLI Example:
.. code-block:: bash
salt '*' net.config
salt '*' net.config source=candidate
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_config',
**{
'retrieve': source
}
)
@salt.utils.napalm.proxy_napalm_wrap
def optics(**kwargs): # pylint: disable=unused-argument
'''
.. versionadded:: 2017.7.0
Fetches the power usage on the various transceivers installed
on the network device (in dBm), and returns a view that conforms with the
OpenConfig model openconfig-platform-transceiver.yang.
:return:
Returns a dictionary where the keys are as listed below:
* intf_name (unicode)
* physical_channels
* channels (list of dicts)
* index (int)
* state
* input_power
* instant (float)
* avg (float)
* min (float)
* max (float)
* output_power
* instant (float)
* avg (float)
* min (float)
* max (float)
* laser_bias_current
* instant (float)
* avg (float)
* min (float)
* max (float)
CLI Example:
.. code-block:: bash
salt '*' net.optics
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_optics',
**{
}
)
# <---- Call NAPALM getters --------------------------------------------------------------------------------------------
# ----- Configuration specific functions ------------------------------------------------------------------------------>
@salt.utils.napalm.proxy_napalm_wrap
def load_config(filename=None,
text=None,
test=False,
commit=True,
debug=False,
replace=False,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
commit_jid=None,
inherit_napalm_device=None,
saltenv='base',
**kwargs): # pylint: disable=unused-argument
'''
Applies configuration changes on the device. It can be loaded from a file or from inline string.
If you send both a filename and a string containing the configuration, the file has higher precedence.
By default this function will commit the changes. If there are no changes, it does not commit and
the flag ``already_configured`` will be set as ``True`` to point this out.
To avoid committing the configuration, set the argument ``test`` to ``True`` and will discard (dry run).
To keep the changes but not commit, set ``commit`` to ``False``.
To replace the config, set ``replace`` to ``True``.
filename
Path to the file containing the desired configuration.
This can be specified using the absolute path to the file,
or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
.. versionchanged:: 2018.3.0
text
String containing the desired configuration.
This argument is ignored when ``filename`` is specified.
test: False
Dry run? If set as ``True``, will apply the config, discard and return the changes. Default: ``False``
and will commit the changes on the device.
commit: True
Commit? Default: ``True``.
debug: False
Debug mode. Will insert a new key under the output dictionary, as ``loaded_config`` containing the raw
configuration loaded on the device.
.. versionadded:: 2016.11.2
replace: False
Load and replace the configuration. Default: ``False``.
.. versionadded:: 2016.11.2
commit_in: ``None``
Commit the changes in a specific number of minutes / hours. Example of
accepted formats: ``5`` (commit in 5 minutes), ``2m`` (commit in 2
minutes), ``1h`` (commit the changes in 1 hour)`, ``5h30m`` (commit
the changes in 5 hours and 30 minutes).
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
commit_at: ``None``
Commit the changes at a specific time. Example of accepted formats:
``1am`` (will commit the changes at the next 1AM), ``13:20`` (will
commit at 13:20), ``1:20am``, etc.
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
revert_in: ``None``
Commit and revert the changes in a specific number of minutes / hours.
Example of accepted formats: ``5`` (revert in 5 minutes), ``2m`` (revert
in 2 minutes), ``1h`` (revert the changes in 1 hour)`, ``5h30m`` (revert
the changes in 5 hours and 30 minutes).
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
revert_at: ``None``
Commit and revert the changes at a specific time. Example of accepted
formats: ``1am`` (will commit and revert the changes at the next 1AM),
``13:20`` (will commit and revert at 13:20), ``1:20am``, etc.
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
saltenv: ``base``
Specifies the Salt environment name.
.. versionadded:: 2018.3.0
:return: a dictionary having the following keys:
* result (bool): if the config was applied successfully. It is ``False`` only in case of failure. In case \
there are no changes to be applied and successfully performs all operations it is still ``True`` and so will be \
the ``already_configured`` flag (example below)
* comment (str): a message for the user
* already_configured (bool): flag to check if there were no changes applied
* loaded_config (str): the configuration loaded on the device. Requires ``debug`` to be set as ``True``
* diff (str): returns the config changes applied
CLI Example:
.. code-block:: bash
salt '*' net.load_config text='ntp peer 192.168.0.1'
salt '*' net.load_config filename='/absolute/path/to/your/file'
salt '*' net.load_config filename='/absolute/path/to/your/file' test=True
salt '*' net.load_config filename='/absolute/path/to/your/file' commit=False
Example output:
.. code-block:: python
{
'comment': 'Configuration discarded.',
'already_configured': False,
'result': True,
'diff': '[edit interfaces xe-0/0/5]+ description "Adding a description";'
}
'''
fun = 'load_merge_candidate'
if replace:
fun = 'load_replace_candidate'
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
if filename:
text = __salt__['cp.get_file_str'](filename, saltenv=saltenv)
if text is False:
# When using salt:// or https://, if the resource is not available,
# it will either raise an exception, or return False.
ret = {
'result': False,
'out': None
}
ret['comment'] = 'Unable to read from {}. Please specify a valid file or text.'.format(filename)
log.error(ret['comment'])
return ret
if commit_jid:
# When the commit_jid argument is passed, it probably is a scheduled
# commit to be executed, and filename is a temporary file which
# can be removed after reading it.
salt.utils.files.safe_rm(filename)
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
fun,
**{
'config': text
}
)
return _config_logic(napalm_device, # pylint: disable=undefined-variable
_loaded,
test=test,
debug=debug,
replace=replace,
commit_config=commit,
loaded_config=text,
commit_at=commit_at,
commit_in=commit_in,
revert_in=revert_in,
revert_at=revert_at,
commit_jid=commit_jid,
**kwargs)
@salt.utils.napalm.proxy_napalm_wrap
def load_template(template_name=None,
template_source=None,
context=None,
defaults=None,
template_engine='jinja',
saltenv='base',
template_hash=None,
template_hash_name=None,
skip_verify=False,
test=False,
commit=True,
debug=False,
replace=False,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
inherit_napalm_device=None, # pylint: disable=unused-argument
**template_vars):
'''
Renders a configuration template (default: Jinja) and loads the result on the device.
By default this function will commit the changes. If there are no changes,
it does not commit, discards he config and the flag ``already_configured``
will be set as ``True`` to point this out.
To avoid committing the configuration, set the argument ``test`` to ``True``
and will discard (dry run).
To preserve the changes, set ``commit`` to ``False``.
However, this is recommended to be used only in exceptional cases
when there are applied few consecutive states
and/or configuration changes.
Otherwise the user might forget that the config DB is locked
and the candidate config buffer is not cleared/merged in the running config.
To replace the config, set ``replace`` to ``True``.
template_name
Identifies path to the template source.
The template can be either stored on the local machine, either remotely.
The recommended location is under the ``file_roots``
as specified in the master config file.
For example, let's suppose the ``file_roots`` is configured as:
.. code-block:: yaml
file_roots:
base:
- /etc/salt/states
Placing the template under ``/etc/salt/states/templates/example.jinja``,
it can be used as ``salt://templates/example.jinja``.
Alternatively, for local files, the user can specify the absolute path.
If remotely, the source can be retrieved via ``http``, ``https`` or ``ftp``.
Examples:
- ``salt://my_template.jinja``
- ``/absolute/path/to/my_template.jinja``
- ``http://example.com/template.cheetah``
- ``https:/example.com/template.mako``
- ``ftp://example.com/template.py``
.. versionchanged:: 2019.2.0
This argument can now support a list of templates to be rendered.
The resulting configuration text is loaded at once, as a single
configuration chunk.
template_source: None
Inline config template to be rendered and loaded on the device.
template_hash: None
Hash of the template file. Format: ``{hash_type: 'md5', 'hsum': <md5sum>}``
.. versionadded:: 2016.11.2
context: None
Overrides default context variables passed to the template.
.. versionadded:: 2019.2.0
template_hash_name: None
When ``template_hash`` refers to a remote file,
this specifies the filename to look for in that file.
.. versionadded:: 2016.11.2
saltenv: ``base``
Specifies the template environment.
This will influence the relative imports inside the templates.
.. versionadded:: 2016.11.2
template_engine: jinja
The following templates engines are supported:
- :mod:`cheetah<salt.renderers.cheetah>`
- :mod:`genshi<salt.renderers.genshi>`
- :mod:`jinja<salt.renderers.jinja>`
- :mod:`mako<salt.renderers.mako>`
- :mod:`py<salt.renderers.py>`
- :mod:`wempy<salt.renderers.wempy>`
.. versionadded:: 2016.11.2
skip_verify: True
If ``True``, hash verification of remote file sources
(``http://``, ``https://``, ``ftp://``) will be skipped,
and the ``source_hash`` argument will be ignored.
.. versionadded:: 2016.11.2
test: False
Dry run? If set to ``True``, will apply the config,
discard and return the changes.
Default: ``False`` and will commit the changes on the device.
commit: True
Commit? (default: ``True``)
debug: False
Debug mode. Will insert a new key under the output dictionary,
as ``loaded_config`` containing the raw result after the template was rendered.
.. versionadded:: 2016.11.2
replace: False
Load and replace the configuration.
.. versionadded:: 2016.11.2
commit_in: ``None``
Commit the changes in a specific number of minutes / hours. Example of
accepted formats: ``5`` (commit in 5 minutes), ``2m`` (commit in 2
minutes), ``1h`` (commit the changes in 1 hour)`, ``5h30m`` (commit
the changes in 5 hours and 30 minutes).
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
commit_at: ``None``
Commit the changes at a specific time. Example of accepted formats:
``1am`` (will commit the changes at the next 1AM), ``13:20`` (will
commit at 13:20), ``1:20am``, etc.
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
revert_in: ``None``
Commit and revert the changes in a specific number of minutes / hours.
Example of accepted formats: ``5`` (revert in 5 minutes), ``2m`` (revert
in 2 minutes), ``1h`` (revert the changes in 1 hour)`, ``5h30m`` (revert
the changes in 5 hours and 30 minutes).
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
revert_at: ``None``
Commit and revert the changes at a specific time. Example of accepted
formats: ``1am`` (will commit and revert the changes at the next 1AM),
``13:20`` (will commit and revert at 13:20), ``1:20am``, etc.
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
defaults: None
Default variables/context passed to the template.
.. versionadded:: 2016.11.2
template_vars
Dictionary with the arguments/context to be used when the template is rendered.
.. note::
Do not explicitly specify this argument. This represents any other
variable that will be sent to the template rendering system.
Please see the examples below!
.. note::
It is more recommended to use the ``context`` argument to avoid
conflicts between CLI arguments and template variables.
:return: a dictionary having the following keys:
- result (bool): if the config was applied successfully. It is ``False``
only in case of failure. In case there are no changes to be applied and
successfully performs all operations it is still ``True`` and so will be
the ``already_configured`` flag (example below)
- comment (str): a message for the user
- already_configured (bool): flag to check if there were no changes applied
- loaded_config (str): the configuration loaded on the device, after
rendering the template. Requires ``debug`` to be set as ``True``
- diff (str): returns the config changes applied
The template can use variables from the ``grains``, ``pillar`` or ``opts``, for example:
.. code-block:: jinja
{% set router_model = grains.get('model') -%}
{% set router_vendor = grains.get('vendor') -%}
{% set os_version = grains.get('version') -%}
{% set hostname = pillar.get('proxy', {}).get('host') -%}
{% if router_vendor|lower == 'juniper' %}
system {
host-name {{hostname}};
}
{% elif router_vendor|lower == 'cisco' %}
hostname {{hostname}}
{% endif %}
CLI Examples:
.. code-block:: bash
salt '*' net.load_template set_ntp_peers peers=[192.168.0.1] # uses NAPALM default templates
# inline template:
salt -G 'os:junos' net.load_template template_source='system { host-name {{host_name}}; }' \
host_name='MX480.lab'
# inline template using grains info:
salt -G 'os:junos' net.load_template \
template_source='system { host-name {{grains.model}}.lab; }'
# if the device is a MX480, the command above will set the hostname as: MX480.lab
# inline template using pillar data:
salt -G 'os:junos' net.load_template template_source='system { host-name {{pillar.proxy.host}}; }'
salt '*' net.load_template https://bit.ly/2OhSgqP hostname=example # will commit
salt '*' net.load_template https://bit.ly/2OhSgqP hostname=example test=True # dry run
salt '*' net.load_template salt://templates/example.jinja debug=True # Using the salt:// URI
# render a mako template:
salt '*' net.load_template salt://templates/example.mako template_engine=mako debug=True
# render remote template
salt -G 'os:junos' net.load_template http://bit.ly/2fReJg7 test=True debug=True peers=['192.168.0.1']
salt -G 'os:ios' net.load_template http://bit.ly/2gKOj20 test=True debug=True peers=['192.168.0.1']
# render multiple templates at once
salt '*' net.load_template "['https://bit.ly/2OhSgqP', 'salt://templates/example.jinja']" context="{'hostname': 'example'}"
Example output:
.. code-block:: python
{
'comment': '',
'already_configured': False,
'result': True,
'diff': '[edit system]+ host-name edge01.bjm01',
'loaded_config': 'system { host-name edge01.bjm01; }''
}
'''
_rendered = ''
_loaded = {
'result': True,
'comment': '',
'out': None
}
loaded_config = None
# prechecks
deprecated_args = ('template_user', 'template_attrs', 'template_group', 'template_mode')
for deprecated_arg in deprecated_args:
if template_vars.get(deprecated_arg):
del template_vars[deprecated_arg]
salt.utils.versions.warn_until(
'Sodium',
('The \'{arg}\' argument to \'net.load_template\' is deprecated '
'and has been ignored').format(arg=deprecated_arg)
)
if template_engine not in salt.utils.templates.TEMPLATE_REGISTRY:
_loaded.update({
'result': False,
'comment': 'Invalid templating engine! Choose between: {tpl_eng_opts}'.format(
tpl_eng_opts=', '.join(list(salt.utils.templates.TEMPLATE_REGISTRY.keys()))
)
})
return _loaded # exit
# to check if will be rendered by salt or NAPALM
salt_render_prefixes = ('salt://', 'http://', 'https://', 'ftp://')
salt_render = False
file_exists = False
if not isinstance(template_name, (tuple, list)):
for salt_render_prefix in salt_render_prefixes:
if not salt_render:
salt_render = salt_render or template_name.startswith(salt_render_prefix)
file_exists = __salt__['file.file_exists'](template_name)
if template_source or file_exists or salt_render or isinstance(template_name, (tuple, list)):
# either inline template
# either template in a custom path
# either abs path send
# either starts with salt:// and
# then use Salt render system
if context is None:
context = {}
context.update(template_vars)
# if needed to render the template send as inline arg
if template_source:
# render the content
_rendered = __salt__['file.apply_template_on_contents'](
contents=template_source,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv
)
if not isinstance(_rendered, six.string_types):
if 'result' in _rendered:
_loaded['result'] = _rendered['result']
else:
_loaded['result'] = False
if 'comment' in _rendered:
_loaded['comment'] = _rendered['comment']
else:
_loaded['comment'] = 'Error while rendering the template.'
return _loaded
else:
# render the file - either local, either remote
if not isinstance(template_name, (list, tuple)):
template_name = [template_name]
if template_hash_name and not isinstance(template_hash_name, (list, tuple)):
template_hash_name = [template_hash_name]
elif not template_hash_name:
template_hash_name = [None] * len(template_name)
if template_hash and isinstance(template_hash, six.string_types) and not\
(template_hash.startswith('salt://') or template_hash.startswith('file://')):
# If the template hash is passed as string, and it's not a file
# (starts with the salt:// or file:// URI), then make it a list
# of 1 element (for the iteration below)
template_hash = [template_hash]
elif template_hash and isinstance(template_hash, six.string_types) and\
(template_hash.startswith('salt://') or template_hash.startswith('file://')):
# If the template hash is a file URI, then provide the same value
# for each of the templates in the list, as probably they all
# share the same hash file, otherwise the user should provide
# this as a list
template_hash = [template_hash] * len(template_name)
elif not template_hash:
template_hash = [None] * len(template_name)
for tpl_index, tpl_name in enumerate(template_name):
tpl_hash = template_hash[tpl_index]
tpl_hash_name = template_hash_name[tpl_index]
_rand_filename = __salt__['random.hash'](tpl_name, 'md5')
_temp_file = __salt__['file.join']('/tmp', _rand_filename)
_managed = __salt__['file.get_managed'](name=_temp_file,
source=tpl_name,
source_hash=tpl_hash,
source_hash_name=tpl_hash_name,
user=None,
group=None,
mode=None,
attrs=None,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv,
skip_verify=skip_verify)
if not isinstance(_managed, (list, tuple)) and isinstance(_managed, six.string_types):
_loaded['comment'] += _managed
_loaded['result'] = False
elif isinstance(_managed, (list, tuple)) and not _managed:
_loaded['result'] = False
_loaded['comment'] += 'Error while rendering the template.'
elif isinstance(_managed, (list, tuple)) and not _managed[0]:
_loaded['result'] = False
_loaded['comment'] += _managed[-1] # contains the error message
if _loaded['result']: # all good
_temp_tpl_file = _managed[0]
_temp_tpl_file_exists = __salt__['file.file_exists'](_temp_tpl_file)
if not _temp_tpl_file_exists:
_loaded['result'] = False
_loaded['comment'] += 'Error while rendering the template.'
return _loaded
_rendered += __salt__['file.read'](_temp_tpl_file)
__salt__['file.remove'](_temp_tpl_file)
else:
return _loaded # exit
loaded_config = _rendered
if _loaded['result']: # all good
fun = 'load_merge_candidate'
if replace: # replace requested
fun = 'load_replace_candidate'
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
fun,
**{
'config': _rendered
}
)
else:
salt.utils.versions.warn_until(
'Sodium',
'Native NAPALM templates support will be removed in the Sodium '
'release. Please consider using the Salt rendering pipeline instead.'
'If you are using the \'netntp\', \'netsnmp\', or \'netusers\' Salt '
'State modules, you can ignore this message'
)
# otherwise, use NAPALM render system, injecting pillar/grains/opts vars
load_templates_params = defaults if defaults else {}
load_templates_params.update(template_vars)
load_templates_params.update(
{
'template_name': template_name,
'template_source': template_source, # inline template
'pillar': __pillar__, # inject pillar content
'grains': __grains__, # inject grains content
'opts': __opts__ # inject opts content
}
)
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
# so we'll set the CLOSE global explicitly as False
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'load_template',
**load_templates_params
)
return _config_logic(napalm_device, # pylint: disable=undefined-variable
_loaded,
test=test,
debug=debug,
replace=replace,
commit_config=commit,
loaded_config=loaded_config,
commit_at=commit_at,
commit_in=commit_in,
revert_in=revert_in,
revert_at=revert_at,
**template_vars)
@salt.utils.napalm.proxy_napalm_wrap
def commit(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Commits the configuration changes made on the network device.
CLI Example:
.. code-block:: bash
salt '*' net.commit
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'commit_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def discard_config(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
"""
Discards the changes applied.
CLI Example:
.. code-block:: bash
salt '*' net.discard_config
"""
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'discard_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def compare_config(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Returns the difference between the running config and the candidate config.
CLI Example:
.. code-block:: bash
salt '*' net.compare_config
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'compare_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def rollback(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Rollbacks the configuration.
CLI Example:
.. code-block:: bash
salt '*' net.rollback
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'rollback',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def config_changed(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Will prompt if the configuration has been changed.
:return: A tuple with a boolean that specifies if the config was changed on the device.\
And a string that provides more details of the reason why the configuration was not changed.
CLI Example:
.. code-block:: bash
salt '*' net.config_changed
'''
is_config_changed = False
reason = ''
try_compare = compare_config(inherit_napalm_device=napalm_device) # pylint: disable=undefined-variable
if try_compare.get('result'):
if try_compare.get('out'):
is_config_changed = True
else:
reason = 'Configuration was not changed on the device.'
else:
reason = try_compare.get('comment')
return is_config_changed, reason
@salt.utils.napalm.proxy_napalm_wrap
def config_control(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Will check if the configuration was changed.
If differences found, will try to commit.
In case commit unsuccessful, will try to rollback.
:return: A tuple with a boolean that specifies if the config was changed/committed/rollbacked on the device.\
And a string that provides more details of the reason why the configuration was not committed properly.
CLI Example:
.. code-block:: bash
salt '*' net.config_control
'''
result = True
comment = ''
changed, not_changed_rsn = config_changed(inherit_napalm_device=napalm_device) # pylint: disable=undefined-variable
if not changed:
return (changed, not_changed_rsn)
# config changed, thus let's try to commit
try_commit = commit()
if not try_commit.get('result'):
result = False
comment = 'Unable to commit the changes: {reason}.\n\
Will try to rollback now!'.format(
reason=try_commit.get('comment')
)
try_rollback = rollback()
if not try_rollback.get('result'):
comment += '\nCannot rollback! {reason}'.format(
reason=try_rollback.get('comment')
)
return result, comment
def cancel_commit(jid):
'''
.. versionadded:: 2019.2.0
Cancel a commit scheduled to be executed via the ``commit_in`` and
``commit_at`` arguments from the
:py:func:`net.load_template <salt.modules.napalm_network.load_template>` or
:py:func:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit ID is displayed when the commit is scheduled
via the functions named above.
CLI Example:
.. code-block:: bash
salt '*' net.cancel_commit 20180726083540640360
'''
job_name = '__napalm_commit_{}'.format(jid)
removed = __salt__['schedule.delete'](job_name)
if removed['result']:
saved = __salt__['schedule.save']()
removed['comment'] = 'Commit #{jid} cancelled.'.format(jid=jid)
else:
removed['comment'] = 'Unable to find commit #{jid}.'.format(jid=jid)
return removed
def confirm_commit(jid):
'''
.. versionadded:: 2019.2.0
Confirm a commit scheduled to be reverted via the ``revert_in`` and
``revert_at`` arguments from the
:mod:`net.load_template <salt.modules.napalm_network.load_template>` or
:mod:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit ID is displayed when the commit confirmed
is scheduled via the functions named above.
CLI Example:
.. code-block:: bash
salt '*' net.confirm_commit 20180726083540640360
'''
if __grains__['os'] == 'junos':
# Confirm the commit, by committing (i.e., invoking the RPC call)
confirmed = __salt__['napalm.junos_commit']()
confirmed['result'] = confirmed.pop('out')
confirmed['comment'] = confirmed.pop('message')
else:
confirmed = cancel_commit(jid)
if confirmed['result']:
confirmed['comment'] = 'Commit #{jid} confirmed.'.format(jid=jid)
return confirmed
def save_config(source=None,
path=None):
'''
.. versionadded:: 2019.2.0
Save the configuration to a file on the local file system.
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``,
``startup``. Default: ``running``.
path
Absolute path to file where to save the configuration.
To push the files to the Master, use
:mod:`cp.push <salt.modules.cp.push>` Execution function.
CLI Example:
.. code-block:: bash
salt '*' net.save_config source=running
'''
if not source:
source = 'running'
if not path:
path = salt.utils.files.mkstemp()
running_config = __salt__['net.config'](source=source)
if not running_config or not running_config['result']:
log.error('Unable to retrieve the config')
return running_config
with salt.utils.files.fopen(path, 'w') as fh_:
fh_.write(running_config['out'][source])
return {
'result': True,
'out': path,
'comment': '{source} config saved to {path}'.format(source=source, path=path)
}
def replace_pattern(pattern,
repl,
count=0,
flags=8,
bufsize=1,
append_if_not_found=False,
prepend_if_not_found=False,
not_found_content=None,
search_only=False,
show_changes=True,
backslash_literal=False,
source=None,
path=None,
test=False,
replace=True,
debug=False,
commit=True):
'''
.. versionadded:: 2019.2.0
Replace occurrences of a pattern in the configuration source. If
``show_changes`` is ``True``, then a diff of what changed will be returned,
otherwise a ``True`` will be returned when changes are made, and ``False``
when no changes are made.
This is a pure Python implementation that wraps Python's :py:func:`~re.sub`.
pattern
A regular expression, to be matched using Python's
:py:func:`~re.search`.
repl
The replacement text.
count: ``0``
Maximum number of pattern occurrences to be replaced. If count is a
positive integer ``n``, only ``n`` occurrences will be replaced,
otherwise all occurrences will be replaced.
flags (list or int): ``8``
A list of flags defined in the ``re`` module documentation from the
Python standard library. Each list item should be a string that will
correlate to the human-friendly flag name. E.g., ``['IGNORECASE',
'MULTILINE']``. Optionally, ``flags`` may be an int, with a value
corresponding to the XOR (``|``) of all the desired flags. Defaults to
8 (which supports 'MULTILINE').
bufsize (int or str): ``1``
How much of the configuration to buffer into memory at once. The
default value ``1`` processes one line at a time. The special value
``file`` may be specified which will read the entire file into memory
before processing.
append_if_not_found: ``False``
If set to ``True``, and pattern is not found, then the content will be
appended to the file.
prepend_if_not_found: ``False``
If set to ``True`` and pattern is not found, then the content will be
prepended to the file.
not_found_content
Content to use for append/prepend if not found. If None (default), uses
``repl``. Useful when ``repl`` uses references to group in pattern.
search_only: ``False``
If set to true, this no changes will be performed on the file, and this
function will simply return ``True`` if the pattern was matched, and
``False`` if not.
show_changes: ``True``
If ``True``, return a diff of changes made. Otherwise, return ``True``
if changes were made, and ``False`` if not.
backslash_literal: ``False``
Interpret backslashes as literal backslashes for the repl and not
escape characters. This will help when using append/prepend so that
the backslashes are not interpreted for the repl on the second run of
the state.
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path
Save the temporary configuration to a specific path, then read from
there.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' net.replace_pattern "bind-address\\s*=" "bind-address:"
CLI Example:
.. code-block:: bash
salt '*' net.replace_pattern PREFIX-LIST_NAME new-prefix-list-name
salt '*' net.replace_pattern bgp-group-name new-bgp-group-name count=1
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
replace_pattern = __salt__['file.replace'](path,
pattern,
repl,
count=count,
flags=flags,
bufsize=bufsize,
append_if_not_found=append_if_not_found,
prepend_if_not_found=prepend_if_not_found,
not_found_content=not_found_content,
search_only=search_only,
show_changes=show_changes,
backslash_literal=backslash_literal)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
def patch(patchfile,
options='',
saltenv='base',
source_hash=None,
show_changes=True,
source='running',
path=None,
test=False,
commit=True,
debug=False,
replace=True):
'''
.. versionadded:: 2019.2.0
Apply a patch to the configuration source, and load the result into the
running config of the device.
patchfile
A patch file to apply to the configuration source.
options
Options to pass to patch.
source_hash
If the patch file (specified via the ``patchfile`` argument) is an
HTTP(S) or FTP URL and the file exists in the minion's file cache, this
option can be passed to keep the minion from re-downloading the file if
the cached copy matches the specified hash.
show_changes: ``True``
Controls how changes are presented. If ``True``, this function will
return the of the changes made.
If ``False``, then it will return a boolean (``True`` if any changes
were made, otherwise False).
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path: ``None``
Save the temporary configuration to a specific path, then read from
there. This argument is optional, can the user prefers a particular
location of the temporary file.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
CLI Example:
.. code-block:: bash
salt '*' net.patch https://example.com/running_config.patch
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
patchfile_cache = __salt__['cp.cache_file'](patchfile)
if patchfile_cache is False:
return {
'out': None,
'result': False,
'comment': 'The file "{}" does not exist.'.format(patchfile)
}
replace_pattern = __salt__['file.patch'](path,
patchfile_cache,
options=options)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
# <---- Configuration specific functions -------------------------------------------------------------------------------
|
saltstack/salt
|
salt/modules/napalm_network.py
|
patch
|
python
|
def patch(patchfile,
options='',
saltenv='base',
source_hash=None,
show_changes=True,
source='running',
path=None,
test=False,
commit=True,
debug=False,
replace=True):
'''
.. versionadded:: 2019.2.0
Apply a patch to the configuration source, and load the result into the
running config of the device.
patchfile
A patch file to apply to the configuration source.
options
Options to pass to patch.
source_hash
If the patch file (specified via the ``patchfile`` argument) is an
HTTP(S) or FTP URL and the file exists in the minion's file cache, this
option can be passed to keep the minion from re-downloading the file if
the cached copy matches the specified hash.
show_changes: ``True``
Controls how changes are presented. If ``True``, this function will
return the of the changes made.
If ``False``, then it will return a boolean (``True`` if any changes
were made, otherwise False).
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path: ``None``
Save the temporary configuration to a specific path, then read from
there. This argument is optional, can the user prefers a particular
location of the temporary file.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
CLI Example:
.. code-block:: bash
salt '*' net.patch https://example.com/running_config.patch
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
patchfile_cache = __salt__['cp.cache_file'](patchfile)
if patchfile_cache is False:
return {
'out': None,
'result': False,
'comment': 'The file "{}" does not exist.'.format(patchfile)
}
replace_pattern = __salt__['file.patch'](path,
patchfile_cache,
options=options)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
|
.. versionadded:: 2019.2.0
Apply a patch to the configuration source, and load the result into the
running config of the device.
patchfile
A patch file to apply to the configuration source.
options
Options to pass to patch.
source_hash
If the patch file (specified via the ``patchfile`` argument) is an
HTTP(S) or FTP URL and the file exists in the minion's file cache, this
option can be passed to keep the minion from re-downloading the file if
the cached copy matches the specified hash.
show_changes: ``True``
Controls how changes are presented. If ``True``, this function will
return the of the changes made.
If ``False``, then it will return a boolean (``True`` if any changes
were made, otherwise False).
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path: ``None``
Save the temporary configuration to a specific path, then read from
there. This argument is optional, can the user prefers a particular
location of the temporary file.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
CLI Example:
.. code-block:: bash
salt '*' net.patch https://example.com/running_config.patch
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_network.py#L2585-L2670
|
[
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n",
"def save_config(source=None,\n path=None):\n '''\n .. versionadded:: 2019.2.0\n\n Save the configuration to a file on the local file system.\n\n source: ``running``\n The configuration source. Choose from: ``running``, ``candidate``,\n ``startup``. Default: ``running``.\n\n path\n Absolute path to file where to save the configuration.\n To push the files to the Master, use\n :mod:`cp.push <salt.modules.cp.push>` Execution function.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' net.save_config source=running\n '''\n if not source:\n source = 'running'\n if not path:\n path = salt.utils.files.mkstemp()\n running_config = __salt__['net.config'](source=source)\n if not running_config or not running_config['result']:\n log.error('Unable to retrieve the config')\n return running_config\n with salt.utils.files.fopen(path, 'w') as fh_:\n fh_.write(running_config['out'][source])\n return {\n 'result': True,\n 'out': path,\n 'comment': '{source} config saved to {path}'.format(source=source, path=path)\n }\n"
] |
# -*- coding: utf-8 -*-
'''
NAPALM Network
==============
Basic methods for interaction with the network device through the virtual proxy 'napalm'.
:codeauthor: Mircea Ulinic <mircea@cloudflare.com> & Jerome Fleury <jf@cloudflare.com>
:maturity: new
:depends: napalm
:platform: unix
Dependencies
------------
- :mod:`napalm proxy minion <salt.proxy.napalm>`
.. versionadded:: 2016.11.0
.. versionchanged:: 2017.7.0
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import time
import logging
import datetime
log = logging.getLogger(__name__)
# Import Salt libs
from salt.ext import six
import salt.utils.files
import salt.utils.napalm
import salt.utils.versions
import salt.utils.templates
# Import 3rd-party libs
try:
import jxmlease # pylint: disable=unused-import
HAS_JXMLEASE = True
except ImportError:
HAS_JXMLEASE = False
# ----------------------------------------------------------------------------------------------------------------------
# module properties
# ----------------------------------------------------------------------------------------------------------------------
__virtualname__ = 'net'
__proxyenabled__ = ['*']
__virtual_aliases__ = ('napalm_net',)
# uses NAPALM-based proxy to interact with network devices
# ----------------------------------------------------------------------------------------------------------------------
# property functions
# ----------------------------------------------------------------------------------------------------------------------
def __virtual__():
'''
NAPALM library must be installed for this module to work and run in a (proxy) minion.
'''
return salt.utils.napalm.virtual(__opts__, __virtualname__, __file__)
# ----------------------------------------------------------------------------------------------------------------------
# helper functions -- will not be exported
# ----------------------------------------------------------------------------------------------------------------------
def _filter_list(input_list, search_key, search_value):
'''
Filters a list of dictionary by a set of key-value pair.
:param input_list: is a list of dictionaries
:param search_key: is the key we are looking for
:param search_value: is the value we are looking for the key specified in search_key
:return: filered list of dictionaries
'''
output_list = list()
for dictionary in input_list:
if dictionary.get(search_key) == search_value:
output_list.append(dictionary)
return output_list
def _filter_dict(input_dict, search_key, search_value):
'''
Filters a dictionary of dictionaries by a key-value pair.
:param input_dict: is a dictionary whose values are lists of dictionaries
:param search_key: is the key in the leaf dictionaries
:param search_values: is the value in the leaf dictionaries
:return: filtered dictionary
'''
output_dict = dict()
for key, key_list in six.iteritems(input_dict):
key_list_filtered = _filter_list(key_list, search_key, search_value)
if key_list_filtered:
output_dict[key] = key_list_filtered
return output_dict
def _safe_commit_config(loaded_result, napalm_device):
_commit = commit(inherit_napalm_device=napalm_device) # calls the function commit, defined below
if not _commit.get('result', False):
# if unable to commit
loaded_result['comment'] += _commit['comment'] if _commit.get('comment') else 'Unable to commit.'
loaded_result['result'] = False
# unable to commit, something went wrong
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
return _commit
def _safe_dicard_config(loaded_result, napalm_device):
'''
'''
log.debug('Discarding the config')
log.debug(loaded_result)
_discarded = discard_config(inherit_napalm_device=napalm_device)
if not _discarded.get('result', False):
loaded_result['comment'] += _discarded['comment'] if _discarded.get('comment') \
else 'Unable to discard config.'
loaded_result['result'] = False
# make sure it notifies
# that something went wrong
_explicit_close(napalm_device)
__context__['retcode'] = 1
return loaded_result
return _discarded
def _explicit_close(napalm_device):
'''
Will explicily close the config session with the network device,
when running in a now-always-alive proxy minion or regular minion.
This helper must be used in configuration-related functions,
as the session is preserved and not closed before making any changes.
'''
if salt.utils.napalm.not_always_alive(__opts__):
# force closing the configuration session
# when running in a non-always-alive proxy
# or regular minion
try:
napalm_device['DRIVER'].close()
except Exception as err:
log.error('Unable to close the temp connection with the device:')
log.error(err)
log.error('Please report.')
def _config_logic(napalm_device,
loaded_result,
test=False,
debug=False,
replace=False,
commit_config=True,
loaded_config=None,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
commit_jid=None,
**kwargs):
'''
Builds the config logic for `load_config` and `load_template` functions.
'''
# As the Salt logic is built around independent events
# when it comes to configuration changes in the
# candidate DB on the network devices, we need to
# make sure we're using the same session.
# Hence, we need to pass the same object around.
# the napalm_device object is inherited from
# the load_config or load_template functions
# and forwarded to compare, discard, commit etc.
# then the decorator will make sure that
# if not proxy (when the connection is always alive)
# and the `inherit_napalm_device` is set,
# `napalm_device` will be overridden.
# See `salt.utils.napalm.proxy_napalm_wrap` decorator.
current_jid = kwargs.get('__pub_jid')
if not current_jid:
current_jid = '{0:%Y%m%d%H%M%S%f}'.format(datetime.datetime.now())
loaded_result['already_configured'] = False
loaded_result['loaded_config'] = ''
if debug:
loaded_result['loaded_config'] = loaded_config
_compare = compare_config(inherit_napalm_device=napalm_device)
if _compare.get('result', False):
loaded_result['diff'] = _compare.get('out')
loaded_result.pop('out', '') # not needed
else:
loaded_result['diff'] = None
loaded_result['result'] = False
loaded_result['comment'] = _compare.get('comment')
__context__['retcode'] = 1
return loaded_result
_loaded_res = loaded_result.get('result', False)
if not _loaded_res or test:
# if unable to load the config (errors / warnings)
# or in testing mode,
# will discard the config
if loaded_result['comment']:
loaded_result['comment'] += '\n'
if not loaded_result.get('diff', ''):
loaded_result['already_configured'] = True
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
loaded_result['comment'] += 'Configuration discarded.'
# loaded_result['result'] = False not necessary
# as the result can be true when test=True
_explicit_close(napalm_device)
if not loaded_result['result']:
__context__['retcode'] = 1
return loaded_result
if not test and commit_config:
# if not in testing mode and trying to commit
if commit_jid:
log.info('Committing the JID: %s', str(commit_jid))
removed = cancel_commit(commit_jid)
log.debug('Cleaned up the commit from the schedule')
log.debug(removed['comment'])
if loaded_result.get('diff', ''):
# if not testing mode
# and also the user wants to commit (default)
# and there are changes to commit
if commit_in or commit_at:
commit_time = __utils__['timeutil.get_time_at'](time_in=commit_in,
time_at=commit_in)
# schedule job
scheduled_job_name = '__napalm_commit_{}'.format(current_jid)
temp_file = salt.utils.files.mkstemp()
with salt.utils.files.fopen(temp_file, 'w') as fp_:
fp_.write(loaded_config)
scheduled = __salt__['schedule.add'](scheduled_job_name,
function='net.load_config',
job_kwargs={
'filename': temp_file,
'commit_jid': current_jid,
'replace': replace
},
once=commit_time)
log.debug('Scheduling job')
log.debug(scheduled)
saved = __salt__['schedule.save']() # ensure the schedule is
# persistent cross Minion restart
discarded = _safe_dicard_config(loaded_result, napalm_device)
# discard the changes
if not discarded['result']:
discarded['comment'] += ('Scheduled the job to be executed at {schedule_ts}, '
'but was unable to discard the config: \n').format(schedule_ts=commit_time)
return discarded
loaded_result['comment'] = ('Changes discarded for now, and scheduled commit at: {schedule_ts}.\n'
'The commit ID is: {current_jid}.\n'
'To discard this commit, you can execute: \n\n'
'salt {min_id} net.cancel_commit {current_jid}').format(schedule_ts=commit_time,
min_id=__opts__['id'],
current_jid=current_jid)
loaded_result['commit_id'] = current_jid
return loaded_result
log.debug('About to commit:')
log.debug(loaded_result['diff'])
if revert_in or revert_at:
revert_time = __utils__['timeutil.get_time_at'](time_in=revert_in,
time_at=revert_at)
if __grains__['os'] == 'junos':
if not HAS_JXMLEASE:
loaded_result['comment'] = ('This feature requires the library jxmlease to be installed.\n'
'To install, please execute: ``pip install jxmlease``.')
loaded_result['result'] = False
return loaded_result
timestamp_at = __utils__['timeutil.get_timestamp_at'](time_in=revert_in,
time_at=revert_at)
minutes = int((timestamp_at - time.time())/60)
_comm = __salt__['napalm.junos_commit'](confirm=minutes)
if not _comm['out']:
# If unable to commit confirm, should try to bail out
loaded_result['comment'] = 'Unable to commit confirm: {}'.format(_comm['message'])
loaded_result['result'] = False
# But before exiting, we must gracefully discard the config
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
else:
temp_file = salt.utils.files.mkstemp()
running_config = __salt__['net.config'](source='running')['out']['running']
with salt.utils.files.fopen(temp_file, 'w') as fp_:
fp_.write(running_config)
committed = _safe_commit_config(loaded_result, napalm_device)
if not committed['result']:
# If unable to commit, dicard the config (which is
# already done by the _safe_commit_config function), and
# return with the command and other details.
return loaded_result
scheduled_job_name = '__napalm_commit_{}'.format(current_jid)
scheduled = __salt__['schedule.add'](scheduled_job_name,
function='net.load_config',
job_kwargs={
'filename': temp_file,
'commit_jid': current_jid,
'replace': True
},
once=revert_time)
log.debug('Scheduling commit confirmed')
log.debug(scheduled)
saved = __salt__['schedule.save']()
loaded_result['comment'] = ('The commit ID is: {current_jid}.\n'
'This commit will be reverted at: {schedule_ts}, unless confirmed.\n'
'To confirm the commit and avoid reverting, you can execute:\n\n'
'salt {min_id} net.confirm_commit {current_jid}').format(schedule_ts=revert_time,
min_id=__opts__['id'],
current_jid=current_jid)
loaded_result['commit_id'] = current_jid
return loaded_result
committed = _safe_commit_config(loaded_result, napalm_device)
if not committed['result']:
return loaded_result
else:
# would like to commit, but there's no change
# need to call discard_config() to release the config DB
discarded = _safe_dicard_config(loaded_result, napalm_device)
if not discarded['result']:
return loaded_result
loaded_result['already_configured'] = True
loaded_result['comment'] = 'Already configured.'
_explicit_close(napalm_device)
if not loaded_result['result']:
__context__['retcode'] = 1
return loaded_result
# ----------------------------------------------------------------------------------------------------------------------
# callable functions
# ----------------------------------------------------------------------------------------------------------------------
@salt.utils.napalm.proxy_napalm_wrap
def connected(**kwargs): # pylint: disable=unused-argument
'''
Specifies if the connection to the device succeeded.
CLI Example:
.. code-block:: bash
salt '*' net.connected
'''
return {
'out': napalm_device.get('UP', False) # pylint: disable=undefined-variable
}
@salt.utils.napalm.proxy_napalm_wrap
def facts(**kwargs): # pylint: disable=unused-argument
'''
Returns characteristics of the network device.
:return: a dictionary with the following keys:
* uptime - Uptime of the device in seconds.
* vendor - Manufacturer of the device.
* model - Device model.
* hostname - Hostname of the device
* fqdn - Fqdn of the device
* os_version - String with the OS version running on the device.
* serial_number - Serial number of the device
* interface_list - List of the interfaces of the device
CLI Example:
.. code-block:: bash
salt '*' net.facts
Example output:
.. code-block:: python
{
'os_version': '13.3R6.5',
'uptime': 10117140,
'interface_list': [
'lc-0/0/0',
'pfe-0/0/0',
'pfh-0/0/0',
'xe-0/0/0',
'xe-0/0/1',
'xe-0/0/2',
'xe-0/0/3',
'gr-0/0/10',
'ip-0/0/10'
],
'vendor': 'Juniper',
'serial_number': 'JN131356FBFA',
'model': 'MX480',
'hostname': 're0.edge05.syd01',
'fqdn': 're0.edge05.syd01'
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_facts',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def environment(**kwargs): # pylint: disable=unused-argument
'''
Returns the environment of the device.
CLI Example:
.. code-block:: bash
salt '*' net.environment
Example output:
.. code-block:: python
{
'fans': {
'Bottom Rear Fan': {
'status': True
},
'Bottom Middle Fan': {
'status': True
},
'Top Middle Fan': {
'status': True
},
'Bottom Front Fan': {
'status': True
},
'Top Front Fan': {
'status': True
},
'Top Rear Fan': {
'status': True
}
},
'memory': {
'available_ram': 16349,
'used_ram': 4934
},
'temperature': {
'FPC 0 Exhaust A': {
'is_alert': False,
'temperature': 35.0,
'is_critical': False
}
},
'cpu': {
'1': {
'%usage': 19.0
},
'0': {
'%usage': 35.0
}
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_environment',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def cli(*commands, **kwargs): # pylint: disable=unused-argument
'''
Returns a dictionary with the raw output of all commands passed as arguments.
commands
List of commands to be executed on the device.
textfsm_parse: ``False``
Try parsing the outputs using the TextFSM templates.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``napalm_cli_textfsm_parse``.
textfsm_path
The path where the TextFSM templates can be found. This option implies
the usage of the TextFSM index file.
``textfsm_path`` can be either absolute path on the server,
either specified using the following URL mschemes: ``file://``,
``salt://``, ``http://``, ``https://``, ``ftp://``,
``s3://``, ``swift://``.
.. versionadded:: 2018.3.0
.. note::
This needs to be a directory with a flat structure, having an
index file (whose name can be specified using the ``index_file`` option)
and a number of TextFSM templates.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_path``.
textfsm_template
The path to a certain the TextFSM template.
This can be specified using the absolute path
to the file, or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
.. versionadded:: 2018.3.0
textfsm_template_dict
A dictionary with the mapping between a command
and the corresponding TextFSM path to use to extract the data.
The TextFSM paths can be specified as in ``textfsm_template``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``napalm_cli_textfsm_template_dict``.
platform_grain_name: ``os``
The name of the grain used to identify the platform name
in the TextFSM index file. Default: ``os``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_grain``.
platform_column_name: ``Platform``
The column name used to identify the platform,
exactly as specified in the TextFSM index file.
Default: ``Platform``.
.. versionadded:: 2018.3.0
.. note::
This is field is case sensitive, make sure
to assign the correct value to this option,
exactly as defined in the index file.
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_platform_column_name``.
index_file: ``index``
The name of the TextFSM index file, under the ``textfsm_path``. Default: ``index``.
.. versionadded:: 2018.3.0
.. note::
This option can be also specified in the minion configuration
file or pillar as ``textfsm_index_file``.
saltenv: ``base``
Salt fileserver envrionment from which to retrieve the file.
Ignored if ``textfsm_path`` is not a ``salt://`` URL.
.. versionadded:: 2018.3.0
include_empty: ``False``
Include empty files under the ``textfsm_path``.
.. versionadded:: 2018.3.0
include_pat
Glob or regex to narrow down the files cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. versionadded:: 2018.3.0
exclude_pat
Glob or regex to exclude certain files from being cached from the given path.
If matching with a regex, the regex must be prefixed with ``E@``,
otherwise the expression will be interpreted as a glob.
.. versionadded:: 2018.3.0
.. note::
If used with ``include_pat``, files matching this pattern will be
excluded from the subset of files defined by ``include_pat``.
CLI Example:
.. code-block:: bash
salt '*' net.cli "show version" "show chassis fan"
CLI Example with TextFSM template:
.. code-block:: bash
salt '*' net.cli textfsm_parse=True textfsm_path=salt://textfsm/
Example output:
.. code-block:: python
{
'show version and haiku': 'Hostname: re0.edge01.arn01
Model: mx480
Junos: 13.3R6.5
Help me, Obi-Wan
I just saw Episode Two
You're my only hope
',
'show chassis fan' : 'Item Status RPM Measurement
Top Rear Fan OK 3840 Spinning at intermediate-speed
Bottom Rear Fan OK 3840 Spinning at intermediate-speed
Top Middle Fan OK 3900 Spinning at intermediate-speed
Bottom Middle Fan OK 3840 Spinning at intermediate-speed
Top Front Fan OK 3810 Spinning at intermediate-speed
Bottom Front Fan OK 3840 Spinning at intermediate-speed
'
}
Example output with TextFSM parsing:
.. code-block:: json
{
"comment": "",
"result": true,
"out": {
"sh ver": [
{
"kernel": "9.1S3.5",
"documentation": "9.1S3.5",
"boot": "9.1S3.5",
"crypto": "9.1S3.5",
"chassis": "",
"routing": "9.1S3.5",
"base": "9.1S3.5",
"model": "mx960"
}
]
}
}
'''
raw_cli_outputs = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'cli',
**{
'commands': list(commands)
}
)
# thus we can display the output as is
# in case of errors, they'll be catched in the proxy
if not raw_cli_outputs['result']:
# Error -> dispaly the output as-is.
return raw_cli_outputs
textfsm_parse = kwargs.get('textfsm_parse') or __opts__.get('napalm_cli_textfsm_parse') or\
__pillar__.get('napalm_cli_textfsm_parse', False)
if not textfsm_parse:
# No TextFSM parsing required, return raw commands.
log.debug('No TextFSM parsing requested.')
return raw_cli_outputs
if 'textfsm.extract' not in __salt__ or 'textfsm.index' not in __salt__:
raw_cli_outputs['comment'] += 'Unable to process: is TextFSM installed?'
log.error(raw_cli_outputs['comment'])
return raw_cli_outputs
textfsm_template = kwargs.get('textfsm_template')
log.debug('textfsm_template: %s', textfsm_template)
textfsm_path = kwargs.get('textfsm_path') or __opts__.get('textfsm_path') or\
__pillar__.get('textfsm_path')
log.debug('textfsm_path: %s', textfsm_path)
textfsm_template_dict = kwargs.get('textfsm_template_dict') or __opts__.get('napalm_cli_textfsm_template_dict') or\
__pillar__.get('napalm_cli_textfsm_template_dict', {})
log.debug('TextFSM command-template mapping: %s', textfsm_template_dict)
index_file = kwargs.get('index_file') or __opts__.get('textfsm_index_file') or\
__pillar__.get('textfsm_index_file')
log.debug('index_file: %s', index_file)
platform_grain_name = kwargs.get('platform_grain_name') or __opts__.get('textfsm_platform_grain') or\
__pillar__.get('textfsm_platform_grain', 'os')
log.debug('platform_grain_name: %s', platform_grain_name)
platform_column_name = kwargs.get('platform_column_name') or __opts__.get('textfsm_platform_column_name') or\
__pillar__.get('textfsm_platform_column_name', 'Platform')
log.debug('platform_column_name: %s', platform_column_name)
saltenv = kwargs.get('saltenv', 'base')
include_empty = kwargs.get('include_empty', False)
include_pat = kwargs.get('include_pat')
exclude_pat = kwargs.get('exclude_pat')
processed_cli_outputs = {
'comment': raw_cli_outputs.get('comment', ''),
'result': raw_cli_outputs['result'],
'out': {}
}
log.debug('Starting to analyse the raw outputs')
for command in list(commands):
command_output = raw_cli_outputs['out'][command]
log.debug('Output from command: %s', command)
log.debug(command_output)
processed_command_output = None
if textfsm_path:
log.debug('Using the templates under %s', textfsm_path)
processed_cli_output = __salt__['textfsm.index'](command,
platform_grain_name=platform_grain_name,
platform_column_name=platform_column_name,
output=command_output.strip(),
textfsm_path=textfsm_path,
saltenv=saltenv,
include_empty=include_empty,
include_pat=include_pat,
exclude_pat=exclude_pat)
log.debug('Processed CLI output:')
log.debug(processed_cli_output)
if not processed_cli_output['result']:
log.debug('Apparently this didnt work, returnin the raw output')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {0}: {1}.'.format(command,
processed_cli_output['comment'])
log.error(processed_cli_outputs['comment'])
elif processed_cli_output['out']:
log.debug('All good, %s has a nice output!', command)
processed_command_output = processed_cli_output['out']
else:
comment = '''\nProcessing "{}" didn't fail, but didn't return anything either. Dumping raw.'''.format(
command)
processed_cli_outputs['comment'] += comment
log.error(comment)
processed_command_output = command_output
elif textfsm_template or command in textfsm_template_dict:
if command in textfsm_template_dict:
textfsm_template = textfsm_template_dict[command]
log.debug('Using %s to process the command: %s', textfsm_template, command)
processed_cli_output = __salt__['textfsm.extract'](textfsm_template,
raw_text=command_output,
saltenv=saltenv)
log.debug('Processed CLI output:')
log.debug(processed_cli_output)
if not processed_cli_output['result']:
log.debug('Apparently this didnt work, returning '
'the raw output')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {0}: {1}'.format(command,
processed_cli_output['comment'])
log.error(processed_cli_outputs['comment'])
elif processed_cli_output['out']:
log.debug('All good, %s has a nice output!', command)
processed_command_output = processed_cli_output['out']
else:
log.debug('Processing %s didnt fail, but didnt return'
' anything either. Dumping raw.', command)
processed_command_output = command_output
else:
log.error('No TextFSM template specified, or no TextFSM path defined')
processed_command_output = command_output
processed_cli_outputs['comment'] += '\nUnable to process the output from {}.'.format(command)
processed_cli_outputs['out'][command] = processed_command_output
processed_cli_outputs['comment'] = processed_cli_outputs['comment'].strip()
return processed_cli_outputs
@salt.utils.napalm.proxy_napalm_wrap
def traceroute(destination, source=None, ttl=None, timeout=None, vrf=None, **kwargs): # pylint: disable=unused-argument
'''
Calls the method traceroute from the NAPALM driver object and returns a dictionary with the result of the traceroute
command executed on the device.
destination
Hostname or address of remote host
source
Source address to use in outgoing traceroute packets
ttl
IP maximum time-to-live value (or IPv6 maximum hop-limit value)
timeout
Number of seconds to wait for response (seconds)
vrf
VRF (routing instance) for traceroute attempt
.. versionadded:: 2016.11.4
CLI Example:
.. code-block:: bash
salt '*' net.traceroute 8.8.8.8
salt '*' net.traceroute 8.8.8.8 source=127.0.0.1 ttl=5 timeout=1
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'traceroute',
**{
'destination': destination,
'source': source,
'ttl': ttl,
'timeout': timeout,
'vrf': vrf
}
)
@salt.utils.napalm.proxy_napalm_wrap
def ping(destination, source=None, ttl=None, timeout=None, size=None, count=None, vrf=None, **kwargs): # pylint: disable=unused-argument
'''
Executes a ping on the network device and returns a dictionary as a result.
destination
Hostname or IP address of remote host
source
Source address of echo request
ttl
IP time-to-live value (IPv6 hop-limit value) (1..255 hops)
timeout
Maximum wait time after sending final packet (seconds)
size
Size of request packets (0..65468 bytes)
count
Number of ping requests to send (1..2000000000 packets)
vrf
VRF (routing instance) for ping attempt
.. versionadded:: 2016.11.4
CLI Example:
.. code-block:: bash
salt '*' net.ping 8.8.8.8
salt '*' net.ping 8.8.8.8 ttl=3 size=65468
salt '*' net.ping 8.8.8.8 source=127.0.0.1 timeout=1 count=100
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'ping',
**{
'destination': destination,
'source': source,
'ttl': ttl,
'timeout': timeout,
'size': size,
'count': count,
'vrf': vrf
}
)
@salt.utils.napalm.proxy_napalm_wrap
def arp(interface='', ipaddr='', macaddr='', **kwargs): # pylint: disable=unused-argument
'''
NAPALM returns a list of dictionaries with details of the ARP entries.
:param interface: interface name to filter on
:param ipaddr: IP address to filter on
:param macaddr: MAC address to filter on
:return: List of the entries in the ARP table
CLI Example:
.. code-block:: bash
salt '*' net.arp
salt '*' net.arp macaddr='5c:5e:ab:da:3c:f0'
Example output:
.. code-block:: python
[
{
'interface' : 'MgmtEth0/RSP0/CPU0/0',
'mac' : '5c:5e:ab:da:3c:f0',
'ip' : '172.17.17.1',
'age' : 1454496274.84
},
{
'interface': 'MgmtEth0/RSP0/CPU0/0',
'mac' : '66:0e:94:96:e0:ff',
'ip' : '172.17.17.2',
'age' : 1435641582.49
}
]
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_arp_table',
**{
}
)
if not proxy_output.get('result'):
return proxy_output
arp_table = proxy_output.get('out')
if interface:
arp_table = _filter_list(arp_table, 'interface', interface)
if ipaddr:
arp_table = _filter_list(arp_table, 'ip', ipaddr)
if macaddr:
arp_table = _filter_list(arp_table, 'mac', macaddr)
proxy_output.update({
'out': arp_table
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def ipaddrs(**kwargs): # pylint: disable=unused-argument
'''
Returns IP addresses configured on the device.
:return: A dictionary with the IPv4 and IPv6 addresses of the interfaces.
Returns all configured IP addresses on all interfaces as a dictionary
of dictionaries. Keys of the main dictionary represent the name of the
interface. Values of the main dictionary represent are dictionaries
that may consist of two keys 'ipv4' and 'ipv6' (one, both or none)
which are themselvs dictionaries with the IP addresses as keys.
CLI Example:
.. code-block:: bash
salt '*' net.ipaddrs
Example output:
.. code-block:: python
{
'FastEthernet8': {
'ipv4': {
'10.66.43.169': {
'prefix_length': 22
}
}
},
'Loopback555': {
'ipv4': {
'192.168.1.1': {
'prefix_length': 24
}
},
'ipv6': {
'1::1': {
'prefix_length': 64
},
'2001:DB8:1::1': {
'prefix_length': 64
},
'FE80::3': {
'prefix_length': 'N/A'
}
}
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_interfaces_ip',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def interfaces(**kwargs): # pylint: disable=unused-argument
'''
Returns details of the interfaces on the device.
:return: Returns a dictionary of dictionaries. The keys for the first
dictionary will be the interfaces in the devices.
CLI Example:
.. code-block:: bash
salt '*' net.interfaces
Example output:
.. code-block:: python
{
'Management1': {
'is_up': False,
'is_enabled': False,
'description': '',
'last_flapped': -1,
'speed': 1000,
'mac_address': 'dead:beef:dead',
},
'Ethernet1':{
'is_up': True,
'is_enabled': True,
'description': 'foo',
'last_flapped': 1429978575.1554043,
'speed': 1000,
'mac_address': 'beef:dead:beef',
}
}
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_interfaces',
**{
}
)
@salt.utils.napalm.proxy_napalm_wrap
def lldp(interface='', **kwargs): # pylint: disable=unused-argument
'''
Returns a detailed view of the LLDP neighbors.
:param interface: interface name to filter on
:return: A dictionary with the LLDL neighbors. The keys are the
interfaces with LLDP activated on.
CLI Example:
.. code-block:: bash
salt '*' net.lldp
salt '*' net.lldp interface='TenGigE0/0/0/8'
Example output:
.. code-block:: python
{
'TenGigE0/0/0/8': [
{
'parent_interface': 'Bundle-Ether8',
'interface_description': 'TenGigE0/0/0/8',
'remote_chassis_id': '8c60.4f69.e96c',
'remote_system_name': 'switch',
'remote_port': 'Eth2/2/1',
'remote_port_description': 'Ethernet2/2/1',
'remote_system_description': 'Cisco Nexus Operating System (NX-OS) Software 7.1(0)N1(1a)
TAC support: http://www.cisco.com/tac
Copyright (c) 2002-2015, Cisco Systems, Inc. All rights reserved.',
'remote_system_capab': 'B, R',
'remote_system_enable_capab': 'B'
}
]
}
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_lldp_neighbors_detail',
**{
}
)
if not proxy_output.get('result'):
return proxy_output
lldp_neighbors = proxy_output.get('out')
if interface:
lldp_neighbors = {interface: lldp_neighbors.get(interface)}
proxy_output.update({
'out': lldp_neighbors
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def mac(address='', interface='', vlan=0, **kwargs): # pylint: disable=unused-argument
'''
Returns the MAC Address Table on the device.
:param address: MAC address to filter on
:param interface: Interface name to filter on
:param vlan: VLAN identifier
:return: A list of dictionaries representing the entries in the MAC Address Table
CLI Example:
.. code-block:: bash
salt '*' net.mac
salt '*' net.mac vlan=10
Example output:
.. code-block:: python
[
{
'mac' : '00:1c:58:29:4a:71',
'interface' : 'xe-3/0/2',
'static' : False,
'active' : True,
'moves' : 1,
'vlan' : 10,
'last_move' : 1454417742.58
},
{
'mac' : '8c:60:4f:58:e1:c1',
'interface' : 'xe-1/0/1',
'static' : False,
'active' : True,
'moves' : 2,
'vlan' : 42,
'last_move' : 1453191948.11
}
]
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_mac_address_table',
**{
}
)
if not proxy_output.get('result'):
# if negative, leave the output unchanged
return proxy_output
mac_address_table = proxy_output.get('out')
if vlan and isinstance(vlan, int):
mac_address_table = _filter_list(mac_address_table, 'vlan', vlan)
if address:
mac_address_table = _filter_list(mac_address_table, 'mac', address)
if interface:
mac_address_table = _filter_list(mac_address_table, 'interface', interface)
proxy_output.update({
'out': mac_address_table
})
return proxy_output
@salt.utils.napalm.proxy_napalm_wrap
def config(source=None, **kwargs): # pylint: disable=unused-argument
'''
.. versionadded:: 2017.7.0
Return the whole configuration of the network device. By default, it will
return all possible configuration sources supported by the network device.
At most, there will be:
- running config
- startup config
- candidate config
To return only one of the configurations, you can use the ``source``
argument.
source
Which configuration type you want to display, default is all of them.
Options:
- running
- candidate
- startup
:return:
The object returned is a dictionary with the following keys:
- running (string): Representation of the native running configuration.
- candidate (string): Representation of the native candidate configuration.
If the device doesn't differentiate between running and startup
configuration this will an empty string.
- startup (string): Representation of the native startup configuration.
If the device doesn't differentiate between running and startup
configuration this will an empty string.
CLI Example:
.. code-block:: bash
salt '*' net.config
salt '*' net.config source=candidate
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_config',
**{
'retrieve': source
}
)
@salt.utils.napalm.proxy_napalm_wrap
def optics(**kwargs): # pylint: disable=unused-argument
'''
.. versionadded:: 2017.7.0
Fetches the power usage on the various transceivers installed
on the network device (in dBm), and returns a view that conforms with the
OpenConfig model openconfig-platform-transceiver.yang.
:return:
Returns a dictionary where the keys are as listed below:
* intf_name (unicode)
* physical_channels
* channels (list of dicts)
* index (int)
* state
* input_power
* instant (float)
* avg (float)
* min (float)
* max (float)
* output_power
* instant (float)
* avg (float)
* min (float)
* max (float)
* laser_bias_current
* instant (float)
* avg (float)
* min (float)
* max (float)
CLI Example:
.. code-block:: bash
salt '*' net.optics
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_optics',
**{
}
)
# <---- Call NAPALM getters --------------------------------------------------------------------------------------------
# ----- Configuration specific functions ------------------------------------------------------------------------------>
@salt.utils.napalm.proxy_napalm_wrap
def load_config(filename=None,
text=None,
test=False,
commit=True,
debug=False,
replace=False,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
commit_jid=None,
inherit_napalm_device=None,
saltenv='base',
**kwargs): # pylint: disable=unused-argument
'''
Applies configuration changes on the device. It can be loaded from a file or from inline string.
If you send both a filename and a string containing the configuration, the file has higher precedence.
By default this function will commit the changes. If there are no changes, it does not commit and
the flag ``already_configured`` will be set as ``True`` to point this out.
To avoid committing the configuration, set the argument ``test`` to ``True`` and will discard (dry run).
To keep the changes but not commit, set ``commit`` to ``False``.
To replace the config, set ``replace`` to ``True``.
filename
Path to the file containing the desired configuration.
This can be specified using the absolute path to the file,
or using one of the following URL schemes:
- ``salt://``, to fetch the template from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
.. versionchanged:: 2018.3.0
text
String containing the desired configuration.
This argument is ignored when ``filename`` is specified.
test: False
Dry run? If set as ``True``, will apply the config, discard and return the changes. Default: ``False``
and will commit the changes on the device.
commit: True
Commit? Default: ``True``.
debug: False
Debug mode. Will insert a new key under the output dictionary, as ``loaded_config`` containing the raw
configuration loaded on the device.
.. versionadded:: 2016.11.2
replace: False
Load and replace the configuration. Default: ``False``.
.. versionadded:: 2016.11.2
commit_in: ``None``
Commit the changes in a specific number of minutes / hours. Example of
accepted formats: ``5`` (commit in 5 minutes), ``2m`` (commit in 2
minutes), ``1h`` (commit the changes in 1 hour)`, ``5h30m`` (commit
the changes in 5 hours and 30 minutes).
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
commit_at: ``None``
Commit the changes at a specific time. Example of accepted formats:
``1am`` (will commit the changes at the next 1AM), ``13:20`` (will
commit at 13:20), ``1:20am``, etc.
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
revert_in: ``None``
Commit and revert the changes in a specific number of minutes / hours.
Example of accepted formats: ``5`` (revert in 5 minutes), ``2m`` (revert
in 2 minutes), ``1h`` (revert the changes in 1 hour)`, ``5h30m`` (revert
the changes in 5 hours and 30 minutes).
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
revert_at: ``None``
Commit and revert the changes at a specific time. Example of accepted
formats: ``1am`` (will commit and revert the changes at the next 1AM),
``13:20`` (will commit and revert at 13:20), ``1:20am``, etc.
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
saltenv: ``base``
Specifies the Salt environment name.
.. versionadded:: 2018.3.0
:return: a dictionary having the following keys:
* result (bool): if the config was applied successfully. It is ``False`` only in case of failure. In case \
there are no changes to be applied and successfully performs all operations it is still ``True`` and so will be \
the ``already_configured`` flag (example below)
* comment (str): a message for the user
* already_configured (bool): flag to check if there were no changes applied
* loaded_config (str): the configuration loaded on the device. Requires ``debug`` to be set as ``True``
* diff (str): returns the config changes applied
CLI Example:
.. code-block:: bash
salt '*' net.load_config text='ntp peer 192.168.0.1'
salt '*' net.load_config filename='/absolute/path/to/your/file'
salt '*' net.load_config filename='/absolute/path/to/your/file' test=True
salt '*' net.load_config filename='/absolute/path/to/your/file' commit=False
Example output:
.. code-block:: python
{
'comment': 'Configuration discarded.',
'already_configured': False,
'result': True,
'diff': '[edit interfaces xe-0/0/5]+ description "Adding a description";'
}
'''
fun = 'load_merge_candidate'
if replace:
fun = 'load_replace_candidate'
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
if filename:
text = __salt__['cp.get_file_str'](filename, saltenv=saltenv)
if text is False:
# When using salt:// or https://, if the resource is not available,
# it will either raise an exception, or return False.
ret = {
'result': False,
'out': None
}
ret['comment'] = 'Unable to read from {}. Please specify a valid file or text.'.format(filename)
log.error(ret['comment'])
return ret
if commit_jid:
# When the commit_jid argument is passed, it probably is a scheduled
# commit to be executed, and filename is a temporary file which
# can be removed after reading it.
salt.utils.files.safe_rm(filename)
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
fun,
**{
'config': text
}
)
return _config_logic(napalm_device, # pylint: disable=undefined-variable
_loaded,
test=test,
debug=debug,
replace=replace,
commit_config=commit,
loaded_config=text,
commit_at=commit_at,
commit_in=commit_in,
revert_in=revert_in,
revert_at=revert_at,
commit_jid=commit_jid,
**kwargs)
@salt.utils.napalm.proxy_napalm_wrap
def load_template(template_name=None,
template_source=None,
context=None,
defaults=None,
template_engine='jinja',
saltenv='base',
template_hash=None,
template_hash_name=None,
skip_verify=False,
test=False,
commit=True,
debug=False,
replace=False,
commit_in=None,
commit_at=None,
revert_in=None,
revert_at=None,
inherit_napalm_device=None, # pylint: disable=unused-argument
**template_vars):
'''
Renders a configuration template (default: Jinja) and loads the result on the device.
By default this function will commit the changes. If there are no changes,
it does not commit, discards he config and the flag ``already_configured``
will be set as ``True`` to point this out.
To avoid committing the configuration, set the argument ``test`` to ``True``
and will discard (dry run).
To preserve the changes, set ``commit`` to ``False``.
However, this is recommended to be used only in exceptional cases
when there are applied few consecutive states
and/or configuration changes.
Otherwise the user might forget that the config DB is locked
and the candidate config buffer is not cleared/merged in the running config.
To replace the config, set ``replace`` to ``True``.
template_name
Identifies path to the template source.
The template can be either stored on the local machine, either remotely.
The recommended location is under the ``file_roots``
as specified in the master config file.
For example, let's suppose the ``file_roots`` is configured as:
.. code-block:: yaml
file_roots:
base:
- /etc/salt/states
Placing the template under ``/etc/salt/states/templates/example.jinja``,
it can be used as ``salt://templates/example.jinja``.
Alternatively, for local files, the user can specify the absolute path.
If remotely, the source can be retrieved via ``http``, ``https`` or ``ftp``.
Examples:
- ``salt://my_template.jinja``
- ``/absolute/path/to/my_template.jinja``
- ``http://example.com/template.cheetah``
- ``https:/example.com/template.mako``
- ``ftp://example.com/template.py``
.. versionchanged:: 2019.2.0
This argument can now support a list of templates to be rendered.
The resulting configuration text is loaded at once, as a single
configuration chunk.
template_source: None
Inline config template to be rendered and loaded on the device.
template_hash: None
Hash of the template file. Format: ``{hash_type: 'md5', 'hsum': <md5sum>}``
.. versionadded:: 2016.11.2
context: None
Overrides default context variables passed to the template.
.. versionadded:: 2019.2.0
template_hash_name: None
When ``template_hash`` refers to a remote file,
this specifies the filename to look for in that file.
.. versionadded:: 2016.11.2
saltenv: ``base``
Specifies the template environment.
This will influence the relative imports inside the templates.
.. versionadded:: 2016.11.2
template_engine: jinja
The following templates engines are supported:
- :mod:`cheetah<salt.renderers.cheetah>`
- :mod:`genshi<salt.renderers.genshi>`
- :mod:`jinja<salt.renderers.jinja>`
- :mod:`mako<salt.renderers.mako>`
- :mod:`py<salt.renderers.py>`
- :mod:`wempy<salt.renderers.wempy>`
.. versionadded:: 2016.11.2
skip_verify: True
If ``True``, hash verification of remote file sources
(``http://``, ``https://``, ``ftp://``) will be skipped,
and the ``source_hash`` argument will be ignored.
.. versionadded:: 2016.11.2
test: False
Dry run? If set to ``True``, will apply the config,
discard and return the changes.
Default: ``False`` and will commit the changes on the device.
commit: True
Commit? (default: ``True``)
debug: False
Debug mode. Will insert a new key under the output dictionary,
as ``loaded_config`` containing the raw result after the template was rendered.
.. versionadded:: 2016.11.2
replace: False
Load and replace the configuration.
.. versionadded:: 2016.11.2
commit_in: ``None``
Commit the changes in a specific number of minutes / hours. Example of
accepted formats: ``5`` (commit in 5 minutes), ``2m`` (commit in 2
minutes), ``1h`` (commit the changes in 1 hour)`, ``5h30m`` (commit
the changes in 5 hours and 30 minutes).
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
commit_at: ``None``
Commit the changes at a specific time. Example of accepted formats:
``1am`` (will commit the changes at the next 1AM), ``13:20`` (will
commit at 13:20), ``1:20am``, etc.
.. note::
This feature works on any platforms, as it does not rely on the
native features of the network operating system.
.. note::
After the command is executed and the ``diff`` is not satisfactory,
or for any other reasons you have to discard the commit, you are
able to do so using the
:py:func:`net.cancel_commit <salt.modules.napalm_network.cancel_commit>`
execution function, using the commit ID returned by this function.
.. warning::
Using this feature, Salt will load the exact configuration you
expect, however the diff may change in time (i.e., if an user
applies a manual configuration change, or a different process or
command changes the configuration in the meanwhile).
.. versionadded:: 2019.2.0
revert_in: ``None``
Commit and revert the changes in a specific number of minutes / hours.
Example of accepted formats: ``5`` (revert in 5 minutes), ``2m`` (revert
in 2 minutes), ``1h`` (revert the changes in 1 hour)`, ``5h30m`` (revert
the changes in 5 hours and 30 minutes).
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
revert_at: ``None``
Commit and revert the changes at a specific time. Example of accepted
formats: ``1am`` (will commit and revert the changes at the next 1AM),
``13:20`` (will commit and revert at 13:20), ``1:20am``, etc.
.. note::
To confirm the commit, and prevent reverting the changes, you will
have to execute the
:mod:`net.confirm_commit <salt.modules.napalm_network.confirm_commit>`
function, using the commit ID returned by this function.
.. warning::
This works on any platform, regardless if they have or don't have
native capabilities to confirming a commit. However, please be
*very* cautious when using this feature: on Junos (as it is the only
NAPALM core platform supporting this natively) it executes a commit
confirmed as you would do from the command line.
All the other platforms don't have this capability natively,
therefore the revert is done via Salt. That means, your device needs
to be reachable at the moment when Salt will attempt to revert your
changes. Be cautious when pushing configuration changes that would
prevent you reach the device.
Similarly, if an user or a different process apply other
configuration changes in the meanwhile (between the moment you
commit and till the changes are reverted), these changes would be
equally reverted, as Salt cannot be aware of them.
.. versionadded:: 2019.2.0
defaults: None
Default variables/context passed to the template.
.. versionadded:: 2016.11.2
template_vars
Dictionary with the arguments/context to be used when the template is rendered.
.. note::
Do not explicitly specify this argument. This represents any other
variable that will be sent to the template rendering system.
Please see the examples below!
.. note::
It is more recommended to use the ``context`` argument to avoid
conflicts between CLI arguments and template variables.
:return: a dictionary having the following keys:
- result (bool): if the config was applied successfully. It is ``False``
only in case of failure. In case there are no changes to be applied and
successfully performs all operations it is still ``True`` and so will be
the ``already_configured`` flag (example below)
- comment (str): a message for the user
- already_configured (bool): flag to check if there were no changes applied
- loaded_config (str): the configuration loaded on the device, after
rendering the template. Requires ``debug`` to be set as ``True``
- diff (str): returns the config changes applied
The template can use variables from the ``grains``, ``pillar`` or ``opts``, for example:
.. code-block:: jinja
{% set router_model = grains.get('model') -%}
{% set router_vendor = grains.get('vendor') -%}
{% set os_version = grains.get('version') -%}
{% set hostname = pillar.get('proxy', {}).get('host') -%}
{% if router_vendor|lower == 'juniper' %}
system {
host-name {{hostname}};
}
{% elif router_vendor|lower == 'cisco' %}
hostname {{hostname}}
{% endif %}
CLI Examples:
.. code-block:: bash
salt '*' net.load_template set_ntp_peers peers=[192.168.0.1] # uses NAPALM default templates
# inline template:
salt -G 'os:junos' net.load_template template_source='system { host-name {{host_name}}; }' \
host_name='MX480.lab'
# inline template using grains info:
salt -G 'os:junos' net.load_template \
template_source='system { host-name {{grains.model}}.lab; }'
# if the device is a MX480, the command above will set the hostname as: MX480.lab
# inline template using pillar data:
salt -G 'os:junos' net.load_template template_source='system { host-name {{pillar.proxy.host}}; }'
salt '*' net.load_template https://bit.ly/2OhSgqP hostname=example # will commit
salt '*' net.load_template https://bit.ly/2OhSgqP hostname=example test=True # dry run
salt '*' net.load_template salt://templates/example.jinja debug=True # Using the salt:// URI
# render a mako template:
salt '*' net.load_template salt://templates/example.mako template_engine=mako debug=True
# render remote template
salt -G 'os:junos' net.load_template http://bit.ly/2fReJg7 test=True debug=True peers=['192.168.0.1']
salt -G 'os:ios' net.load_template http://bit.ly/2gKOj20 test=True debug=True peers=['192.168.0.1']
# render multiple templates at once
salt '*' net.load_template "['https://bit.ly/2OhSgqP', 'salt://templates/example.jinja']" context="{'hostname': 'example'}"
Example output:
.. code-block:: python
{
'comment': '',
'already_configured': False,
'result': True,
'diff': '[edit system]+ host-name edge01.bjm01',
'loaded_config': 'system { host-name edge01.bjm01; }''
}
'''
_rendered = ''
_loaded = {
'result': True,
'comment': '',
'out': None
}
loaded_config = None
# prechecks
deprecated_args = ('template_user', 'template_attrs', 'template_group', 'template_mode')
for deprecated_arg in deprecated_args:
if template_vars.get(deprecated_arg):
del template_vars[deprecated_arg]
salt.utils.versions.warn_until(
'Sodium',
('The \'{arg}\' argument to \'net.load_template\' is deprecated '
'and has been ignored').format(arg=deprecated_arg)
)
if template_engine not in salt.utils.templates.TEMPLATE_REGISTRY:
_loaded.update({
'result': False,
'comment': 'Invalid templating engine! Choose between: {tpl_eng_opts}'.format(
tpl_eng_opts=', '.join(list(salt.utils.templates.TEMPLATE_REGISTRY.keys()))
)
})
return _loaded # exit
# to check if will be rendered by salt or NAPALM
salt_render_prefixes = ('salt://', 'http://', 'https://', 'ftp://')
salt_render = False
file_exists = False
if not isinstance(template_name, (tuple, list)):
for salt_render_prefix in salt_render_prefixes:
if not salt_render:
salt_render = salt_render or template_name.startswith(salt_render_prefix)
file_exists = __salt__['file.file_exists'](template_name)
if template_source or file_exists or salt_render or isinstance(template_name, (tuple, list)):
# either inline template
# either template in a custom path
# either abs path send
# either starts with salt:// and
# then use Salt render system
if context is None:
context = {}
context.update(template_vars)
# if needed to render the template send as inline arg
if template_source:
# render the content
_rendered = __salt__['file.apply_template_on_contents'](
contents=template_source,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv
)
if not isinstance(_rendered, six.string_types):
if 'result' in _rendered:
_loaded['result'] = _rendered['result']
else:
_loaded['result'] = False
if 'comment' in _rendered:
_loaded['comment'] = _rendered['comment']
else:
_loaded['comment'] = 'Error while rendering the template.'
return _loaded
else:
# render the file - either local, either remote
if not isinstance(template_name, (list, tuple)):
template_name = [template_name]
if template_hash_name and not isinstance(template_hash_name, (list, tuple)):
template_hash_name = [template_hash_name]
elif not template_hash_name:
template_hash_name = [None] * len(template_name)
if template_hash and isinstance(template_hash, six.string_types) and not\
(template_hash.startswith('salt://') or template_hash.startswith('file://')):
# If the template hash is passed as string, and it's not a file
# (starts with the salt:// or file:// URI), then make it a list
# of 1 element (for the iteration below)
template_hash = [template_hash]
elif template_hash and isinstance(template_hash, six.string_types) and\
(template_hash.startswith('salt://') or template_hash.startswith('file://')):
# If the template hash is a file URI, then provide the same value
# for each of the templates in the list, as probably they all
# share the same hash file, otherwise the user should provide
# this as a list
template_hash = [template_hash] * len(template_name)
elif not template_hash:
template_hash = [None] * len(template_name)
for tpl_index, tpl_name in enumerate(template_name):
tpl_hash = template_hash[tpl_index]
tpl_hash_name = template_hash_name[tpl_index]
_rand_filename = __salt__['random.hash'](tpl_name, 'md5')
_temp_file = __salt__['file.join']('/tmp', _rand_filename)
_managed = __salt__['file.get_managed'](name=_temp_file,
source=tpl_name,
source_hash=tpl_hash,
source_hash_name=tpl_hash_name,
user=None,
group=None,
mode=None,
attrs=None,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv,
skip_verify=skip_verify)
if not isinstance(_managed, (list, tuple)) and isinstance(_managed, six.string_types):
_loaded['comment'] += _managed
_loaded['result'] = False
elif isinstance(_managed, (list, tuple)) and not _managed:
_loaded['result'] = False
_loaded['comment'] += 'Error while rendering the template.'
elif isinstance(_managed, (list, tuple)) and not _managed[0]:
_loaded['result'] = False
_loaded['comment'] += _managed[-1] # contains the error message
if _loaded['result']: # all good
_temp_tpl_file = _managed[0]
_temp_tpl_file_exists = __salt__['file.file_exists'](_temp_tpl_file)
if not _temp_tpl_file_exists:
_loaded['result'] = False
_loaded['comment'] += 'Error while rendering the template.'
return _loaded
_rendered += __salt__['file.read'](_temp_tpl_file)
__salt__['file.remove'](_temp_tpl_file)
else:
return _loaded # exit
loaded_config = _rendered
if _loaded['result']: # all good
fun = 'load_merge_candidate'
if replace: # replace requested
fun = 'load_replace_candidate'
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
fun,
**{
'config': _rendered
}
)
else:
salt.utils.versions.warn_until(
'Sodium',
'Native NAPALM templates support will be removed in the Sodium '
'release. Please consider using the Salt rendering pipeline instead.'
'If you are using the \'netntp\', \'netsnmp\', or \'netusers\' Salt '
'State modules, you can ignore this message'
)
# otherwise, use NAPALM render system, injecting pillar/grains/opts vars
load_templates_params = defaults if defaults else {}
load_templates_params.update(template_vars)
load_templates_params.update(
{
'template_name': template_name,
'template_source': template_source, # inline template
'pillar': __pillar__, # inject pillar content
'grains': __grains__, # inject grains content
'opts': __opts__ # inject opts content
}
)
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
# so we'll set the CLOSE global explicitly as False
napalm_device['CLOSE'] = False # pylint: disable=undefined-variable
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'load_template',
**load_templates_params
)
return _config_logic(napalm_device, # pylint: disable=undefined-variable
_loaded,
test=test,
debug=debug,
replace=replace,
commit_config=commit,
loaded_config=loaded_config,
commit_at=commit_at,
commit_in=commit_in,
revert_in=revert_in,
revert_at=revert_at,
**template_vars)
@salt.utils.napalm.proxy_napalm_wrap
def commit(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Commits the configuration changes made on the network device.
CLI Example:
.. code-block:: bash
salt '*' net.commit
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'commit_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def discard_config(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
"""
Discards the changes applied.
CLI Example:
.. code-block:: bash
salt '*' net.discard_config
"""
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'discard_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def compare_config(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Returns the difference between the running config and the candidate config.
CLI Example:
.. code-block:: bash
salt '*' net.compare_config
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'compare_config',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def rollback(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Rollbacks the configuration.
CLI Example:
.. code-block:: bash
salt '*' net.rollback
'''
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'rollback',
**{}
)
@salt.utils.napalm.proxy_napalm_wrap
def config_changed(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Will prompt if the configuration has been changed.
:return: A tuple with a boolean that specifies if the config was changed on the device.\
And a string that provides more details of the reason why the configuration was not changed.
CLI Example:
.. code-block:: bash
salt '*' net.config_changed
'''
is_config_changed = False
reason = ''
try_compare = compare_config(inherit_napalm_device=napalm_device) # pylint: disable=undefined-variable
if try_compare.get('result'):
if try_compare.get('out'):
is_config_changed = True
else:
reason = 'Configuration was not changed on the device.'
else:
reason = try_compare.get('comment')
return is_config_changed, reason
@salt.utils.napalm.proxy_napalm_wrap
def config_control(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Will check if the configuration was changed.
If differences found, will try to commit.
In case commit unsuccessful, will try to rollback.
:return: A tuple with a boolean that specifies if the config was changed/committed/rollbacked on the device.\
And a string that provides more details of the reason why the configuration was not committed properly.
CLI Example:
.. code-block:: bash
salt '*' net.config_control
'''
result = True
comment = ''
changed, not_changed_rsn = config_changed(inherit_napalm_device=napalm_device) # pylint: disable=undefined-variable
if not changed:
return (changed, not_changed_rsn)
# config changed, thus let's try to commit
try_commit = commit()
if not try_commit.get('result'):
result = False
comment = 'Unable to commit the changes: {reason}.\n\
Will try to rollback now!'.format(
reason=try_commit.get('comment')
)
try_rollback = rollback()
if not try_rollback.get('result'):
comment += '\nCannot rollback! {reason}'.format(
reason=try_rollback.get('comment')
)
return result, comment
def cancel_commit(jid):
'''
.. versionadded:: 2019.2.0
Cancel a commit scheduled to be executed via the ``commit_in`` and
``commit_at`` arguments from the
:py:func:`net.load_template <salt.modules.napalm_network.load_template>` or
:py:func:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit ID is displayed when the commit is scheduled
via the functions named above.
CLI Example:
.. code-block:: bash
salt '*' net.cancel_commit 20180726083540640360
'''
job_name = '__napalm_commit_{}'.format(jid)
removed = __salt__['schedule.delete'](job_name)
if removed['result']:
saved = __salt__['schedule.save']()
removed['comment'] = 'Commit #{jid} cancelled.'.format(jid=jid)
else:
removed['comment'] = 'Unable to find commit #{jid}.'.format(jid=jid)
return removed
def confirm_commit(jid):
'''
.. versionadded:: 2019.2.0
Confirm a commit scheduled to be reverted via the ``revert_in`` and
``revert_at`` arguments from the
:mod:`net.load_template <salt.modules.napalm_network.load_template>` or
:mod:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit ID is displayed when the commit confirmed
is scheduled via the functions named above.
CLI Example:
.. code-block:: bash
salt '*' net.confirm_commit 20180726083540640360
'''
if __grains__['os'] == 'junos':
# Confirm the commit, by committing (i.e., invoking the RPC call)
confirmed = __salt__['napalm.junos_commit']()
confirmed['result'] = confirmed.pop('out')
confirmed['comment'] = confirmed.pop('message')
else:
confirmed = cancel_commit(jid)
if confirmed['result']:
confirmed['comment'] = 'Commit #{jid} confirmed.'.format(jid=jid)
return confirmed
def save_config(source=None,
path=None):
'''
.. versionadded:: 2019.2.0
Save the configuration to a file on the local file system.
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``,
``startup``. Default: ``running``.
path
Absolute path to file where to save the configuration.
To push the files to the Master, use
:mod:`cp.push <salt.modules.cp.push>` Execution function.
CLI Example:
.. code-block:: bash
salt '*' net.save_config source=running
'''
if not source:
source = 'running'
if not path:
path = salt.utils.files.mkstemp()
running_config = __salt__['net.config'](source=source)
if not running_config or not running_config['result']:
log.error('Unable to retrieve the config')
return running_config
with salt.utils.files.fopen(path, 'w') as fh_:
fh_.write(running_config['out'][source])
return {
'result': True,
'out': path,
'comment': '{source} config saved to {path}'.format(source=source, path=path)
}
def replace_pattern(pattern,
repl,
count=0,
flags=8,
bufsize=1,
append_if_not_found=False,
prepend_if_not_found=False,
not_found_content=None,
search_only=False,
show_changes=True,
backslash_literal=False,
source=None,
path=None,
test=False,
replace=True,
debug=False,
commit=True):
'''
.. versionadded:: 2019.2.0
Replace occurrences of a pattern in the configuration source. If
``show_changes`` is ``True``, then a diff of what changed will be returned,
otherwise a ``True`` will be returned when changes are made, and ``False``
when no changes are made.
This is a pure Python implementation that wraps Python's :py:func:`~re.sub`.
pattern
A regular expression, to be matched using Python's
:py:func:`~re.search`.
repl
The replacement text.
count: ``0``
Maximum number of pattern occurrences to be replaced. If count is a
positive integer ``n``, only ``n`` occurrences will be replaced,
otherwise all occurrences will be replaced.
flags (list or int): ``8``
A list of flags defined in the ``re`` module documentation from the
Python standard library. Each list item should be a string that will
correlate to the human-friendly flag name. E.g., ``['IGNORECASE',
'MULTILINE']``. Optionally, ``flags`` may be an int, with a value
corresponding to the XOR (``|``) of all the desired flags. Defaults to
8 (which supports 'MULTILINE').
bufsize (int or str): ``1``
How much of the configuration to buffer into memory at once. The
default value ``1`` processes one line at a time. The special value
``file`` may be specified which will read the entire file into memory
before processing.
append_if_not_found: ``False``
If set to ``True``, and pattern is not found, then the content will be
appended to the file.
prepend_if_not_found: ``False``
If set to ``True`` and pattern is not found, then the content will be
prepended to the file.
not_found_content
Content to use for append/prepend if not found. If None (default), uses
``repl``. Useful when ``repl`` uses references to group in pattern.
search_only: ``False``
If set to true, this no changes will be performed on the file, and this
function will simply return ``True`` if the pattern was matched, and
``False`` if not.
show_changes: ``True``
If ``True``, return a diff of changes made. Otherwise, return ``True``
if changes were made, and ``False`` if not.
backslash_literal: ``False``
Interpret backslashes as literal backslashes for the repl and not
escape characters. This will help when using append/prepend so that
the backslashes are not interpreted for the repl on the second run of
the state.
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path
Save the temporary configuration to a specific path, then read from
there.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' net.replace_pattern "bind-address\\s*=" "bind-address:"
CLI Example:
.. code-block:: bash
salt '*' net.replace_pattern PREFIX-LIST_NAME new-prefix-list-name
salt '*' net.replace_pattern bgp-group-name new-bgp-group-name count=1
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
replace_pattern = __salt__['file.replace'](path,
pattern,
repl,
count=count,
flags=flags,
bufsize=bufsize,
append_if_not_found=append_if_not_found,
prepend_if_not_found=prepend_if_not_found,
not_found_content=not_found_content,
search_only=search_only,
show_changes=show_changes,
backslash_literal=backslash_literal)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
def blockreplace(marker_start,
marker_end,
content='',
append_if_not_found=False,
prepend_if_not_found=False,
show_changes=True,
append_newline=False,
source='running',
path=None,
test=False,
commit=True,
debug=False,
replace=True):
'''
.. versionadded:: 2019.2.0
Replace content of the configuration source, delimited by the line markers.
A block of content delimited by comments can help you manage several lines
without worrying about old entries removal.
marker_start
The line content identifying a line as the start of the content block.
Note that the whole line containing this marker will be considered,
so whitespace or extra content before or after the marker is included
in final output.
marker_end
The line content identifying a line as the end of the content block.
Note that the whole line containing this marker will be considered,
so whitespace or extra content before or after the marker is included
in final output.
content
The content to be used between the two lines identified by
``marker_start`` and ``marker_stop``.
append_if_not_found: ``False``
If markers are not found and set to True then, the markers and content
will be appended to the file.
prepend_if_not_found: ``False``
If markers are not found and set to True then, the markers and content
will be prepended to the file.
append_newline: ``False``
Controls whether or not a newline is appended to the content block.
If the value of this argument is ``True`` then a newline will be added
to the content block. If it is ``False``, then a newline will not be
added to the content block. If it is ``None`` then a newline will only
be added to the content block if it does not already end in a newline.
show_changes: ``True``
Controls how changes are presented. If ``True``, this function will
return the of the changes made.
If ``False``, then it will return a boolean (``True`` if any changes
were made, otherwise False).
source: ``running``
The configuration source. Choose from: ``running``, ``candidate``, or
``startup``. Default: ``running``.
path: ``None``
Save the temporary configuration to a specific path, then read from
there. This argument is optional, can be used when you prefers a
particular location of the temporary file.
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return
the changes. Default: ``False`` and will commit the changes on the
device.
commit: ``True``
Commit the configuration changes? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key in the output dictionary, as
``loaded_config`` containing the raw configuration loaded on the device.
replace: ``True``
Load and replace the configuration. Default: ``True``.
CLI Example:
.. code-block:: bash
salt '*' net.blockreplace 'ntp' 'interface' ''
'''
config_saved = save_config(source=source, path=path)
if not config_saved or not config_saved['result']:
return config_saved
path = config_saved['out']
replace_pattern = __salt__['file.blockreplace'](path,
marker_start=marker_start,
marker_end=marker_end,
content=content,
append_if_not_found=append_if_not_found,
prepend_if_not_found=prepend_if_not_found,
show_changes=show_changes,
append_newline=append_newline)
with salt.utils.files.fopen(path, 'r') as fh_:
updated_config = fh_.read()
return __salt__['net.load_config'](text=updated_config,
test=test,
debug=debug,
replace=replace,
commit=commit)
# <---- Configuration specific functions -------------------------------------------------------------------------------
|
saltstack/salt
|
salt/cli/run.py
|
SaltRun.run
|
python
|
def run(self):
'''
Execute salt-run
'''
import salt.runner
self.parse_args()
# Setup file logging!
self.setup_logfile_logger()
verify_log(self.config)
profiling_enabled = self.options.profiling_enabled
runner = salt.runner.Runner(self.config)
if self.options.doc:
runner.print_docs()
self.exit(salt.defaults.exitcodes.EX_OK)
# Run this here so SystemExit isn't raised anywhere else when
# someone tries to use the runners via the python API
try:
if check_user(self.config['user']):
pr = salt.utils.profile.activate_profile(profiling_enabled)
try:
ret = runner.run()
# In older versions ret['data']['retcode'] was used
# for signaling the return code. This has been
# changed for the orchestrate runner, but external
# runners might still use it. For this reason, we
# also check ret['data']['retcode'] if
# ret['retcode'] is not available.
if isinstance(ret, dict) and 'retcode' in ret:
self.exit(ret['retcode'])
elif isinstance(ret, dict) and 'retcode' in ret.get('data', {}):
self.exit(ret['data']['retcode'])
finally:
salt.utils.profile.output_profile(
pr,
stats_path=self.options.profiling_path,
stop=True)
except SaltClientError as exc:
raise SystemExit(six.text_type(exc))
|
Execute salt-run
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/run.py#L17-L58
|
[
"def check_user(user):\n '''\n Check user and assign process uid/gid.\n '''\n if salt.utils.platform.is_windows():\n return True\n if user == salt.utils.user.get_user():\n return True\n import pwd # after confirming not running Windows\n try:\n pwuser = pwd.getpwnam(user)\n try:\n if hasattr(os, 'initgroups'):\n os.initgroups(user, pwuser.pw_gid) # pylint: disable=minimum-python-version\n else:\n os.setgroups(salt.utils.user.get_gid_list(user, include_default=False))\n os.setgid(pwuser.pw_gid)\n os.setuid(pwuser.pw_uid)\n\n # We could just reset the whole environment but let's just override\n # the variables we can get from pwuser\n if 'HOME' in os.environ:\n os.environ['HOME'] = pwuser.pw_dir\n\n if 'SHELL' in os.environ:\n os.environ['SHELL'] = pwuser.pw_shell\n\n for envvar in ('USER', 'LOGNAME'):\n if envvar in os.environ:\n os.environ[envvar] = pwuser.pw_name\n\n except OSError:\n msg = 'Salt configured to run as user \"{0}\" but unable to switch.'\n msg = msg.format(user)\n if is_console_configured():\n log.critical(msg)\n else:\n sys.stderr.write(\"CRITICAL: {0}\\n\".format(msg))\n return False\n except KeyError:\n msg = 'User not found: \"{0}\"'.format(user)\n if is_console_configured():\n log.critical(msg)\n else:\n sys.stderr.write(\"CRITICAL: {0}\\n\".format(msg))\n return False\n return True\n",
"def verify_log(opts):\n '''\n If an insecre logging configuration is found, show a warning\n '''\n level = LOG_LEVELS.get(str(opts.get('log_level')).lower(), logging.NOTSET)\n\n if level < logging.INFO:\n log.warning('Insecure logging configuration detected! Sensitive data may be logged.')\n",
"def activate_profile(test=True):\n pr = None\n if test:\n if HAS_CPROFILE:\n pr = cProfile.Profile()\n pr.enable()\n else:\n log.error('cProfile is not available on your platform')\n return pr\n",
"def output_profile(pr, stats_path='/tmp/stats', stop=False, id_=None):\n if pr is not None and HAS_CPROFILE:\n try:\n pr.disable()\n if not os.path.isdir(stats_path):\n os.makedirs(stats_path)\n date = datetime.datetime.now().isoformat()\n if id_ is None:\n id_ = salt.utils.hashutils.random_hash(size=32)\n ficp = os.path.join(stats_path, '{0}.{1}.pstats'.format(id_, date))\n fico = os.path.join(stats_path, '{0}.{1}.dot'.format(id_, date))\n ficn = os.path.join(stats_path, '{0}.{1}.stats'.format(id_, date))\n if not os.path.exists(ficp):\n pr.dump_stats(ficp)\n with salt.utils.files.fopen(ficn, 'w') as fic:\n pstats.Stats(pr, stream=fic).sort_stats('cumulative')\n log.info('PROFILING: %s generated', ficp)\n log.info('PROFILING (cumulative): %s generated', ficn)\n pyprof = salt.utils.path.which('pyprof2calltree')\n cmd = [pyprof, '-i', ficp, '-o', fico]\n if pyprof:\n failed = False\n try:\n pro = subprocess.Popen(\n cmd, shell=False,\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n except OSError:\n failed = True\n if pro.returncode:\n failed = True\n if failed:\n log.error('PROFILING (dot problem')\n else:\n log.info('PROFILING (dot): %s generated', fico)\n log.trace('pyprof2calltree output:')\n log.trace(salt.utils.stringutils.to_str(pro.stdout.read()).strip() +\n salt.utils.stringutils.to_str(pro.stderr.read()).strip())\n else:\n log.info('You can run %s for additional stats.', cmd)\n finally:\n if not stop:\n pr.enable()\n return pr\n",
"def run(self):\n '''\n Execute the runner sequence\n '''\n # Print documentation only\n if self.opts.get('doc', False):\n self.print_docs()\n else:\n return self._run_runner()\n",
"def print_docs(self):\n '''\n Print out the documentation!\n '''\n arg = self.opts.get('fun', None)\n docs = super(Runner, self).get_docs(arg)\n for fun in sorted(docs):\n display_output('{0}:'.format(fun), 'text', self.opts)\n print(docs[fun])\n"
] |
class SaltRun(salt.utils.parsers.SaltRunOptionParser):
'''
Used to execute Salt runners
'''
|
saltstack/salt
|
salt/states/dellchassis.py
|
blade_idrac
|
python
|
def blade_idrac(name, idrac_password=None, idrac_ipmi=None,
idrac_ip=None, idrac_netmask=None, idrac_gateway=None,
idrac_dnsname=None,
idrac_dhcp=None):
'''
Set parameters for iDRAC in a blade.
:param idrac_password: Password to use to connect to the iDRACs directly
(idrac_ipmi and idrac_dnsname must be set directly on the iDRAC. They
can't be set through the CMC. If this password is present, use it
instead of the CMC password)
:param idrac_ipmi: Enable/Disable IPMI over LAN
:param idrac_ip: Set IP address for iDRAC
:param idrac_netmask: Set netmask for iDRAC
:param idrac_gateway: Set gateway for iDRAC
:param idrac_dhcp: Turn on DHCP for iDRAC (True turns on, False does
nothing becaause setting a static IP will disable DHCP).
:return: A standard Salt changes dictionary
NOTE: If any of the IP address settings is configured, all of ip, netmask,
and gateway must be present
'''
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
if not idrac_password:
(username, password) = __salt__['chassis.chassis_credentials']()
else:
password = idrac_password
module_network = __salt__['chassis.cmd']('network_info', module=name)
current_idrac_ip = module_network['Network']['IP Address']
if idrac_ipmi is not None:
if idrac_ipmi is True or idrac_ipmi == 1:
idrac_ipmi = '1'
if idrac_ipmi is False or idrac_ipmi == 0:
idrac_ipmi = '0'
current_ipmi = __salt__['dracr.get_general']('cfgIpmiLan', 'cfgIpmiLanEnable',
host=current_idrac_ip, admin_username='root',
admin_password=password)
if current_ipmi != idrac_ipmi:
ch = {'Old': current_ipmi, 'New': idrac_ipmi}
ret['changes']['IPMI'] = ch
if idrac_dnsname is not None:
dnsret = __salt__['dracr.get_dns_dracname'](host=current_idrac_ip,
admin_username='root',
admin_password=password)
current_dnsname = dnsret['[Key=iDRAC.Embedded.1#NIC.1]']['DNSRacName']
if current_dnsname != idrac_dnsname:
ch = {'Old': current_dnsname,
'New': idrac_dnsname}
ret['changes']['DNSRacName'] = ch
if idrac_dhcp is not None or idrac_ip or idrac_netmask or idrac_gateway:
if idrac_dhcp is True or idrac_dhcp == 1:
idrac_dhcp = 1
else:
idrac_dhcp = 0
if six.text_type(module_network['Network']['DHCP Enabled']) == '0' and idrac_dhcp == 1:
ch = {'Old': module_network['Network']['DHCP Enabled'],
'New': idrac_dhcp}
ret['changes']['DRAC DHCP'] = ch
if idrac_dhcp == 0 and all([idrac_ip, idrac_netmask, idrac_netmask]):
current_network = __salt__['chassis.cmd']('network_info',
module=name)
old_ipv4 = {}
new_ipv4 = {}
if current_network['Network']['IP Address'] != idrac_ip:
old_ipv4['ip'] = current_network['Network']['IP Address']
new_ipv4['ip'] = idrac_ip
if current_network['Network']['Subnet Mask'] != idrac_netmask:
old_ipv4['netmask'] = current_network['Network']['Subnet Mask']
new_ipv4['netmask'] = idrac_netmask
if current_network['Network']['Gateway'] != idrac_gateway:
old_ipv4['gateway'] = current_network['Network']['Gateway']
new_ipv4['gateway'] = idrac_gateway
if new_ipv4 != {}:
ret['changes']['Network'] = {}
ret['changes']['Network']['Old'] = old_ipv4
ret['changes']['Network']['New'] = new_ipv4
if ret['changes'] == {}:
ret['comment'] = 'iDRAC on blade is already in the desired state.'
return ret
if __opts__['test'] and ret['changes'] != {}:
ret['result'] = None
ret['comment'] = 'iDRAC on blade will change.'
return ret
if 'IPMI' in ret['changes']:
ipmi_result = __salt__['dracr.set_general']('cfgIpmiLan',
'cfgIpmiLanEnable',
idrac_ipmi,
host=current_idrac_ip,
admin_username='root',
admin_password=password)
if not ipmi_result:
ret['result'] = False
ret['changes']['IPMI']['success'] = False
if 'DNSRacName' in ret['changes']:
dnsracname_result = __salt__['dracr.set_dns_dracname'](idrac_dnsname,
host=current_idrac_ip,
admin_username='root',
admin_password=password)
if dnsracname_result['retcode'] == 0:
ret['changes']['DNSRacName']['success'] = True
else:
ret['result'] = False
ret['changes']['DNSRacName']['success'] = False
ret['changes']['DNSRacName']['return'] = dnsracname_result
if 'DRAC DHCP' in ret['changes']:
dhcp_result = __salt__['chassis.cmd']('set_niccfg', dhcp=idrac_dhcp)
if dhcp_result['retcode']:
ret['changes']['DRAC DHCP']['success'] = True
else:
ret['result'] = False
ret['changes']['DRAC DHCP']['success'] = False
ret['changes']['DRAC DHCP']['return'] = dhcp_result
if 'Network' in ret['changes']:
network_result = __salt__['chassis.cmd']('set_niccfg', ip=idrac_ip,
netmask=idrac_netmask,
gateway=idrac_gateway,
module=name)
if network_result['retcode'] == 0:
ret['changes']['Network']['success'] = True
else:
ret['result'] = False
ret['changes']['Network']['success'] = False
ret['changes']['Network']['return'] = network_result
return ret
|
Set parameters for iDRAC in a blade.
:param idrac_password: Password to use to connect to the iDRACs directly
(idrac_ipmi and idrac_dnsname must be set directly on the iDRAC. They
can't be set through the CMC. If this password is present, use it
instead of the CMC password)
:param idrac_ipmi: Enable/Disable IPMI over LAN
:param idrac_ip: Set IP address for iDRAC
:param idrac_netmask: Set netmask for iDRAC
:param idrac_gateway: Set gateway for iDRAC
:param idrac_dhcp: Turn on DHCP for iDRAC (True turns on, False does
nothing becaause setting a static IP will disable DHCP).
:return: A standard Salt changes dictionary
NOTE: If any of the IP address settings is configured, all of ip, netmask,
and gateway must be present
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/dellchassis.py#L174-L317
| null |
# -*- coding: utf-8 -*-
'''
Manage chassis via Salt Proxies.
.. versionadded:: 2015.8.2
Below is an example state that sets basic parameters:
.. code-block:: yaml
my-dell-chassis:
dellchassis.chassis:
- chassis_name: my-dell-chassis
- datacenter: dc-1-us
- location: my-location
- mode: 2
- idrac_launch: 1
- slot_names:
- server-1: my-slot-name
- server-2: my-other-slot-name
- blade_power_states:
- server-1: on
- server-2: off
- server-3: powercycle
However, it is possible to place the entire set of chassis configuration
data in pillar. Here's an example pillar structure:
.. code-block:: yaml
proxy:
host: 10.27.20.18
admin_username: root
fallback_admin_username: root
passwords:
- super-secret
- old-secret
proxytype: fx2
chassis:
name: fx2-1
username: root
password: saltstack1
datacenter: london
location: rack-1-shelf-3
management_mode: 2
idrac_launch: 0
slot_names:
- 'server-1': blade1
- 'server-2': blade2
servers:
server-1:
idrac_password: saltstack1
ipmi_over_lan: True
ip: 172.17.17.132
netmask: 255.255.0.0
gateway: 172.17.17.1
server-2:
idrac_password: saltstack1
ipmi_over_lan: True
ip: 172.17.17.2
netmask: 255.255.0.0
gateway: 172.17.17.1
server-3:
idrac_password: saltstack1
ipmi_over_lan: True
ip: 172.17.17.20
netmask: 255.255.0.0
gateway: 172.17.17.1
server-4:
idrac_password: saltstack1
ipmi_over_lan: True
ip: 172.17.17.2
netmask: 255.255.0.0
gateway: 172.17.17.1
switches:
switch-1:
ip: 192.168.1.2
netmask: 255.255.255.0
gateway: 192.168.1.1
snmp: nonpublic
password: saltstack1
switch-2:
ip: 192.168.1.3
netmask: 255.255.255.0
gateway: 192.168.1.1
snmp: nonpublic
password: saltstack1
And to go with it, here's an example state that pulls the data from the
pillar stated above:
.. code-block:: jinja
{% set details = pillar.get('proxy:chassis', {}) %}
standup-step1:
dellchassis.chassis:
- name: {{ details['name'] }}
- location: {{ details['location'] }}
- mode: {{ details['management_mode'] }}
- idrac_launch: {{ details['idrac_launch'] }}
- slot_names:
{% for entry details['slot_names'] %}
- {{ entry.keys()[0] }}: {{ entry[entry.keys()[0]] }}
{% endfor %}
blade_powercycle:
dellchassis.chassis:
- blade_power_states:
- server-1: powercycle
- server-2: powercycle
- server-3: powercycle
- server-4: powercycle
# Set idrac_passwords for blades. racadm needs them to be called 'server-x'
{% for k, v in details['servers'].iteritems() %}
{{ k }}:
dellchassis.blade_idrac:
- idrac_password: {{ v['idrac_password'] }}
{% endfor %}
# Set management ip addresses, passwords, and snmp strings for switches
{% for k, v in details['switches'].iteritems() %}
{{ k }}-switch-setup:
dellchassis.switch:
- name: {{ k }}
- ip: {{ v['ip'] }}
- netmask: {{ v['netmask'] }}
- gateway: {{ v['gateway'] }}
- password: {{ v['password'] }}
- snmp: {{ v['snmp'] }}
{% endfor %}
.. note::
This state module relies on the dracr.py execution module, which runs racadm commands on
the chassis, blades, etc. The racadm command runs very slowly and, depending on your state,
the proxy minion return might timeout before the racadm commands have completed. If you
are repeatedly seeing minions timeout after state calls, please use the ``-t`` CLI argument
to increase the timeout variable.
For example:
.. code-block:: bash
salt '*' state.sls my-dell-chasis-state-name -t 60
.. note::
The Dell CMC units perform adequately but many iDRACs are **excruciatingly**
slow. Some functions can take minutes to execute.
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import logging
import os
# Import Salt lobs
from salt.ext import six
from salt.exceptions import CommandExecutionError
# Get logging started
log = logging.getLogger(__name__)
def __virtual__():
return 'chassis.cmd' in __salt__
def chassis(name, chassis_name=None, password=None, datacenter=None,
location=None, mode=None, idrac_launch=None, slot_names=None,
blade_power_states=None):
'''
Manage a Dell Chassis.
chassis_name
The name of the chassis.
datacenter
The datacenter in which the chassis is located
location
The location of the chassis.
password
Password for the chassis. Note: If this password is set for the chassis,
the current implementation of this state will set this password both on
the chassis and the iDrac passwords on any configured blades. If the
password for the blades should be distinct, they should be set separately
with the blade_idrac function.
mode
The management mode of the chassis. Viable options are:
- 0: None
- 1: Monitor
- 2: Manage and Monitor
idrac_launch
The iDRAC launch method of the chassis. Viable options are:
- 0: Disabled (launch iDRAC using IP address)
- 1: Enabled (launch iDRAC using DNS name)
slot_names
The names of the slots, provided as a list identified by
their slot numbers.
blade_power_states
The power states of a blade server, provided as a list and
identified by their server numbers. Viable options are:
- on: Ensure the blade server is powered on.
- off: Ensure the blade server is powered off.
- powercycle: Power cycle the blade server.
Example:
.. code-block:: yaml
my-dell-chassis:
dellchassis.chassis:
- chassis_name: my-dell-chassis
- location: my-location
- datacenter: london
- mode: 2
- idrac_launch: 1
- slot_names:
- 1: my-slot-name
- 2: my-other-slot-name
- blade_power_states:
- server-1: on
- server-2: off
- server-3: powercycle
'''
ret = {'name': chassis_name,
'chassis_name': chassis_name,
'result': True,
'changes': {},
'comment': ''}
chassis_cmd = 'chassis.cmd'
cfg_tuning = 'cfgRacTuning'
mode_cmd = 'cfgRacTuneChassisMgmtAtServer'
launch_cmd = 'cfgRacTuneIdracDNSLaunchEnable'
inventory = __salt__[chassis_cmd]('inventory')
if idrac_launch:
idrac_launch = six.text_type(idrac_launch)
current_name = __salt__[chassis_cmd]('get_chassis_name')
if chassis_name != current_name:
ret['changes'].update({'Name':
{'Old': current_name,
'New': chassis_name}})
current_dc = __salt__[chassis_cmd]('get_chassis_datacenter')
if datacenter and datacenter != current_dc:
ret['changes'].update({'Datacenter':
{'Old': current_dc,
'New': datacenter}})
if password:
ret['changes'].update({'Password':
{'Old': '******',
'New': '******'}})
if location:
current_location = __salt__[chassis_cmd]('get_chassis_location')
if location != current_location:
ret['changes'].update({'Location':
{'Old': current_location,
'New': location}})
if mode:
current_mode = __salt__[chassis_cmd]('get_general', cfg_tuning, mode_cmd)
if mode != current_mode:
ret['changes'].update({'Management Mode':
{'Old': current_mode,
'New': mode}})
if idrac_launch:
current_launch_method = __salt__[chassis_cmd]('get_general', cfg_tuning, launch_cmd)
if idrac_launch != current_launch_method:
ret['changes'].update({'iDrac Launch Method':
{'Old': current_launch_method,
'New': idrac_launch}})
if slot_names:
current_slot_names = __salt__[chassis_cmd]('list_slotnames')
for s in slot_names:
key = s.keys()[0]
new_name = s[key]
if key.startswith('slot-'):
key = key[5:]
current_slot_name = current_slot_names.get(key).get('slotname')
if current_slot_name != new_name:
old = {key: current_slot_name}
new = {key: new_name}
if ret['changes'].get('Slot Names') is None:
ret['changes'].update({'Slot Names':
{'Old': {},
'New': {}}})
ret['changes']['Slot Names']['Old'].update(old)
ret['changes']['Slot Names']['New'].update(new)
current_power_states = {}
target_power_states = {}
if blade_power_states:
for b in blade_power_states:
key = b.keys()[0]
status = __salt__[chassis_cmd]('server_powerstatus', module=key)
current_power_states[key] = status.get('status', -1)
if b[key] == 'powerdown':
if current_power_states[key] != -1 and current_power_states[key]:
target_power_states[key] = 'powerdown'
if b[key] == 'powerup':
if current_power_states[key] != -1 and not current_power_states[key]:
target_power_states[key] = 'powerup'
if b[key] == 'powercycle':
if current_power_states[key] != -1 and not current_power_states[key]:
target_power_states[key] = 'powerup'
if current_power_states[key] != -1 and current_power_states[key]:
target_power_states[key] = 'powercycle'
for k, v in six.iteritems(target_power_states):
old = {k: current_power_states[k]}
new = {k: v}
if ret['changes'].get('Blade Power States') is None:
ret['changes'].update({'Blade Power States':
{'Old': {},
'New': {}}})
ret['changes']['Blade Power States']['Old'].update(old)
ret['changes']['Blade Power States']['New'].update(new)
if ret['changes'] == {}:
ret['comment'] = 'Dell chassis is already in the desired state.'
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Dell chassis configuration will change.'
return ret
# Finally, set the necessary configurations on the chassis.
name = __salt__[chassis_cmd]('set_chassis_name', chassis_name)
if location:
location = __salt__[chassis_cmd]('set_chassis_location', location)
pw_result = True
if password:
pw_single = True
if __salt__[chassis_cmd]('change_password', username='root', uid=1,
password=password):
for blade in inventory['server']:
pw_single = __salt__[chassis_cmd]('deploy_password',
username='root',
password=password,
module=blade)
if not pw_single:
pw_result = False
else:
pw_result = False
if datacenter:
datacenter_result = __salt__[chassis_cmd]('set_chassis_datacenter',
datacenter)
if mode:
mode = __salt__[chassis_cmd]('set_general', cfg_tuning, mode_cmd, mode)
if idrac_launch:
idrac_launch = __salt__[chassis_cmd]('set_general', cfg_tuning, launch_cmd, idrac_launch)
if ret['changes'].get('Slot Names') is not None:
slot_rets = []
for s in slot_names:
key = s.keys()[0]
new_name = s[key]
if key.startswith('slot-'):
key = key[5:]
slot_rets.append(__salt__[chassis_cmd]('set_slotname', key, new_name))
if any(slot_rets) is False:
slot_names = False
else:
slot_names = True
powerchange_all_ok = True
for k, v in six.iteritems(target_power_states):
powerchange_ok = __salt__[chassis_cmd]('server_power', v, module=k)
if not powerchange_ok:
powerchange_all_ok = False
if any([name, location, mode, idrac_launch,
slot_names, powerchange_all_ok]) is False:
ret['result'] = False
ret['comment'] = 'There was an error setting the Dell chassis.'
ret['comment'] = 'Dell chassis was updated.'
return ret
def switch(name, ip=None, netmask=None, gateway=None, dhcp=None,
password=None, snmp=None):
'''
Manage switches in a Dell Chassis.
name
The switch designation (e.g. switch-1, switch-2)
ip
The Static IP Address of the switch
netmask
The netmask for the static IP
gateway
The gateway for the static IP
dhcp
True: Enable DHCP
False: Do not change DHCP setup
(disabling DHCP is automatic when a static IP is set)
password
The access (root) password for the switch
snmp
The SNMP community string for the switch
Example:
.. code-block:: yaml
my-dell-chassis:
dellchassis.switch:
- switch: switch-1
- ip: 192.168.1.1
- netmask: 255.255.255.0
- gateway: 192.168.1.254
- dhcp: True
- password: secret
- snmp: public
'''
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
current_nic = __salt__['chassis.cmd']('network_info', module=name)
try:
if current_nic.get('retcode', 0) != 0:
ret['result'] = False
ret['comment'] = current_nic['stdout']
return ret
if ip or netmask or gateway:
if not ip:
ip = current_nic['Network']['IP Address']
if not netmask:
ip = current_nic['Network']['Subnet Mask']
if not gateway:
ip = current_nic['Network']['Gateway']
if current_nic['Network']['DHCP Enabled'] == '0' and dhcp:
ret['changes'].update({'DHCP': {'Old': {'DHCP Enabled': current_nic['Network']['DHCP Enabled']},
'New': {'DHCP Enabled': dhcp}}})
if ((ip or netmask or gateway) and not dhcp and (ip != current_nic['Network']['IP Address'] or
netmask != current_nic['Network']['Subnet Mask'] or
gateway != current_nic['Network']['Gateway'])):
ret['changes'].update({'IP': {'Old': current_nic['Network'],
'New': {'IP Address': ip,
'Subnet Mask': netmask,
'Gateway': gateway}}})
if password:
if 'New' not in ret['changes']:
ret['changes']['New'] = {}
ret['changes']['New'].update({'Password': '*****'})
if snmp:
if 'New' not in ret['changes']:
ret['changes']['New'] = {}
ret['changes']['New'].update({'SNMP': '*****'})
if ret['changes'] == {}:
ret['comment'] = 'Switch ' + name + ' is already in desired state'
return ret
except AttributeError:
ret['changes'] = {}
ret['comment'] = 'Something went wrong retrieving the switch details'
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Switch ' + name + ' configuration will change'
return ret
# Finally, set the necessary configurations on the chassis.
dhcp_ret = net_ret = password_ret = snmp_ret = True
if dhcp:
dhcp_ret = __salt__['chassis.cmd']('set_niccfg', module=name, dhcp=dhcp)
if ip or netmask or gateway:
net_ret = __salt__['chassis.cmd']('set_niccfg', ip, netmask, gateway, module=name)
if password:
password_ret = __salt__['chassis.cmd']('deploy_password', 'root', password, module=name)
if snmp:
snmp_ret = __salt__['chassis.cmd']('deploy_snmp', snmp, module=name)
if any([password_ret, snmp_ret, net_ret, dhcp_ret]) is False:
ret['result'] = False
ret['comment'] = 'There was an error setting the switch {0}.'.format(name)
ret['comment'] = 'Dell chassis switch {0} was updated.'.format(name)
return ret
def _firmware_update(firmwarefile='', host='',
directory=''):
'''
Update firmware for a single host
'''
dest = os.path.join(directory, firmwarefile[7:])
__salt__['cp.get_file'](firmwarefile, dest)
username = __pillar__['proxy']['admin_user']
password = __pillar__['proxy']['admin_password']
__salt__['dracr.update_firmware'](dest,
host=host,
admin_username=username,
admin_password=password)
def firmware_update(hosts=None, directory=''):
'''
State to update the firmware on host
using the ``racadm`` command
firmwarefile
filename (string) starting with ``salt://``
host
string representing the hostname
supplied to the ``racadm`` command
directory
Directory name where firmwarefile
will be downloaded
.. code-block:: yaml
dell-chassis-firmware-update:
dellchassis.firmware_update:
hosts:
cmc:
salt://firmware_cmc.exe
server-1:
salt://firmware.exe
directory: /opt/firmwares
'''
ret = {}
ret.changes = {}
success = True
for host, firmwarefile in hosts:
try:
_firmware_update(firmwarefile, host, directory)
ret['changes'].update({
'host': {
'comment': 'Firmware update submitted for {0}'.format(host),
'success': True,
}
})
except CommandExecutionError as err:
success = False
ret['changes'].update({
'host': {
'comment': 'FAILED to update firmware for {0}'.format(host),
'success': False,
'reason': six.text_type(err),
}
})
ret['result'] = success
return ret
|
saltstack/salt
|
salt/states/dellchassis.py
|
chassis
|
python
|
def chassis(name, chassis_name=None, password=None, datacenter=None,
location=None, mode=None, idrac_launch=None, slot_names=None,
blade_power_states=None):
'''
Manage a Dell Chassis.
chassis_name
The name of the chassis.
datacenter
The datacenter in which the chassis is located
location
The location of the chassis.
password
Password for the chassis. Note: If this password is set for the chassis,
the current implementation of this state will set this password both on
the chassis and the iDrac passwords on any configured blades. If the
password for the blades should be distinct, they should be set separately
with the blade_idrac function.
mode
The management mode of the chassis. Viable options are:
- 0: None
- 1: Monitor
- 2: Manage and Monitor
idrac_launch
The iDRAC launch method of the chassis. Viable options are:
- 0: Disabled (launch iDRAC using IP address)
- 1: Enabled (launch iDRAC using DNS name)
slot_names
The names of the slots, provided as a list identified by
their slot numbers.
blade_power_states
The power states of a blade server, provided as a list and
identified by their server numbers. Viable options are:
- on: Ensure the blade server is powered on.
- off: Ensure the blade server is powered off.
- powercycle: Power cycle the blade server.
Example:
.. code-block:: yaml
my-dell-chassis:
dellchassis.chassis:
- chassis_name: my-dell-chassis
- location: my-location
- datacenter: london
- mode: 2
- idrac_launch: 1
- slot_names:
- 1: my-slot-name
- 2: my-other-slot-name
- blade_power_states:
- server-1: on
- server-2: off
- server-3: powercycle
'''
ret = {'name': chassis_name,
'chassis_name': chassis_name,
'result': True,
'changes': {},
'comment': ''}
chassis_cmd = 'chassis.cmd'
cfg_tuning = 'cfgRacTuning'
mode_cmd = 'cfgRacTuneChassisMgmtAtServer'
launch_cmd = 'cfgRacTuneIdracDNSLaunchEnable'
inventory = __salt__[chassis_cmd]('inventory')
if idrac_launch:
idrac_launch = six.text_type(idrac_launch)
current_name = __salt__[chassis_cmd]('get_chassis_name')
if chassis_name != current_name:
ret['changes'].update({'Name':
{'Old': current_name,
'New': chassis_name}})
current_dc = __salt__[chassis_cmd]('get_chassis_datacenter')
if datacenter and datacenter != current_dc:
ret['changes'].update({'Datacenter':
{'Old': current_dc,
'New': datacenter}})
if password:
ret['changes'].update({'Password':
{'Old': '******',
'New': '******'}})
if location:
current_location = __salt__[chassis_cmd]('get_chassis_location')
if location != current_location:
ret['changes'].update({'Location':
{'Old': current_location,
'New': location}})
if mode:
current_mode = __salt__[chassis_cmd]('get_general', cfg_tuning, mode_cmd)
if mode != current_mode:
ret['changes'].update({'Management Mode':
{'Old': current_mode,
'New': mode}})
if idrac_launch:
current_launch_method = __salt__[chassis_cmd]('get_general', cfg_tuning, launch_cmd)
if idrac_launch != current_launch_method:
ret['changes'].update({'iDrac Launch Method':
{'Old': current_launch_method,
'New': idrac_launch}})
if slot_names:
current_slot_names = __salt__[chassis_cmd]('list_slotnames')
for s in slot_names:
key = s.keys()[0]
new_name = s[key]
if key.startswith('slot-'):
key = key[5:]
current_slot_name = current_slot_names.get(key).get('slotname')
if current_slot_name != new_name:
old = {key: current_slot_name}
new = {key: new_name}
if ret['changes'].get('Slot Names') is None:
ret['changes'].update({'Slot Names':
{'Old': {},
'New': {}}})
ret['changes']['Slot Names']['Old'].update(old)
ret['changes']['Slot Names']['New'].update(new)
current_power_states = {}
target_power_states = {}
if blade_power_states:
for b in blade_power_states:
key = b.keys()[0]
status = __salt__[chassis_cmd]('server_powerstatus', module=key)
current_power_states[key] = status.get('status', -1)
if b[key] == 'powerdown':
if current_power_states[key] != -1 and current_power_states[key]:
target_power_states[key] = 'powerdown'
if b[key] == 'powerup':
if current_power_states[key] != -1 and not current_power_states[key]:
target_power_states[key] = 'powerup'
if b[key] == 'powercycle':
if current_power_states[key] != -1 and not current_power_states[key]:
target_power_states[key] = 'powerup'
if current_power_states[key] != -1 and current_power_states[key]:
target_power_states[key] = 'powercycle'
for k, v in six.iteritems(target_power_states):
old = {k: current_power_states[k]}
new = {k: v}
if ret['changes'].get('Blade Power States') is None:
ret['changes'].update({'Blade Power States':
{'Old': {},
'New': {}}})
ret['changes']['Blade Power States']['Old'].update(old)
ret['changes']['Blade Power States']['New'].update(new)
if ret['changes'] == {}:
ret['comment'] = 'Dell chassis is already in the desired state.'
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Dell chassis configuration will change.'
return ret
# Finally, set the necessary configurations on the chassis.
name = __salt__[chassis_cmd]('set_chassis_name', chassis_name)
if location:
location = __salt__[chassis_cmd]('set_chassis_location', location)
pw_result = True
if password:
pw_single = True
if __salt__[chassis_cmd]('change_password', username='root', uid=1,
password=password):
for blade in inventory['server']:
pw_single = __salt__[chassis_cmd]('deploy_password',
username='root',
password=password,
module=blade)
if not pw_single:
pw_result = False
else:
pw_result = False
if datacenter:
datacenter_result = __salt__[chassis_cmd]('set_chassis_datacenter',
datacenter)
if mode:
mode = __salt__[chassis_cmd]('set_general', cfg_tuning, mode_cmd, mode)
if idrac_launch:
idrac_launch = __salt__[chassis_cmd]('set_general', cfg_tuning, launch_cmd, idrac_launch)
if ret['changes'].get('Slot Names') is not None:
slot_rets = []
for s in slot_names:
key = s.keys()[0]
new_name = s[key]
if key.startswith('slot-'):
key = key[5:]
slot_rets.append(__salt__[chassis_cmd]('set_slotname', key, new_name))
if any(slot_rets) is False:
slot_names = False
else:
slot_names = True
powerchange_all_ok = True
for k, v in six.iteritems(target_power_states):
powerchange_ok = __salt__[chassis_cmd]('server_power', v, module=k)
if not powerchange_ok:
powerchange_all_ok = False
if any([name, location, mode, idrac_launch,
slot_names, powerchange_all_ok]) is False:
ret['result'] = False
ret['comment'] = 'There was an error setting the Dell chassis.'
ret['comment'] = 'Dell chassis was updated.'
return ret
|
Manage a Dell Chassis.
chassis_name
The name of the chassis.
datacenter
The datacenter in which the chassis is located
location
The location of the chassis.
password
Password for the chassis. Note: If this password is set for the chassis,
the current implementation of this state will set this password both on
the chassis and the iDrac passwords on any configured blades. If the
password for the blades should be distinct, they should be set separately
with the blade_idrac function.
mode
The management mode of the chassis. Viable options are:
- 0: None
- 1: Monitor
- 2: Manage and Monitor
idrac_launch
The iDRAC launch method of the chassis. Viable options are:
- 0: Disabled (launch iDRAC using IP address)
- 1: Enabled (launch iDRAC using DNS name)
slot_names
The names of the slots, provided as a list identified by
their slot numbers.
blade_power_states
The power states of a blade server, provided as a list and
identified by their server numbers. Viable options are:
- on: Ensure the blade server is powered on.
- off: Ensure the blade server is powered off.
- powercycle: Power cycle the blade server.
Example:
.. code-block:: yaml
my-dell-chassis:
dellchassis.chassis:
- chassis_name: my-dell-chassis
- location: my-location
- datacenter: london
- mode: 2
- idrac_launch: 1
- slot_names:
- 1: my-slot-name
- 2: my-other-slot-name
- blade_power_states:
- server-1: on
- server-2: off
- server-3: powercycle
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/dellchassis.py#L320-L546
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n"
] |
# -*- coding: utf-8 -*-
'''
Manage chassis via Salt Proxies.
.. versionadded:: 2015.8.2
Below is an example state that sets basic parameters:
.. code-block:: yaml
my-dell-chassis:
dellchassis.chassis:
- chassis_name: my-dell-chassis
- datacenter: dc-1-us
- location: my-location
- mode: 2
- idrac_launch: 1
- slot_names:
- server-1: my-slot-name
- server-2: my-other-slot-name
- blade_power_states:
- server-1: on
- server-2: off
- server-3: powercycle
However, it is possible to place the entire set of chassis configuration
data in pillar. Here's an example pillar structure:
.. code-block:: yaml
proxy:
host: 10.27.20.18
admin_username: root
fallback_admin_username: root
passwords:
- super-secret
- old-secret
proxytype: fx2
chassis:
name: fx2-1
username: root
password: saltstack1
datacenter: london
location: rack-1-shelf-3
management_mode: 2
idrac_launch: 0
slot_names:
- 'server-1': blade1
- 'server-2': blade2
servers:
server-1:
idrac_password: saltstack1
ipmi_over_lan: True
ip: 172.17.17.132
netmask: 255.255.0.0
gateway: 172.17.17.1
server-2:
idrac_password: saltstack1
ipmi_over_lan: True
ip: 172.17.17.2
netmask: 255.255.0.0
gateway: 172.17.17.1
server-3:
idrac_password: saltstack1
ipmi_over_lan: True
ip: 172.17.17.20
netmask: 255.255.0.0
gateway: 172.17.17.1
server-4:
idrac_password: saltstack1
ipmi_over_lan: True
ip: 172.17.17.2
netmask: 255.255.0.0
gateway: 172.17.17.1
switches:
switch-1:
ip: 192.168.1.2
netmask: 255.255.255.0
gateway: 192.168.1.1
snmp: nonpublic
password: saltstack1
switch-2:
ip: 192.168.1.3
netmask: 255.255.255.0
gateway: 192.168.1.1
snmp: nonpublic
password: saltstack1
And to go with it, here's an example state that pulls the data from the
pillar stated above:
.. code-block:: jinja
{% set details = pillar.get('proxy:chassis', {}) %}
standup-step1:
dellchassis.chassis:
- name: {{ details['name'] }}
- location: {{ details['location'] }}
- mode: {{ details['management_mode'] }}
- idrac_launch: {{ details['idrac_launch'] }}
- slot_names:
{% for entry details['slot_names'] %}
- {{ entry.keys()[0] }}: {{ entry[entry.keys()[0]] }}
{% endfor %}
blade_powercycle:
dellchassis.chassis:
- blade_power_states:
- server-1: powercycle
- server-2: powercycle
- server-3: powercycle
- server-4: powercycle
# Set idrac_passwords for blades. racadm needs them to be called 'server-x'
{% for k, v in details['servers'].iteritems() %}
{{ k }}:
dellchassis.blade_idrac:
- idrac_password: {{ v['idrac_password'] }}
{% endfor %}
# Set management ip addresses, passwords, and snmp strings for switches
{% for k, v in details['switches'].iteritems() %}
{{ k }}-switch-setup:
dellchassis.switch:
- name: {{ k }}
- ip: {{ v['ip'] }}
- netmask: {{ v['netmask'] }}
- gateway: {{ v['gateway'] }}
- password: {{ v['password'] }}
- snmp: {{ v['snmp'] }}
{% endfor %}
.. note::
This state module relies on the dracr.py execution module, which runs racadm commands on
the chassis, blades, etc. The racadm command runs very slowly and, depending on your state,
the proxy minion return might timeout before the racadm commands have completed. If you
are repeatedly seeing minions timeout after state calls, please use the ``-t`` CLI argument
to increase the timeout variable.
For example:
.. code-block:: bash
salt '*' state.sls my-dell-chasis-state-name -t 60
.. note::
The Dell CMC units perform adequately but many iDRACs are **excruciatingly**
slow. Some functions can take minutes to execute.
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import logging
import os
# Import Salt lobs
from salt.ext import six
from salt.exceptions import CommandExecutionError
# Get logging started
log = logging.getLogger(__name__)
def __virtual__():
return 'chassis.cmd' in __salt__
def blade_idrac(name, idrac_password=None, idrac_ipmi=None,
idrac_ip=None, idrac_netmask=None, idrac_gateway=None,
idrac_dnsname=None,
idrac_dhcp=None):
'''
Set parameters for iDRAC in a blade.
:param idrac_password: Password to use to connect to the iDRACs directly
(idrac_ipmi and idrac_dnsname must be set directly on the iDRAC. They
can't be set through the CMC. If this password is present, use it
instead of the CMC password)
:param idrac_ipmi: Enable/Disable IPMI over LAN
:param idrac_ip: Set IP address for iDRAC
:param idrac_netmask: Set netmask for iDRAC
:param idrac_gateway: Set gateway for iDRAC
:param idrac_dhcp: Turn on DHCP for iDRAC (True turns on, False does
nothing becaause setting a static IP will disable DHCP).
:return: A standard Salt changes dictionary
NOTE: If any of the IP address settings is configured, all of ip, netmask,
and gateway must be present
'''
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
if not idrac_password:
(username, password) = __salt__['chassis.chassis_credentials']()
else:
password = idrac_password
module_network = __salt__['chassis.cmd']('network_info', module=name)
current_idrac_ip = module_network['Network']['IP Address']
if idrac_ipmi is not None:
if idrac_ipmi is True or idrac_ipmi == 1:
idrac_ipmi = '1'
if idrac_ipmi is False or idrac_ipmi == 0:
idrac_ipmi = '0'
current_ipmi = __salt__['dracr.get_general']('cfgIpmiLan', 'cfgIpmiLanEnable',
host=current_idrac_ip, admin_username='root',
admin_password=password)
if current_ipmi != idrac_ipmi:
ch = {'Old': current_ipmi, 'New': idrac_ipmi}
ret['changes']['IPMI'] = ch
if idrac_dnsname is not None:
dnsret = __salt__['dracr.get_dns_dracname'](host=current_idrac_ip,
admin_username='root',
admin_password=password)
current_dnsname = dnsret['[Key=iDRAC.Embedded.1#NIC.1]']['DNSRacName']
if current_dnsname != idrac_dnsname:
ch = {'Old': current_dnsname,
'New': idrac_dnsname}
ret['changes']['DNSRacName'] = ch
if idrac_dhcp is not None or idrac_ip or idrac_netmask or idrac_gateway:
if idrac_dhcp is True or idrac_dhcp == 1:
idrac_dhcp = 1
else:
idrac_dhcp = 0
if six.text_type(module_network['Network']['DHCP Enabled']) == '0' and idrac_dhcp == 1:
ch = {'Old': module_network['Network']['DHCP Enabled'],
'New': idrac_dhcp}
ret['changes']['DRAC DHCP'] = ch
if idrac_dhcp == 0 and all([idrac_ip, idrac_netmask, idrac_netmask]):
current_network = __salt__['chassis.cmd']('network_info',
module=name)
old_ipv4 = {}
new_ipv4 = {}
if current_network['Network']['IP Address'] != idrac_ip:
old_ipv4['ip'] = current_network['Network']['IP Address']
new_ipv4['ip'] = idrac_ip
if current_network['Network']['Subnet Mask'] != idrac_netmask:
old_ipv4['netmask'] = current_network['Network']['Subnet Mask']
new_ipv4['netmask'] = idrac_netmask
if current_network['Network']['Gateway'] != idrac_gateway:
old_ipv4['gateway'] = current_network['Network']['Gateway']
new_ipv4['gateway'] = idrac_gateway
if new_ipv4 != {}:
ret['changes']['Network'] = {}
ret['changes']['Network']['Old'] = old_ipv4
ret['changes']['Network']['New'] = new_ipv4
if ret['changes'] == {}:
ret['comment'] = 'iDRAC on blade is already in the desired state.'
return ret
if __opts__['test'] and ret['changes'] != {}:
ret['result'] = None
ret['comment'] = 'iDRAC on blade will change.'
return ret
if 'IPMI' in ret['changes']:
ipmi_result = __salt__['dracr.set_general']('cfgIpmiLan',
'cfgIpmiLanEnable',
idrac_ipmi,
host=current_idrac_ip,
admin_username='root',
admin_password=password)
if not ipmi_result:
ret['result'] = False
ret['changes']['IPMI']['success'] = False
if 'DNSRacName' in ret['changes']:
dnsracname_result = __salt__['dracr.set_dns_dracname'](idrac_dnsname,
host=current_idrac_ip,
admin_username='root',
admin_password=password)
if dnsracname_result['retcode'] == 0:
ret['changes']['DNSRacName']['success'] = True
else:
ret['result'] = False
ret['changes']['DNSRacName']['success'] = False
ret['changes']['DNSRacName']['return'] = dnsracname_result
if 'DRAC DHCP' in ret['changes']:
dhcp_result = __salt__['chassis.cmd']('set_niccfg', dhcp=idrac_dhcp)
if dhcp_result['retcode']:
ret['changes']['DRAC DHCP']['success'] = True
else:
ret['result'] = False
ret['changes']['DRAC DHCP']['success'] = False
ret['changes']['DRAC DHCP']['return'] = dhcp_result
if 'Network' in ret['changes']:
network_result = __salt__['chassis.cmd']('set_niccfg', ip=idrac_ip,
netmask=idrac_netmask,
gateway=idrac_gateway,
module=name)
if network_result['retcode'] == 0:
ret['changes']['Network']['success'] = True
else:
ret['result'] = False
ret['changes']['Network']['success'] = False
ret['changes']['Network']['return'] = network_result
return ret
def switch(name, ip=None, netmask=None, gateway=None, dhcp=None,
password=None, snmp=None):
'''
Manage switches in a Dell Chassis.
name
The switch designation (e.g. switch-1, switch-2)
ip
The Static IP Address of the switch
netmask
The netmask for the static IP
gateway
The gateway for the static IP
dhcp
True: Enable DHCP
False: Do not change DHCP setup
(disabling DHCP is automatic when a static IP is set)
password
The access (root) password for the switch
snmp
The SNMP community string for the switch
Example:
.. code-block:: yaml
my-dell-chassis:
dellchassis.switch:
- switch: switch-1
- ip: 192.168.1.1
- netmask: 255.255.255.0
- gateway: 192.168.1.254
- dhcp: True
- password: secret
- snmp: public
'''
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
current_nic = __salt__['chassis.cmd']('network_info', module=name)
try:
if current_nic.get('retcode', 0) != 0:
ret['result'] = False
ret['comment'] = current_nic['stdout']
return ret
if ip or netmask or gateway:
if not ip:
ip = current_nic['Network']['IP Address']
if not netmask:
ip = current_nic['Network']['Subnet Mask']
if not gateway:
ip = current_nic['Network']['Gateway']
if current_nic['Network']['DHCP Enabled'] == '0' and dhcp:
ret['changes'].update({'DHCP': {'Old': {'DHCP Enabled': current_nic['Network']['DHCP Enabled']},
'New': {'DHCP Enabled': dhcp}}})
if ((ip or netmask or gateway) and not dhcp and (ip != current_nic['Network']['IP Address'] or
netmask != current_nic['Network']['Subnet Mask'] or
gateway != current_nic['Network']['Gateway'])):
ret['changes'].update({'IP': {'Old': current_nic['Network'],
'New': {'IP Address': ip,
'Subnet Mask': netmask,
'Gateway': gateway}}})
if password:
if 'New' not in ret['changes']:
ret['changes']['New'] = {}
ret['changes']['New'].update({'Password': '*****'})
if snmp:
if 'New' not in ret['changes']:
ret['changes']['New'] = {}
ret['changes']['New'].update({'SNMP': '*****'})
if ret['changes'] == {}:
ret['comment'] = 'Switch ' + name + ' is already in desired state'
return ret
except AttributeError:
ret['changes'] = {}
ret['comment'] = 'Something went wrong retrieving the switch details'
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Switch ' + name + ' configuration will change'
return ret
# Finally, set the necessary configurations on the chassis.
dhcp_ret = net_ret = password_ret = snmp_ret = True
if dhcp:
dhcp_ret = __salt__['chassis.cmd']('set_niccfg', module=name, dhcp=dhcp)
if ip or netmask or gateway:
net_ret = __salt__['chassis.cmd']('set_niccfg', ip, netmask, gateway, module=name)
if password:
password_ret = __salt__['chassis.cmd']('deploy_password', 'root', password, module=name)
if snmp:
snmp_ret = __salt__['chassis.cmd']('deploy_snmp', snmp, module=name)
if any([password_ret, snmp_ret, net_ret, dhcp_ret]) is False:
ret['result'] = False
ret['comment'] = 'There was an error setting the switch {0}.'.format(name)
ret['comment'] = 'Dell chassis switch {0} was updated.'.format(name)
return ret
def _firmware_update(firmwarefile='', host='',
directory=''):
'''
Update firmware for a single host
'''
dest = os.path.join(directory, firmwarefile[7:])
__salt__['cp.get_file'](firmwarefile, dest)
username = __pillar__['proxy']['admin_user']
password = __pillar__['proxy']['admin_password']
__salt__['dracr.update_firmware'](dest,
host=host,
admin_username=username,
admin_password=password)
def firmware_update(hosts=None, directory=''):
'''
State to update the firmware on host
using the ``racadm`` command
firmwarefile
filename (string) starting with ``salt://``
host
string representing the hostname
supplied to the ``racadm`` command
directory
Directory name where firmwarefile
will be downloaded
.. code-block:: yaml
dell-chassis-firmware-update:
dellchassis.firmware_update:
hosts:
cmc:
salt://firmware_cmc.exe
server-1:
salt://firmware.exe
directory: /opt/firmwares
'''
ret = {}
ret.changes = {}
success = True
for host, firmwarefile in hosts:
try:
_firmware_update(firmwarefile, host, directory)
ret['changes'].update({
'host': {
'comment': 'Firmware update submitted for {0}'.format(host),
'success': True,
}
})
except CommandExecutionError as err:
success = False
ret['changes'].update({
'host': {
'comment': 'FAILED to update firmware for {0}'.format(host),
'success': False,
'reason': six.text_type(err),
}
})
ret['result'] = success
return ret
|
saltstack/salt
|
salt/states/dellchassis.py
|
switch
|
python
|
def switch(name, ip=None, netmask=None, gateway=None, dhcp=None,
password=None, snmp=None):
'''
Manage switches in a Dell Chassis.
name
The switch designation (e.g. switch-1, switch-2)
ip
The Static IP Address of the switch
netmask
The netmask for the static IP
gateway
The gateway for the static IP
dhcp
True: Enable DHCP
False: Do not change DHCP setup
(disabling DHCP is automatic when a static IP is set)
password
The access (root) password for the switch
snmp
The SNMP community string for the switch
Example:
.. code-block:: yaml
my-dell-chassis:
dellchassis.switch:
- switch: switch-1
- ip: 192.168.1.1
- netmask: 255.255.255.0
- gateway: 192.168.1.254
- dhcp: True
- password: secret
- snmp: public
'''
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
current_nic = __salt__['chassis.cmd']('network_info', module=name)
try:
if current_nic.get('retcode', 0) != 0:
ret['result'] = False
ret['comment'] = current_nic['stdout']
return ret
if ip or netmask or gateway:
if not ip:
ip = current_nic['Network']['IP Address']
if not netmask:
ip = current_nic['Network']['Subnet Mask']
if not gateway:
ip = current_nic['Network']['Gateway']
if current_nic['Network']['DHCP Enabled'] == '0' and dhcp:
ret['changes'].update({'DHCP': {'Old': {'DHCP Enabled': current_nic['Network']['DHCP Enabled']},
'New': {'DHCP Enabled': dhcp}}})
if ((ip or netmask or gateway) and not dhcp and (ip != current_nic['Network']['IP Address'] or
netmask != current_nic['Network']['Subnet Mask'] or
gateway != current_nic['Network']['Gateway'])):
ret['changes'].update({'IP': {'Old': current_nic['Network'],
'New': {'IP Address': ip,
'Subnet Mask': netmask,
'Gateway': gateway}}})
if password:
if 'New' not in ret['changes']:
ret['changes']['New'] = {}
ret['changes']['New'].update({'Password': '*****'})
if snmp:
if 'New' not in ret['changes']:
ret['changes']['New'] = {}
ret['changes']['New'].update({'SNMP': '*****'})
if ret['changes'] == {}:
ret['comment'] = 'Switch ' + name + ' is already in desired state'
return ret
except AttributeError:
ret['changes'] = {}
ret['comment'] = 'Something went wrong retrieving the switch details'
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Switch ' + name + ' configuration will change'
return ret
# Finally, set the necessary configurations on the chassis.
dhcp_ret = net_ret = password_ret = snmp_ret = True
if dhcp:
dhcp_ret = __salt__['chassis.cmd']('set_niccfg', module=name, dhcp=dhcp)
if ip or netmask or gateway:
net_ret = __salt__['chassis.cmd']('set_niccfg', ip, netmask, gateway, module=name)
if password:
password_ret = __salt__['chassis.cmd']('deploy_password', 'root', password, module=name)
if snmp:
snmp_ret = __salt__['chassis.cmd']('deploy_snmp', snmp, module=name)
if any([password_ret, snmp_ret, net_ret, dhcp_ret]) is False:
ret['result'] = False
ret['comment'] = 'There was an error setting the switch {0}.'.format(name)
ret['comment'] = 'Dell chassis switch {0} was updated.'.format(name)
return ret
|
Manage switches in a Dell Chassis.
name
The switch designation (e.g. switch-1, switch-2)
ip
The Static IP Address of the switch
netmask
The netmask for the static IP
gateway
The gateway for the static IP
dhcp
True: Enable DHCP
False: Do not change DHCP setup
(disabling DHCP is automatic when a static IP is set)
password
The access (root) password for the switch
snmp
The SNMP community string for the switch
Example:
.. code-block:: yaml
my-dell-chassis:
dellchassis.switch:
- switch: switch-1
- ip: 192.168.1.1
- netmask: 255.255.255.0
- gateway: 192.168.1.254
- dhcp: True
- password: secret
- snmp: public
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/dellchassis.py#L549-L664
| null |
# -*- coding: utf-8 -*-
'''
Manage chassis via Salt Proxies.
.. versionadded:: 2015.8.2
Below is an example state that sets basic parameters:
.. code-block:: yaml
my-dell-chassis:
dellchassis.chassis:
- chassis_name: my-dell-chassis
- datacenter: dc-1-us
- location: my-location
- mode: 2
- idrac_launch: 1
- slot_names:
- server-1: my-slot-name
- server-2: my-other-slot-name
- blade_power_states:
- server-1: on
- server-2: off
- server-3: powercycle
However, it is possible to place the entire set of chassis configuration
data in pillar. Here's an example pillar structure:
.. code-block:: yaml
proxy:
host: 10.27.20.18
admin_username: root
fallback_admin_username: root
passwords:
- super-secret
- old-secret
proxytype: fx2
chassis:
name: fx2-1
username: root
password: saltstack1
datacenter: london
location: rack-1-shelf-3
management_mode: 2
idrac_launch: 0
slot_names:
- 'server-1': blade1
- 'server-2': blade2
servers:
server-1:
idrac_password: saltstack1
ipmi_over_lan: True
ip: 172.17.17.132
netmask: 255.255.0.0
gateway: 172.17.17.1
server-2:
idrac_password: saltstack1
ipmi_over_lan: True
ip: 172.17.17.2
netmask: 255.255.0.0
gateway: 172.17.17.1
server-3:
idrac_password: saltstack1
ipmi_over_lan: True
ip: 172.17.17.20
netmask: 255.255.0.0
gateway: 172.17.17.1
server-4:
idrac_password: saltstack1
ipmi_over_lan: True
ip: 172.17.17.2
netmask: 255.255.0.0
gateway: 172.17.17.1
switches:
switch-1:
ip: 192.168.1.2
netmask: 255.255.255.0
gateway: 192.168.1.1
snmp: nonpublic
password: saltstack1
switch-2:
ip: 192.168.1.3
netmask: 255.255.255.0
gateway: 192.168.1.1
snmp: nonpublic
password: saltstack1
And to go with it, here's an example state that pulls the data from the
pillar stated above:
.. code-block:: jinja
{% set details = pillar.get('proxy:chassis', {}) %}
standup-step1:
dellchassis.chassis:
- name: {{ details['name'] }}
- location: {{ details['location'] }}
- mode: {{ details['management_mode'] }}
- idrac_launch: {{ details['idrac_launch'] }}
- slot_names:
{% for entry details['slot_names'] %}
- {{ entry.keys()[0] }}: {{ entry[entry.keys()[0]] }}
{% endfor %}
blade_powercycle:
dellchassis.chassis:
- blade_power_states:
- server-1: powercycle
- server-2: powercycle
- server-3: powercycle
- server-4: powercycle
# Set idrac_passwords for blades. racadm needs them to be called 'server-x'
{% for k, v in details['servers'].iteritems() %}
{{ k }}:
dellchassis.blade_idrac:
- idrac_password: {{ v['idrac_password'] }}
{% endfor %}
# Set management ip addresses, passwords, and snmp strings for switches
{% for k, v in details['switches'].iteritems() %}
{{ k }}-switch-setup:
dellchassis.switch:
- name: {{ k }}
- ip: {{ v['ip'] }}
- netmask: {{ v['netmask'] }}
- gateway: {{ v['gateway'] }}
- password: {{ v['password'] }}
- snmp: {{ v['snmp'] }}
{% endfor %}
.. note::
This state module relies on the dracr.py execution module, which runs racadm commands on
the chassis, blades, etc. The racadm command runs very slowly and, depending on your state,
the proxy minion return might timeout before the racadm commands have completed. If you
are repeatedly seeing minions timeout after state calls, please use the ``-t`` CLI argument
to increase the timeout variable.
For example:
.. code-block:: bash
salt '*' state.sls my-dell-chasis-state-name -t 60
.. note::
The Dell CMC units perform adequately but many iDRACs are **excruciatingly**
slow. Some functions can take minutes to execute.
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import logging
import os
# Import Salt lobs
from salt.ext import six
from salt.exceptions import CommandExecutionError
# Get logging started
log = logging.getLogger(__name__)
def __virtual__():
return 'chassis.cmd' in __salt__
def blade_idrac(name, idrac_password=None, idrac_ipmi=None,
idrac_ip=None, idrac_netmask=None, idrac_gateway=None,
idrac_dnsname=None,
idrac_dhcp=None):
'''
Set parameters for iDRAC in a blade.
:param idrac_password: Password to use to connect to the iDRACs directly
(idrac_ipmi and idrac_dnsname must be set directly on the iDRAC. They
can't be set through the CMC. If this password is present, use it
instead of the CMC password)
:param idrac_ipmi: Enable/Disable IPMI over LAN
:param idrac_ip: Set IP address for iDRAC
:param idrac_netmask: Set netmask for iDRAC
:param idrac_gateway: Set gateway for iDRAC
:param idrac_dhcp: Turn on DHCP for iDRAC (True turns on, False does
nothing becaause setting a static IP will disable DHCP).
:return: A standard Salt changes dictionary
NOTE: If any of the IP address settings is configured, all of ip, netmask,
and gateway must be present
'''
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
if not idrac_password:
(username, password) = __salt__['chassis.chassis_credentials']()
else:
password = idrac_password
module_network = __salt__['chassis.cmd']('network_info', module=name)
current_idrac_ip = module_network['Network']['IP Address']
if idrac_ipmi is not None:
if idrac_ipmi is True or idrac_ipmi == 1:
idrac_ipmi = '1'
if idrac_ipmi is False or idrac_ipmi == 0:
idrac_ipmi = '0'
current_ipmi = __salt__['dracr.get_general']('cfgIpmiLan', 'cfgIpmiLanEnable',
host=current_idrac_ip, admin_username='root',
admin_password=password)
if current_ipmi != idrac_ipmi:
ch = {'Old': current_ipmi, 'New': idrac_ipmi}
ret['changes']['IPMI'] = ch
if idrac_dnsname is not None:
dnsret = __salt__['dracr.get_dns_dracname'](host=current_idrac_ip,
admin_username='root',
admin_password=password)
current_dnsname = dnsret['[Key=iDRAC.Embedded.1#NIC.1]']['DNSRacName']
if current_dnsname != idrac_dnsname:
ch = {'Old': current_dnsname,
'New': idrac_dnsname}
ret['changes']['DNSRacName'] = ch
if idrac_dhcp is not None or idrac_ip or idrac_netmask or idrac_gateway:
if idrac_dhcp is True or idrac_dhcp == 1:
idrac_dhcp = 1
else:
idrac_dhcp = 0
if six.text_type(module_network['Network']['DHCP Enabled']) == '0' and idrac_dhcp == 1:
ch = {'Old': module_network['Network']['DHCP Enabled'],
'New': idrac_dhcp}
ret['changes']['DRAC DHCP'] = ch
if idrac_dhcp == 0 and all([idrac_ip, idrac_netmask, idrac_netmask]):
current_network = __salt__['chassis.cmd']('network_info',
module=name)
old_ipv4 = {}
new_ipv4 = {}
if current_network['Network']['IP Address'] != idrac_ip:
old_ipv4['ip'] = current_network['Network']['IP Address']
new_ipv4['ip'] = idrac_ip
if current_network['Network']['Subnet Mask'] != idrac_netmask:
old_ipv4['netmask'] = current_network['Network']['Subnet Mask']
new_ipv4['netmask'] = idrac_netmask
if current_network['Network']['Gateway'] != idrac_gateway:
old_ipv4['gateway'] = current_network['Network']['Gateway']
new_ipv4['gateway'] = idrac_gateway
if new_ipv4 != {}:
ret['changes']['Network'] = {}
ret['changes']['Network']['Old'] = old_ipv4
ret['changes']['Network']['New'] = new_ipv4
if ret['changes'] == {}:
ret['comment'] = 'iDRAC on blade is already in the desired state.'
return ret
if __opts__['test'] and ret['changes'] != {}:
ret['result'] = None
ret['comment'] = 'iDRAC on blade will change.'
return ret
if 'IPMI' in ret['changes']:
ipmi_result = __salt__['dracr.set_general']('cfgIpmiLan',
'cfgIpmiLanEnable',
idrac_ipmi,
host=current_idrac_ip,
admin_username='root',
admin_password=password)
if not ipmi_result:
ret['result'] = False
ret['changes']['IPMI']['success'] = False
if 'DNSRacName' in ret['changes']:
dnsracname_result = __salt__['dracr.set_dns_dracname'](idrac_dnsname,
host=current_idrac_ip,
admin_username='root',
admin_password=password)
if dnsracname_result['retcode'] == 0:
ret['changes']['DNSRacName']['success'] = True
else:
ret['result'] = False
ret['changes']['DNSRacName']['success'] = False
ret['changes']['DNSRacName']['return'] = dnsracname_result
if 'DRAC DHCP' in ret['changes']:
dhcp_result = __salt__['chassis.cmd']('set_niccfg', dhcp=idrac_dhcp)
if dhcp_result['retcode']:
ret['changes']['DRAC DHCP']['success'] = True
else:
ret['result'] = False
ret['changes']['DRAC DHCP']['success'] = False
ret['changes']['DRAC DHCP']['return'] = dhcp_result
if 'Network' in ret['changes']:
network_result = __salt__['chassis.cmd']('set_niccfg', ip=idrac_ip,
netmask=idrac_netmask,
gateway=idrac_gateway,
module=name)
if network_result['retcode'] == 0:
ret['changes']['Network']['success'] = True
else:
ret['result'] = False
ret['changes']['Network']['success'] = False
ret['changes']['Network']['return'] = network_result
return ret
def chassis(name, chassis_name=None, password=None, datacenter=None,
location=None, mode=None, idrac_launch=None, slot_names=None,
blade_power_states=None):
'''
Manage a Dell Chassis.
chassis_name
The name of the chassis.
datacenter
The datacenter in which the chassis is located
location
The location of the chassis.
password
Password for the chassis. Note: If this password is set for the chassis,
the current implementation of this state will set this password both on
the chassis and the iDrac passwords on any configured blades. If the
password for the blades should be distinct, they should be set separately
with the blade_idrac function.
mode
The management mode of the chassis. Viable options are:
- 0: None
- 1: Monitor
- 2: Manage and Monitor
idrac_launch
The iDRAC launch method of the chassis. Viable options are:
- 0: Disabled (launch iDRAC using IP address)
- 1: Enabled (launch iDRAC using DNS name)
slot_names
The names of the slots, provided as a list identified by
their slot numbers.
blade_power_states
The power states of a blade server, provided as a list and
identified by their server numbers. Viable options are:
- on: Ensure the blade server is powered on.
- off: Ensure the blade server is powered off.
- powercycle: Power cycle the blade server.
Example:
.. code-block:: yaml
my-dell-chassis:
dellchassis.chassis:
- chassis_name: my-dell-chassis
- location: my-location
- datacenter: london
- mode: 2
- idrac_launch: 1
- slot_names:
- 1: my-slot-name
- 2: my-other-slot-name
- blade_power_states:
- server-1: on
- server-2: off
- server-3: powercycle
'''
ret = {'name': chassis_name,
'chassis_name': chassis_name,
'result': True,
'changes': {},
'comment': ''}
chassis_cmd = 'chassis.cmd'
cfg_tuning = 'cfgRacTuning'
mode_cmd = 'cfgRacTuneChassisMgmtAtServer'
launch_cmd = 'cfgRacTuneIdracDNSLaunchEnable'
inventory = __salt__[chassis_cmd]('inventory')
if idrac_launch:
idrac_launch = six.text_type(idrac_launch)
current_name = __salt__[chassis_cmd]('get_chassis_name')
if chassis_name != current_name:
ret['changes'].update({'Name':
{'Old': current_name,
'New': chassis_name}})
current_dc = __salt__[chassis_cmd]('get_chassis_datacenter')
if datacenter and datacenter != current_dc:
ret['changes'].update({'Datacenter':
{'Old': current_dc,
'New': datacenter}})
if password:
ret['changes'].update({'Password':
{'Old': '******',
'New': '******'}})
if location:
current_location = __salt__[chassis_cmd]('get_chassis_location')
if location != current_location:
ret['changes'].update({'Location':
{'Old': current_location,
'New': location}})
if mode:
current_mode = __salt__[chassis_cmd]('get_general', cfg_tuning, mode_cmd)
if mode != current_mode:
ret['changes'].update({'Management Mode':
{'Old': current_mode,
'New': mode}})
if idrac_launch:
current_launch_method = __salt__[chassis_cmd]('get_general', cfg_tuning, launch_cmd)
if idrac_launch != current_launch_method:
ret['changes'].update({'iDrac Launch Method':
{'Old': current_launch_method,
'New': idrac_launch}})
if slot_names:
current_slot_names = __salt__[chassis_cmd]('list_slotnames')
for s in slot_names:
key = s.keys()[0]
new_name = s[key]
if key.startswith('slot-'):
key = key[5:]
current_slot_name = current_slot_names.get(key).get('slotname')
if current_slot_name != new_name:
old = {key: current_slot_name}
new = {key: new_name}
if ret['changes'].get('Slot Names') is None:
ret['changes'].update({'Slot Names':
{'Old': {},
'New': {}}})
ret['changes']['Slot Names']['Old'].update(old)
ret['changes']['Slot Names']['New'].update(new)
current_power_states = {}
target_power_states = {}
if blade_power_states:
for b in blade_power_states:
key = b.keys()[0]
status = __salt__[chassis_cmd]('server_powerstatus', module=key)
current_power_states[key] = status.get('status', -1)
if b[key] == 'powerdown':
if current_power_states[key] != -1 and current_power_states[key]:
target_power_states[key] = 'powerdown'
if b[key] == 'powerup':
if current_power_states[key] != -1 and not current_power_states[key]:
target_power_states[key] = 'powerup'
if b[key] == 'powercycle':
if current_power_states[key] != -1 and not current_power_states[key]:
target_power_states[key] = 'powerup'
if current_power_states[key] != -1 and current_power_states[key]:
target_power_states[key] = 'powercycle'
for k, v in six.iteritems(target_power_states):
old = {k: current_power_states[k]}
new = {k: v}
if ret['changes'].get('Blade Power States') is None:
ret['changes'].update({'Blade Power States':
{'Old': {},
'New': {}}})
ret['changes']['Blade Power States']['Old'].update(old)
ret['changes']['Blade Power States']['New'].update(new)
if ret['changes'] == {}:
ret['comment'] = 'Dell chassis is already in the desired state.'
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Dell chassis configuration will change.'
return ret
# Finally, set the necessary configurations on the chassis.
name = __salt__[chassis_cmd]('set_chassis_name', chassis_name)
if location:
location = __salt__[chassis_cmd]('set_chassis_location', location)
pw_result = True
if password:
pw_single = True
if __salt__[chassis_cmd]('change_password', username='root', uid=1,
password=password):
for blade in inventory['server']:
pw_single = __salt__[chassis_cmd]('deploy_password',
username='root',
password=password,
module=blade)
if not pw_single:
pw_result = False
else:
pw_result = False
if datacenter:
datacenter_result = __salt__[chassis_cmd]('set_chassis_datacenter',
datacenter)
if mode:
mode = __salt__[chassis_cmd]('set_general', cfg_tuning, mode_cmd, mode)
if idrac_launch:
idrac_launch = __salt__[chassis_cmd]('set_general', cfg_tuning, launch_cmd, idrac_launch)
if ret['changes'].get('Slot Names') is not None:
slot_rets = []
for s in slot_names:
key = s.keys()[0]
new_name = s[key]
if key.startswith('slot-'):
key = key[5:]
slot_rets.append(__salt__[chassis_cmd]('set_slotname', key, new_name))
if any(slot_rets) is False:
slot_names = False
else:
slot_names = True
powerchange_all_ok = True
for k, v in six.iteritems(target_power_states):
powerchange_ok = __salt__[chassis_cmd]('server_power', v, module=k)
if not powerchange_ok:
powerchange_all_ok = False
if any([name, location, mode, idrac_launch,
slot_names, powerchange_all_ok]) is False:
ret['result'] = False
ret['comment'] = 'There was an error setting the Dell chassis.'
ret['comment'] = 'Dell chassis was updated.'
return ret
def _firmware_update(firmwarefile='', host='',
directory=''):
'''
Update firmware for a single host
'''
dest = os.path.join(directory, firmwarefile[7:])
__salt__['cp.get_file'](firmwarefile, dest)
username = __pillar__['proxy']['admin_user']
password = __pillar__['proxy']['admin_password']
__salt__['dracr.update_firmware'](dest,
host=host,
admin_username=username,
admin_password=password)
def firmware_update(hosts=None, directory=''):
'''
State to update the firmware on host
using the ``racadm`` command
firmwarefile
filename (string) starting with ``salt://``
host
string representing the hostname
supplied to the ``racadm`` command
directory
Directory name where firmwarefile
will be downloaded
.. code-block:: yaml
dell-chassis-firmware-update:
dellchassis.firmware_update:
hosts:
cmc:
salt://firmware_cmc.exe
server-1:
salt://firmware.exe
directory: /opt/firmwares
'''
ret = {}
ret.changes = {}
success = True
for host, firmwarefile in hosts:
try:
_firmware_update(firmwarefile, host, directory)
ret['changes'].update({
'host': {
'comment': 'Firmware update submitted for {0}'.format(host),
'success': True,
}
})
except CommandExecutionError as err:
success = False
ret['changes'].update({
'host': {
'comment': 'FAILED to update firmware for {0}'.format(host),
'success': False,
'reason': six.text_type(err),
}
})
ret['result'] = success
return ret
|
saltstack/salt
|
salt/states/dellchassis.py
|
_firmware_update
|
python
|
def _firmware_update(firmwarefile='', host='',
directory=''):
'''
Update firmware for a single host
'''
dest = os.path.join(directory, firmwarefile[7:])
__salt__['cp.get_file'](firmwarefile, dest)
username = __pillar__['proxy']['admin_user']
password = __pillar__['proxy']['admin_password']
__salt__['dracr.update_firmware'](dest,
host=host,
admin_username=username,
admin_password=password)
|
Update firmware for a single host
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/dellchassis.py#L667-L681
| null |
# -*- coding: utf-8 -*-
'''
Manage chassis via Salt Proxies.
.. versionadded:: 2015.8.2
Below is an example state that sets basic parameters:
.. code-block:: yaml
my-dell-chassis:
dellchassis.chassis:
- chassis_name: my-dell-chassis
- datacenter: dc-1-us
- location: my-location
- mode: 2
- idrac_launch: 1
- slot_names:
- server-1: my-slot-name
- server-2: my-other-slot-name
- blade_power_states:
- server-1: on
- server-2: off
- server-3: powercycle
However, it is possible to place the entire set of chassis configuration
data in pillar. Here's an example pillar structure:
.. code-block:: yaml
proxy:
host: 10.27.20.18
admin_username: root
fallback_admin_username: root
passwords:
- super-secret
- old-secret
proxytype: fx2
chassis:
name: fx2-1
username: root
password: saltstack1
datacenter: london
location: rack-1-shelf-3
management_mode: 2
idrac_launch: 0
slot_names:
- 'server-1': blade1
- 'server-2': blade2
servers:
server-1:
idrac_password: saltstack1
ipmi_over_lan: True
ip: 172.17.17.132
netmask: 255.255.0.0
gateway: 172.17.17.1
server-2:
idrac_password: saltstack1
ipmi_over_lan: True
ip: 172.17.17.2
netmask: 255.255.0.0
gateway: 172.17.17.1
server-3:
idrac_password: saltstack1
ipmi_over_lan: True
ip: 172.17.17.20
netmask: 255.255.0.0
gateway: 172.17.17.1
server-4:
idrac_password: saltstack1
ipmi_over_lan: True
ip: 172.17.17.2
netmask: 255.255.0.0
gateway: 172.17.17.1
switches:
switch-1:
ip: 192.168.1.2
netmask: 255.255.255.0
gateway: 192.168.1.1
snmp: nonpublic
password: saltstack1
switch-2:
ip: 192.168.1.3
netmask: 255.255.255.0
gateway: 192.168.1.1
snmp: nonpublic
password: saltstack1
And to go with it, here's an example state that pulls the data from the
pillar stated above:
.. code-block:: jinja
{% set details = pillar.get('proxy:chassis', {}) %}
standup-step1:
dellchassis.chassis:
- name: {{ details['name'] }}
- location: {{ details['location'] }}
- mode: {{ details['management_mode'] }}
- idrac_launch: {{ details['idrac_launch'] }}
- slot_names:
{% for entry details['slot_names'] %}
- {{ entry.keys()[0] }}: {{ entry[entry.keys()[0]] }}
{% endfor %}
blade_powercycle:
dellchassis.chassis:
- blade_power_states:
- server-1: powercycle
- server-2: powercycle
- server-3: powercycle
- server-4: powercycle
# Set idrac_passwords for blades. racadm needs them to be called 'server-x'
{% for k, v in details['servers'].iteritems() %}
{{ k }}:
dellchassis.blade_idrac:
- idrac_password: {{ v['idrac_password'] }}
{% endfor %}
# Set management ip addresses, passwords, and snmp strings for switches
{% for k, v in details['switches'].iteritems() %}
{{ k }}-switch-setup:
dellchassis.switch:
- name: {{ k }}
- ip: {{ v['ip'] }}
- netmask: {{ v['netmask'] }}
- gateway: {{ v['gateway'] }}
- password: {{ v['password'] }}
- snmp: {{ v['snmp'] }}
{% endfor %}
.. note::
This state module relies on the dracr.py execution module, which runs racadm commands on
the chassis, blades, etc. The racadm command runs very slowly and, depending on your state,
the proxy minion return might timeout before the racadm commands have completed. If you
are repeatedly seeing minions timeout after state calls, please use the ``-t`` CLI argument
to increase the timeout variable.
For example:
.. code-block:: bash
salt '*' state.sls my-dell-chasis-state-name -t 60
.. note::
The Dell CMC units perform adequately but many iDRACs are **excruciatingly**
slow. Some functions can take minutes to execute.
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import logging
import os
# Import Salt lobs
from salt.ext import six
from salt.exceptions import CommandExecutionError
# Get logging started
log = logging.getLogger(__name__)
def __virtual__():
return 'chassis.cmd' in __salt__
def blade_idrac(name, idrac_password=None, idrac_ipmi=None,
idrac_ip=None, idrac_netmask=None, idrac_gateway=None,
idrac_dnsname=None,
idrac_dhcp=None):
'''
Set parameters for iDRAC in a blade.
:param idrac_password: Password to use to connect to the iDRACs directly
(idrac_ipmi and idrac_dnsname must be set directly on the iDRAC. They
can't be set through the CMC. If this password is present, use it
instead of the CMC password)
:param idrac_ipmi: Enable/Disable IPMI over LAN
:param idrac_ip: Set IP address for iDRAC
:param idrac_netmask: Set netmask for iDRAC
:param idrac_gateway: Set gateway for iDRAC
:param idrac_dhcp: Turn on DHCP for iDRAC (True turns on, False does
nothing becaause setting a static IP will disable DHCP).
:return: A standard Salt changes dictionary
NOTE: If any of the IP address settings is configured, all of ip, netmask,
and gateway must be present
'''
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
if not idrac_password:
(username, password) = __salt__['chassis.chassis_credentials']()
else:
password = idrac_password
module_network = __salt__['chassis.cmd']('network_info', module=name)
current_idrac_ip = module_network['Network']['IP Address']
if idrac_ipmi is not None:
if idrac_ipmi is True or idrac_ipmi == 1:
idrac_ipmi = '1'
if idrac_ipmi is False or idrac_ipmi == 0:
idrac_ipmi = '0'
current_ipmi = __salt__['dracr.get_general']('cfgIpmiLan', 'cfgIpmiLanEnable',
host=current_idrac_ip, admin_username='root',
admin_password=password)
if current_ipmi != idrac_ipmi:
ch = {'Old': current_ipmi, 'New': idrac_ipmi}
ret['changes']['IPMI'] = ch
if idrac_dnsname is not None:
dnsret = __salt__['dracr.get_dns_dracname'](host=current_idrac_ip,
admin_username='root',
admin_password=password)
current_dnsname = dnsret['[Key=iDRAC.Embedded.1#NIC.1]']['DNSRacName']
if current_dnsname != idrac_dnsname:
ch = {'Old': current_dnsname,
'New': idrac_dnsname}
ret['changes']['DNSRacName'] = ch
if idrac_dhcp is not None or idrac_ip or idrac_netmask or idrac_gateway:
if idrac_dhcp is True or idrac_dhcp == 1:
idrac_dhcp = 1
else:
idrac_dhcp = 0
if six.text_type(module_network['Network']['DHCP Enabled']) == '0' and idrac_dhcp == 1:
ch = {'Old': module_network['Network']['DHCP Enabled'],
'New': idrac_dhcp}
ret['changes']['DRAC DHCP'] = ch
if idrac_dhcp == 0 and all([idrac_ip, idrac_netmask, idrac_netmask]):
current_network = __salt__['chassis.cmd']('network_info',
module=name)
old_ipv4 = {}
new_ipv4 = {}
if current_network['Network']['IP Address'] != idrac_ip:
old_ipv4['ip'] = current_network['Network']['IP Address']
new_ipv4['ip'] = idrac_ip
if current_network['Network']['Subnet Mask'] != idrac_netmask:
old_ipv4['netmask'] = current_network['Network']['Subnet Mask']
new_ipv4['netmask'] = idrac_netmask
if current_network['Network']['Gateway'] != idrac_gateway:
old_ipv4['gateway'] = current_network['Network']['Gateway']
new_ipv4['gateway'] = idrac_gateway
if new_ipv4 != {}:
ret['changes']['Network'] = {}
ret['changes']['Network']['Old'] = old_ipv4
ret['changes']['Network']['New'] = new_ipv4
if ret['changes'] == {}:
ret['comment'] = 'iDRAC on blade is already in the desired state.'
return ret
if __opts__['test'] and ret['changes'] != {}:
ret['result'] = None
ret['comment'] = 'iDRAC on blade will change.'
return ret
if 'IPMI' in ret['changes']:
ipmi_result = __salt__['dracr.set_general']('cfgIpmiLan',
'cfgIpmiLanEnable',
idrac_ipmi,
host=current_idrac_ip,
admin_username='root',
admin_password=password)
if not ipmi_result:
ret['result'] = False
ret['changes']['IPMI']['success'] = False
if 'DNSRacName' in ret['changes']:
dnsracname_result = __salt__['dracr.set_dns_dracname'](idrac_dnsname,
host=current_idrac_ip,
admin_username='root',
admin_password=password)
if dnsracname_result['retcode'] == 0:
ret['changes']['DNSRacName']['success'] = True
else:
ret['result'] = False
ret['changes']['DNSRacName']['success'] = False
ret['changes']['DNSRacName']['return'] = dnsracname_result
if 'DRAC DHCP' in ret['changes']:
dhcp_result = __salt__['chassis.cmd']('set_niccfg', dhcp=idrac_dhcp)
if dhcp_result['retcode']:
ret['changes']['DRAC DHCP']['success'] = True
else:
ret['result'] = False
ret['changes']['DRAC DHCP']['success'] = False
ret['changes']['DRAC DHCP']['return'] = dhcp_result
if 'Network' in ret['changes']:
network_result = __salt__['chassis.cmd']('set_niccfg', ip=idrac_ip,
netmask=idrac_netmask,
gateway=idrac_gateway,
module=name)
if network_result['retcode'] == 0:
ret['changes']['Network']['success'] = True
else:
ret['result'] = False
ret['changes']['Network']['success'] = False
ret['changes']['Network']['return'] = network_result
return ret
def chassis(name, chassis_name=None, password=None, datacenter=None,
location=None, mode=None, idrac_launch=None, slot_names=None,
blade_power_states=None):
'''
Manage a Dell Chassis.
chassis_name
The name of the chassis.
datacenter
The datacenter in which the chassis is located
location
The location of the chassis.
password
Password for the chassis. Note: If this password is set for the chassis,
the current implementation of this state will set this password both on
the chassis and the iDrac passwords on any configured blades. If the
password for the blades should be distinct, they should be set separately
with the blade_idrac function.
mode
The management mode of the chassis. Viable options are:
- 0: None
- 1: Monitor
- 2: Manage and Monitor
idrac_launch
The iDRAC launch method of the chassis. Viable options are:
- 0: Disabled (launch iDRAC using IP address)
- 1: Enabled (launch iDRAC using DNS name)
slot_names
The names of the slots, provided as a list identified by
their slot numbers.
blade_power_states
The power states of a blade server, provided as a list and
identified by their server numbers. Viable options are:
- on: Ensure the blade server is powered on.
- off: Ensure the blade server is powered off.
- powercycle: Power cycle the blade server.
Example:
.. code-block:: yaml
my-dell-chassis:
dellchassis.chassis:
- chassis_name: my-dell-chassis
- location: my-location
- datacenter: london
- mode: 2
- idrac_launch: 1
- slot_names:
- 1: my-slot-name
- 2: my-other-slot-name
- blade_power_states:
- server-1: on
- server-2: off
- server-3: powercycle
'''
ret = {'name': chassis_name,
'chassis_name': chassis_name,
'result': True,
'changes': {},
'comment': ''}
chassis_cmd = 'chassis.cmd'
cfg_tuning = 'cfgRacTuning'
mode_cmd = 'cfgRacTuneChassisMgmtAtServer'
launch_cmd = 'cfgRacTuneIdracDNSLaunchEnable'
inventory = __salt__[chassis_cmd]('inventory')
if idrac_launch:
idrac_launch = six.text_type(idrac_launch)
current_name = __salt__[chassis_cmd]('get_chassis_name')
if chassis_name != current_name:
ret['changes'].update({'Name':
{'Old': current_name,
'New': chassis_name}})
current_dc = __salt__[chassis_cmd]('get_chassis_datacenter')
if datacenter and datacenter != current_dc:
ret['changes'].update({'Datacenter':
{'Old': current_dc,
'New': datacenter}})
if password:
ret['changes'].update({'Password':
{'Old': '******',
'New': '******'}})
if location:
current_location = __salt__[chassis_cmd]('get_chassis_location')
if location != current_location:
ret['changes'].update({'Location':
{'Old': current_location,
'New': location}})
if mode:
current_mode = __salt__[chassis_cmd]('get_general', cfg_tuning, mode_cmd)
if mode != current_mode:
ret['changes'].update({'Management Mode':
{'Old': current_mode,
'New': mode}})
if idrac_launch:
current_launch_method = __salt__[chassis_cmd]('get_general', cfg_tuning, launch_cmd)
if idrac_launch != current_launch_method:
ret['changes'].update({'iDrac Launch Method':
{'Old': current_launch_method,
'New': idrac_launch}})
if slot_names:
current_slot_names = __salt__[chassis_cmd]('list_slotnames')
for s in slot_names:
key = s.keys()[0]
new_name = s[key]
if key.startswith('slot-'):
key = key[5:]
current_slot_name = current_slot_names.get(key).get('slotname')
if current_slot_name != new_name:
old = {key: current_slot_name}
new = {key: new_name}
if ret['changes'].get('Slot Names') is None:
ret['changes'].update({'Slot Names':
{'Old': {},
'New': {}}})
ret['changes']['Slot Names']['Old'].update(old)
ret['changes']['Slot Names']['New'].update(new)
current_power_states = {}
target_power_states = {}
if blade_power_states:
for b in blade_power_states:
key = b.keys()[0]
status = __salt__[chassis_cmd]('server_powerstatus', module=key)
current_power_states[key] = status.get('status', -1)
if b[key] == 'powerdown':
if current_power_states[key] != -1 and current_power_states[key]:
target_power_states[key] = 'powerdown'
if b[key] == 'powerup':
if current_power_states[key] != -1 and not current_power_states[key]:
target_power_states[key] = 'powerup'
if b[key] == 'powercycle':
if current_power_states[key] != -1 and not current_power_states[key]:
target_power_states[key] = 'powerup'
if current_power_states[key] != -1 and current_power_states[key]:
target_power_states[key] = 'powercycle'
for k, v in six.iteritems(target_power_states):
old = {k: current_power_states[k]}
new = {k: v}
if ret['changes'].get('Blade Power States') is None:
ret['changes'].update({'Blade Power States':
{'Old': {},
'New': {}}})
ret['changes']['Blade Power States']['Old'].update(old)
ret['changes']['Blade Power States']['New'].update(new)
if ret['changes'] == {}:
ret['comment'] = 'Dell chassis is already in the desired state.'
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Dell chassis configuration will change.'
return ret
# Finally, set the necessary configurations on the chassis.
name = __salt__[chassis_cmd]('set_chassis_name', chassis_name)
if location:
location = __salt__[chassis_cmd]('set_chassis_location', location)
pw_result = True
if password:
pw_single = True
if __salt__[chassis_cmd]('change_password', username='root', uid=1,
password=password):
for blade in inventory['server']:
pw_single = __salt__[chassis_cmd]('deploy_password',
username='root',
password=password,
module=blade)
if not pw_single:
pw_result = False
else:
pw_result = False
if datacenter:
datacenter_result = __salt__[chassis_cmd]('set_chassis_datacenter',
datacenter)
if mode:
mode = __salt__[chassis_cmd]('set_general', cfg_tuning, mode_cmd, mode)
if idrac_launch:
idrac_launch = __salt__[chassis_cmd]('set_general', cfg_tuning, launch_cmd, idrac_launch)
if ret['changes'].get('Slot Names') is not None:
slot_rets = []
for s in slot_names:
key = s.keys()[0]
new_name = s[key]
if key.startswith('slot-'):
key = key[5:]
slot_rets.append(__salt__[chassis_cmd]('set_slotname', key, new_name))
if any(slot_rets) is False:
slot_names = False
else:
slot_names = True
powerchange_all_ok = True
for k, v in six.iteritems(target_power_states):
powerchange_ok = __salt__[chassis_cmd]('server_power', v, module=k)
if not powerchange_ok:
powerchange_all_ok = False
if any([name, location, mode, idrac_launch,
slot_names, powerchange_all_ok]) is False:
ret['result'] = False
ret['comment'] = 'There was an error setting the Dell chassis.'
ret['comment'] = 'Dell chassis was updated.'
return ret
def switch(name, ip=None, netmask=None, gateway=None, dhcp=None,
password=None, snmp=None):
'''
Manage switches in a Dell Chassis.
name
The switch designation (e.g. switch-1, switch-2)
ip
The Static IP Address of the switch
netmask
The netmask for the static IP
gateway
The gateway for the static IP
dhcp
True: Enable DHCP
False: Do not change DHCP setup
(disabling DHCP is automatic when a static IP is set)
password
The access (root) password for the switch
snmp
The SNMP community string for the switch
Example:
.. code-block:: yaml
my-dell-chassis:
dellchassis.switch:
- switch: switch-1
- ip: 192.168.1.1
- netmask: 255.255.255.0
- gateway: 192.168.1.254
- dhcp: True
- password: secret
- snmp: public
'''
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
current_nic = __salt__['chassis.cmd']('network_info', module=name)
try:
if current_nic.get('retcode', 0) != 0:
ret['result'] = False
ret['comment'] = current_nic['stdout']
return ret
if ip or netmask or gateway:
if not ip:
ip = current_nic['Network']['IP Address']
if not netmask:
ip = current_nic['Network']['Subnet Mask']
if not gateway:
ip = current_nic['Network']['Gateway']
if current_nic['Network']['DHCP Enabled'] == '0' and dhcp:
ret['changes'].update({'DHCP': {'Old': {'DHCP Enabled': current_nic['Network']['DHCP Enabled']},
'New': {'DHCP Enabled': dhcp}}})
if ((ip or netmask or gateway) and not dhcp and (ip != current_nic['Network']['IP Address'] or
netmask != current_nic['Network']['Subnet Mask'] or
gateway != current_nic['Network']['Gateway'])):
ret['changes'].update({'IP': {'Old': current_nic['Network'],
'New': {'IP Address': ip,
'Subnet Mask': netmask,
'Gateway': gateway}}})
if password:
if 'New' not in ret['changes']:
ret['changes']['New'] = {}
ret['changes']['New'].update({'Password': '*****'})
if snmp:
if 'New' not in ret['changes']:
ret['changes']['New'] = {}
ret['changes']['New'].update({'SNMP': '*****'})
if ret['changes'] == {}:
ret['comment'] = 'Switch ' + name + ' is already in desired state'
return ret
except AttributeError:
ret['changes'] = {}
ret['comment'] = 'Something went wrong retrieving the switch details'
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Switch ' + name + ' configuration will change'
return ret
# Finally, set the necessary configurations on the chassis.
dhcp_ret = net_ret = password_ret = snmp_ret = True
if dhcp:
dhcp_ret = __salt__['chassis.cmd']('set_niccfg', module=name, dhcp=dhcp)
if ip or netmask or gateway:
net_ret = __salt__['chassis.cmd']('set_niccfg', ip, netmask, gateway, module=name)
if password:
password_ret = __salt__['chassis.cmd']('deploy_password', 'root', password, module=name)
if snmp:
snmp_ret = __salt__['chassis.cmd']('deploy_snmp', snmp, module=name)
if any([password_ret, snmp_ret, net_ret, dhcp_ret]) is False:
ret['result'] = False
ret['comment'] = 'There was an error setting the switch {0}.'.format(name)
ret['comment'] = 'Dell chassis switch {0} was updated.'.format(name)
return ret
def firmware_update(hosts=None, directory=''):
'''
State to update the firmware on host
using the ``racadm`` command
firmwarefile
filename (string) starting with ``salt://``
host
string representing the hostname
supplied to the ``racadm`` command
directory
Directory name where firmwarefile
will be downloaded
.. code-block:: yaml
dell-chassis-firmware-update:
dellchassis.firmware_update:
hosts:
cmc:
salt://firmware_cmc.exe
server-1:
salt://firmware.exe
directory: /opt/firmwares
'''
ret = {}
ret.changes = {}
success = True
for host, firmwarefile in hosts:
try:
_firmware_update(firmwarefile, host, directory)
ret['changes'].update({
'host': {
'comment': 'Firmware update submitted for {0}'.format(host),
'success': True,
}
})
except CommandExecutionError as err:
success = False
ret['changes'].update({
'host': {
'comment': 'FAILED to update firmware for {0}'.format(host),
'success': False,
'reason': six.text_type(err),
}
})
ret['result'] = success
return ret
|
saltstack/salt
|
salt/states/dellchassis.py
|
firmware_update
|
python
|
def firmware_update(hosts=None, directory=''):
'''
State to update the firmware on host
using the ``racadm`` command
firmwarefile
filename (string) starting with ``salt://``
host
string representing the hostname
supplied to the ``racadm`` command
directory
Directory name where firmwarefile
will be downloaded
.. code-block:: yaml
dell-chassis-firmware-update:
dellchassis.firmware_update:
hosts:
cmc:
salt://firmware_cmc.exe
server-1:
salt://firmware.exe
directory: /opt/firmwares
'''
ret = {}
ret.changes = {}
success = True
for host, firmwarefile in hosts:
try:
_firmware_update(firmwarefile, host, directory)
ret['changes'].update({
'host': {
'comment': 'Firmware update submitted for {0}'.format(host),
'success': True,
}
})
except CommandExecutionError as err:
success = False
ret['changes'].update({
'host': {
'comment': 'FAILED to update firmware for {0}'.format(host),
'success': False,
'reason': six.text_type(err),
}
})
ret['result'] = success
return ret
|
State to update the firmware on host
using the ``racadm`` command
firmwarefile
filename (string) starting with ``salt://``
host
string representing the hostname
supplied to the ``racadm`` command
directory
Directory name where firmwarefile
will be downloaded
.. code-block:: yaml
dell-chassis-firmware-update:
dellchassis.firmware_update:
hosts:
cmc:
salt://firmware_cmc.exe
server-1:
salt://firmware.exe
directory: /opt/firmwares
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/dellchassis.py#L684-L731
|
[
"def _firmware_update(firmwarefile='', host='',\n directory=''):\n '''\n Update firmware for a single host\n '''\n dest = os.path.join(directory, firmwarefile[7:])\n\n __salt__['cp.get_file'](firmwarefile, dest)\n\n username = __pillar__['proxy']['admin_user']\n password = __pillar__['proxy']['admin_password']\n __salt__['dracr.update_firmware'](dest,\n host=host,\n admin_username=username,\n admin_password=password)\n"
] |
# -*- coding: utf-8 -*-
'''
Manage chassis via Salt Proxies.
.. versionadded:: 2015.8.2
Below is an example state that sets basic parameters:
.. code-block:: yaml
my-dell-chassis:
dellchassis.chassis:
- chassis_name: my-dell-chassis
- datacenter: dc-1-us
- location: my-location
- mode: 2
- idrac_launch: 1
- slot_names:
- server-1: my-slot-name
- server-2: my-other-slot-name
- blade_power_states:
- server-1: on
- server-2: off
- server-3: powercycle
However, it is possible to place the entire set of chassis configuration
data in pillar. Here's an example pillar structure:
.. code-block:: yaml
proxy:
host: 10.27.20.18
admin_username: root
fallback_admin_username: root
passwords:
- super-secret
- old-secret
proxytype: fx2
chassis:
name: fx2-1
username: root
password: saltstack1
datacenter: london
location: rack-1-shelf-3
management_mode: 2
idrac_launch: 0
slot_names:
- 'server-1': blade1
- 'server-2': blade2
servers:
server-1:
idrac_password: saltstack1
ipmi_over_lan: True
ip: 172.17.17.132
netmask: 255.255.0.0
gateway: 172.17.17.1
server-2:
idrac_password: saltstack1
ipmi_over_lan: True
ip: 172.17.17.2
netmask: 255.255.0.0
gateway: 172.17.17.1
server-3:
idrac_password: saltstack1
ipmi_over_lan: True
ip: 172.17.17.20
netmask: 255.255.0.0
gateway: 172.17.17.1
server-4:
idrac_password: saltstack1
ipmi_over_lan: True
ip: 172.17.17.2
netmask: 255.255.0.0
gateway: 172.17.17.1
switches:
switch-1:
ip: 192.168.1.2
netmask: 255.255.255.0
gateway: 192.168.1.1
snmp: nonpublic
password: saltstack1
switch-2:
ip: 192.168.1.3
netmask: 255.255.255.0
gateway: 192.168.1.1
snmp: nonpublic
password: saltstack1
And to go with it, here's an example state that pulls the data from the
pillar stated above:
.. code-block:: jinja
{% set details = pillar.get('proxy:chassis', {}) %}
standup-step1:
dellchassis.chassis:
- name: {{ details['name'] }}
- location: {{ details['location'] }}
- mode: {{ details['management_mode'] }}
- idrac_launch: {{ details['idrac_launch'] }}
- slot_names:
{% for entry details['slot_names'] %}
- {{ entry.keys()[0] }}: {{ entry[entry.keys()[0]] }}
{% endfor %}
blade_powercycle:
dellchassis.chassis:
- blade_power_states:
- server-1: powercycle
- server-2: powercycle
- server-3: powercycle
- server-4: powercycle
# Set idrac_passwords for blades. racadm needs them to be called 'server-x'
{% for k, v in details['servers'].iteritems() %}
{{ k }}:
dellchassis.blade_idrac:
- idrac_password: {{ v['idrac_password'] }}
{% endfor %}
# Set management ip addresses, passwords, and snmp strings for switches
{% for k, v in details['switches'].iteritems() %}
{{ k }}-switch-setup:
dellchassis.switch:
- name: {{ k }}
- ip: {{ v['ip'] }}
- netmask: {{ v['netmask'] }}
- gateway: {{ v['gateway'] }}
- password: {{ v['password'] }}
- snmp: {{ v['snmp'] }}
{% endfor %}
.. note::
This state module relies on the dracr.py execution module, which runs racadm commands on
the chassis, blades, etc. The racadm command runs very slowly and, depending on your state,
the proxy minion return might timeout before the racadm commands have completed. If you
are repeatedly seeing minions timeout after state calls, please use the ``-t`` CLI argument
to increase the timeout variable.
For example:
.. code-block:: bash
salt '*' state.sls my-dell-chasis-state-name -t 60
.. note::
The Dell CMC units perform adequately but many iDRACs are **excruciatingly**
slow. Some functions can take minutes to execute.
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import logging
import os
# Import Salt lobs
from salt.ext import six
from salt.exceptions import CommandExecutionError
# Get logging started
log = logging.getLogger(__name__)
def __virtual__():
return 'chassis.cmd' in __salt__
def blade_idrac(name, idrac_password=None, idrac_ipmi=None,
idrac_ip=None, idrac_netmask=None, idrac_gateway=None,
idrac_dnsname=None,
idrac_dhcp=None):
'''
Set parameters for iDRAC in a blade.
:param idrac_password: Password to use to connect to the iDRACs directly
(idrac_ipmi and idrac_dnsname must be set directly on the iDRAC. They
can't be set through the CMC. If this password is present, use it
instead of the CMC password)
:param idrac_ipmi: Enable/Disable IPMI over LAN
:param idrac_ip: Set IP address for iDRAC
:param idrac_netmask: Set netmask for iDRAC
:param idrac_gateway: Set gateway for iDRAC
:param idrac_dhcp: Turn on DHCP for iDRAC (True turns on, False does
nothing becaause setting a static IP will disable DHCP).
:return: A standard Salt changes dictionary
NOTE: If any of the IP address settings is configured, all of ip, netmask,
and gateway must be present
'''
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
if not idrac_password:
(username, password) = __salt__['chassis.chassis_credentials']()
else:
password = idrac_password
module_network = __salt__['chassis.cmd']('network_info', module=name)
current_idrac_ip = module_network['Network']['IP Address']
if idrac_ipmi is not None:
if idrac_ipmi is True or idrac_ipmi == 1:
idrac_ipmi = '1'
if idrac_ipmi is False or idrac_ipmi == 0:
idrac_ipmi = '0'
current_ipmi = __salt__['dracr.get_general']('cfgIpmiLan', 'cfgIpmiLanEnable',
host=current_idrac_ip, admin_username='root',
admin_password=password)
if current_ipmi != idrac_ipmi:
ch = {'Old': current_ipmi, 'New': idrac_ipmi}
ret['changes']['IPMI'] = ch
if idrac_dnsname is not None:
dnsret = __salt__['dracr.get_dns_dracname'](host=current_idrac_ip,
admin_username='root',
admin_password=password)
current_dnsname = dnsret['[Key=iDRAC.Embedded.1#NIC.1]']['DNSRacName']
if current_dnsname != idrac_dnsname:
ch = {'Old': current_dnsname,
'New': idrac_dnsname}
ret['changes']['DNSRacName'] = ch
if idrac_dhcp is not None or idrac_ip or idrac_netmask or idrac_gateway:
if idrac_dhcp is True or idrac_dhcp == 1:
idrac_dhcp = 1
else:
idrac_dhcp = 0
if six.text_type(module_network['Network']['DHCP Enabled']) == '0' and idrac_dhcp == 1:
ch = {'Old': module_network['Network']['DHCP Enabled'],
'New': idrac_dhcp}
ret['changes']['DRAC DHCP'] = ch
if idrac_dhcp == 0 and all([idrac_ip, idrac_netmask, idrac_netmask]):
current_network = __salt__['chassis.cmd']('network_info',
module=name)
old_ipv4 = {}
new_ipv4 = {}
if current_network['Network']['IP Address'] != idrac_ip:
old_ipv4['ip'] = current_network['Network']['IP Address']
new_ipv4['ip'] = idrac_ip
if current_network['Network']['Subnet Mask'] != idrac_netmask:
old_ipv4['netmask'] = current_network['Network']['Subnet Mask']
new_ipv4['netmask'] = idrac_netmask
if current_network['Network']['Gateway'] != idrac_gateway:
old_ipv4['gateway'] = current_network['Network']['Gateway']
new_ipv4['gateway'] = idrac_gateway
if new_ipv4 != {}:
ret['changes']['Network'] = {}
ret['changes']['Network']['Old'] = old_ipv4
ret['changes']['Network']['New'] = new_ipv4
if ret['changes'] == {}:
ret['comment'] = 'iDRAC on blade is already in the desired state.'
return ret
if __opts__['test'] and ret['changes'] != {}:
ret['result'] = None
ret['comment'] = 'iDRAC on blade will change.'
return ret
if 'IPMI' in ret['changes']:
ipmi_result = __salt__['dracr.set_general']('cfgIpmiLan',
'cfgIpmiLanEnable',
idrac_ipmi,
host=current_idrac_ip,
admin_username='root',
admin_password=password)
if not ipmi_result:
ret['result'] = False
ret['changes']['IPMI']['success'] = False
if 'DNSRacName' in ret['changes']:
dnsracname_result = __salt__['dracr.set_dns_dracname'](idrac_dnsname,
host=current_idrac_ip,
admin_username='root',
admin_password=password)
if dnsracname_result['retcode'] == 0:
ret['changes']['DNSRacName']['success'] = True
else:
ret['result'] = False
ret['changes']['DNSRacName']['success'] = False
ret['changes']['DNSRacName']['return'] = dnsracname_result
if 'DRAC DHCP' in ret['changes']:
dhcp_result = __salt__['chassis.cmd']('set_niccfg', dhcp=idrac_dhcp)
if dhcp_result['retcode']:
ret['changes']['DRAC DHCP']['success'] = True
else:
ret['result'] = False
ret['changes']['DRAC DHCP']['success'] = False
ret['changes']['DRAC DHCP']['return'] = dhcp_result
if 'Network' in ret['changes']:
network_result = __salt__['chassis.cmd']('set_niccfg', ip=idrac_ip,
netmask=idrac_netmask,
gateway=idrac_gateway,
module=name)
if network_result['retcode'] == 0:
ret['changes']['Network']['success'] = True
else:
ret['result'] = False
ret['changes']['Network']['success'] = False
ret['changes']['Network']['return'] = network_result
return ret
def chassis(name, chassis_name=None, password=None, datacenter=None,
location=None, mode=None, idrac_launch=None, slot_names=None,
blade_power_states=None):
'''
Manage a Dell Chassis.
chassis_name
The name of the chassis.
datacenter
The datacenter in which the chassis is located
location
The location of the chassis.
password
Password for the chassis. Note: If this password is set for the chassis,
the current implementation of this state will set this password both on
the chassis and the iDrac passwords on any configured blades. If the
password for the blades should be distinct, they should be set separately
with the blade_idrac function.
mode
The management mode of the chassis. Viable options are:
- 0: None
- 1: Monitor
- 2: Manage and Monitor
idrac_launch
The iDRAC launch method of the chassis. Viable options are:
- 0: Disabled (launch iDRAC using IP address)
- 1: Enabled (launch iDRAC using DNS name)
slot_names
The names of the slots, provided as a list identified by
their slot numbers.
blade_power_states
The power states of a blade server, provided as a list and
identified by their server numbers. Viable options are:
- on: Ensure the blade server is powered on.
- off: Ensure the blade server is powered off.
- powercycle: Power cycle the blade server.
Example:
.. code-block:: yaml
my-dell-chassis:
dellchassis.chassis:
- chassis_name: my-dell-chassis
- location: my-location
- datacenter: london
- mode: 2
- idrac_launch: 1
- slot_names:
- 1: my-slot-name
- 2: my-other-slot-name
- blade_power_states:
- server-1: on
- server-2: off
- server-3: powercycle
'''
ret = {'name': chassis_name,
'chassis_name': chassis_name,
'result': True,
'changes': {},
'comment': ''}
chassis_cmd = 'chassis.cmd'
cfg_tuning = 'cfgRacTuning'
mode_cmd = 'cfgRacTuneChassisMgmtAtServer'
launch_cmd = 'cfgRacTuneIdracDNSLaunchEnable'
inventory = __salt__[chassis_cmd]('inventory')
if idrac_launch:
idrac_launch = six.text_type(idrac_launch)
current_name = __salt__[chassis_cmd]('get_chassis_name')
if chassis_name != current_name:
ret['changes'].update({'Name':
{'Old': current_name,
'New': chassis_name}})
current_dc = __salt__[chassis_cmd]('get_chassis_datacenter')
if datacenter and datacenter != current_dc:
ret['changes'].update({'Datacenter':
{'Old': current_dc,
'New': datacenter}})
if password:
ret['changes'].update({'Password':
{'Old': '******',
'New': '******'}})
if location:
current_location = __salt__[chassis_cmd]('get_chassis_location')
if location != current_location:
ret['changes'].update({'Location':
{'Old': current_location,
'New': location}})
if mode:
current_mode = __salt__[chassis_cmd]('get_general', cfg_tuning, mode_cmd)
if mode != current_mode:
ret['changes'].update({'Management Mode':
{'Old': current_mode,
'New': mode}})
if idrac_launch:
current_launch_method = __salt__[chassis_cmd]('get_general', cfg_tuning, launch_cmd)
if idrac_launch != current_launch_method:
ret['changes'].update({'iDrac Launch Method':
{'Old': current_launch_method,
'New': idrac_launch}})
if slot_names:
current_slot_names = __salt__[chassis_cmd]('list_slotnames')
for s in slot_names:
key = s.keys()[0]
new_name = s[key]
if key.startswith('slot-'):
key = key[5:]
current_slot_name = current_slot_names.get(key).get('slotname')
if current_slot_name != new_name:
old = {key: current_slot_name}
new = {key: new_name}
if ret['changes'].get('Slot Names') is None:
ret['changes'].update({'Slot Names':
{'Old': {},
'New': {}}})
ret['changes']['Slot Names']['Old'].update(old)
ret['changes']['Slot Names']['New'].update(new)
current_power_states = {}
target_power_states = {}
if blade_power_states:
for b in blade_power_states:
key = b.keys()[0]
status = __salt__[chassis_cmd]('server_powerstatus', module=key)
current_power_states[key] = status.get('status', -1)
if b[key] == 'powerdown':
if current_power_states[key] != -1 and current_power_states[key]:
target_power_states[key] = 'powerdown'
if b[key] == 'powerup':
if current_power_states[key] != -1 and not current_power_states[key]:
target_power_states[key] = 'powerup'
if b[key] == 'powercycle':
if current_power_states[key] != -1 and not current_power_states[key]:
target_power_states[key] = 'powerup'
if current_power_states[key] != -1 and current_power_states[key]:
target_power_states[key] = 'powercycle'
for k, v in six.iteritems(target_power_states):
old = {k: current_power_states[k]}
new = {k: v}
if ret['changes'].get('Blade Power States') is None:
ret['changes'].update({'Blade Power States':
{'Old': {},
'New': {}}})
ret['changes']['Blade Power States']['Old'].update(old)
ret['changes']['Blade Power States']['New'].update(new)
if ret['changes'] == {}:
ret['comment'] = 'Dell chassis is already in the desired state.'
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Dell chassis configuration will change.'
return ret
# Finally, set the necessary configurations on the chassis.
name = __salt__[chassis_cmd]('set_chassis_name', chassis_name)
if location:
location = __salt__[chassis_cmd]('set_chassis_location', location)
pw_result = True
if password:
pw_single = True
if __salt__[chassis_cmd]('change_password', username='root', uid=1,
password=password):
for blade in inventory['server']:
pw_single = __salt__[chassis_cmd]('deploy_password',
username='root',
password=password,
module=blade)
if not pw_single:
pw_result = False
else:
pw_result = False
if datacenter:
datacenter_result = __salt__[chassis_cmd]('set_chassis_datacenter',
datacenter)
if mode:
mode = __salt__[chassis_cmd]('set_general', cfg_tuning, mode_cmd, mode)
if idrac_launch:
idrac_launch = __salt__[chassis_cmd]('set_general', cfg_tuning, launch_cmd, idrac_launch)
if ret['changes'].get('Slot Names') is not None:
slot_rets = []
for s in slot_names:
key = s.keys()[0]
new_name = s[key]
if key.startswith('slot-'):
key = key[5:]
slot_rets.append(__salt__[chassis_cmd]('set_slotname', key, new_name))
if any(slot_rets) is False:
slot_names = False
else:
slot_names = True
powerchange_all_ok = True
for k, v in six.iteritems(target_power_states):
powerchange_ok = __salt__[chassis_cmd]('server_power', v, module=k)
if not powerchange_ok:
powerchange_all_ok = False
if any([name, location, mode, idrac_launch,
slot_names, powerchange_all_ok]) is False:
ret['result'] = False
ret['comment'] = 'There was an error setting the Dell chassis.'
ret['comment'] = 'Dell chassis was updated.'
return ret
def switch(name, ip=None, netmask=None, gateway=None, dhcp=None,
password=None, snmp=None):
'''
Manage switches in a Dell Chassis.
name
The switch designation (e.g. switch-1, switch-2)
ip
The Static IP Address of the switch
netmask
The netmask for the static IP
gateway
The gateway for the static IP
dhcp
True: Enable DHCP
False: Do not change DHCP setup
(disabling DHCP is automatic when a static IP is set)
password
The access (root) password for the switch
snmp
The SNMP community string for the switch
Example:
.. code-block:: yaml
my-dell-chassis:
dellchassis.switch:
- switch: switch-1
- ip: 192.168.1.1
- netmask: 255.255.255.0
- gateway: 192.168.1.254
- dhcp: True
- password: secret
- snmp: public
'''
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
current_nic = __salt__['chassis.cmd']('network_info', module=name)
try:
if current_nic.get('retcode', 0) != 0:
ret['result'] = False
ret['comment'] = current_nic['stdout']
return ret
if ip or netmask or gateway:
if not ip:
ip = current_nic['Network']['IP Address']
if not netmask:
ip = current_nic['Network']['Subnet Mask']
if not gateway:
ip = current_nic['Network']['Gateway']
if current_nic['Network']['DHCP Enabled'] == '0' and dhcp:
ret['changes'].update({'DHCP': {'Old': {'DHCP Enabled': current_nic['Network']['DHCP Enabled']},
'New': {'DHCP Enabled': dhcp}}})
if ((ip or netmask or gateway) and not dhcp and (ip != current_nic['Network']['IP Address'] or
netmask != current_nic['Network']['Subnet Mask'] or
gateway != current_nic['Network']['Gateway'])):
ret['changes'].update({'IP': {'Old': current_nic['Network'],
'New': {'IP Address': ip,
'Subnet Mask': netmask,
'Gateway': gateway}}})
if password:
if 'New' not in ret['changes']:
ret['changes']['New'] = {}
ret['changes']['New'].update({'Password': '*****'})
if snmp:
if 'New' not in ret['changes']:
ret['changes']['New'] = {}
ret['changes']['New'].update({'SNMP': '*****'})
if ret['changes'] == {}:
ret['comment'] = 'Switch ' + name + ' is already in desired state'
return ret
except AttributeError:
ret['changes'] = {}
ret['comment'] = 'Something went wrong retrieving the switch details'
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Switch ' + name + ' configuration will change'
return ret
# Finally, set the necessary configurations on the chassis.
dhcp_ret = net_ret = password_ret = snmp_ret = True
if dhcp:
dhcp_ret = __salt__['chassis.cmd']('set_niccfg', module=name, dhcp=dhcp)
if ip or netmask or gateway:
net_ret = __salt__['chassis.cmd']('set_niccfg', ip, netmask, gateway, module=name)
if password:
password_ret = __salt__['chassis.cmd']('deploy_password', 'root', password, module=name)
if snmp:
snmp_ret = __salt__['chassis.cmd']('deploy_snmp', snmp, module=name)
if any([password_ret, snmp_ret, net_ret, dhcp_ret]) is False:
ret['result'] = False
ret['comment'] = 'There was an error setting the switch {0}.'.format(name)
ret['comment'] = 'Dell chassis switch {0} was updated.'.format(name)
return ret
def _firmware_update(firmwarefile='', host='',
directory=''):
'''
Update firmware for a single host
'''
dest = os.path.join(directory, firmwarefile[7:])
__salt__['cp.get_file'](firmwarefile, dest)
username = __pillar__['proxy']['admin_user']
password = __pillar__['proxy']['admin_password']
__salt__['dracr.update_firmware'](dest,
host=host,
admin_username=username,
admin_password=password)
|
saltstack/salt
|
salt/transport/tcp.py
|
_set_tcp_keepalive
|
python
|
def _set_tcp_keepalive(sock, opts):
'''
Ensure that TCP keepalives are set for the socket.
'''
if hasattr(socket, 'SO_KEEPALIVE'):
if opts.get('tcp_keepalive', False):
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
if hasattr(socket, 'SOL_TCP'):
if hasattr(socket, 'TCP_KEEPIDLE'):
tcp_keepalive_idle = opts.get('tcp_keepalive_idle', -1)
if tcp_keepalive_idle > 0:
sock.setsockopt(
socket.SOL_TCP, socket.TCP_KEEPIDLE,
int(tcp_keepalive_idle))
if hasattr(socket, 'TCP_KEEPCNT'):
tcp_keepalive_cnt = opts.get('tcp_keepalive_cnt', -1)
if tcp_keepalive_cnt > 0:
sock.setsockopt(
socket.SOL_TCP, socket.TCP_KEEPCNT,
int(tcp_keepalive_cnt))
if hasattr(socket, 'TCP_KEEPINTVL'):
tcp_keepalive_intvl = opts.get('tcp_keepalive_intvl', -1)
if tcp_keepalive_intvl > 0:
sock.setsockopt(
socket.SOL_TCP, socket.TCP_KEEPINTVL,
int(tcp_keepalive_intvl))
if hasattr(socket, 'SIO_KEEPALIVE_VALS'):
# Windows doesn't support TCP_KEEPIDLE, TCP_KEEPCNT, nor
# TCP_KEEPINTVL. Instead, it has its own proprietary
# SIO_KEEPALIVE_VALS.
tcp_keepalive_idle = opts.get('tcp_keepalive_idle', -1)
tcp_keepalive_intvl = opts.get('tcp_keepalive_intvl', -1)
# Windows doesn't support changing something equivalent to
# TCP_KEEPCNT.
if tcp_keepalive_idle > 0 or tcp_keepalive_intvl > 0:
# Windows defaults may be found by using the link below.
# Search for 'KeepAliveTime' and 'KeepAliveInterval'.
# https://technet.microsoft.com/en-us/library/bb726981.aspx#EDAA
# If one value is set and the other isn't, we still need
# to send both values to SIO_KEEPALIVE_VALS and they both
# need to be valid. So in that case, use the Windows
# default.
if tcp_keepalive_idle <= 0:
tcp_keepalive_idle = 7200
if tcp_keepalive_intvl <= 0:
tcp_keepalive_intvl = 1
# The values expected are in milliseconds, so multiply by
# 1000.
sock.ioctl(socket.SIO_KEEPALIVE_VALS, (
1, int(tcp_keepalive_idle * 1000),
int(tcp_keepalive_intvl * 1000)))
else:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 0)
|
Ensure that TCP keepalives are set for the socket.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/tcp.py#L83-L135
| null |
# -*- coding: utf-8 -*-
'''
TCP transport classes
Wire protocol: "len(payload) msgpack({'head': SOMEHEADER, 'body': SOMEBODY})"
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import errno
import logging
import socket
import os
import weakref
import time
import threading
import traceback
# Import Salt Libs
import salt.crypt
import salt.utils.asynchronous
import salt.utils.event
import salt.utils.files
import salt.utils.msgpack
import salt.utils.platform
import salt.utils.process
import salt.utils.verify
import salt.payload
import salt.exceptions
import salt.transport.frame
import salt.transport.ipc
import salt.transport.client
import salt.transport.server
import salt.transport.mixins.auth
from salt.ext import six
from salt.ext.six.moves import queue # pylint: disable=import-error
from salt.exceptions import SaltReqTimeoutError, SaltClientError
from salt.transport import iter_transport_opts
# Import Tornado Libs
import tornado
import tornado.tcpserver
import tornado.gen
import tornado.concurrent
import tornado.tcpclient
import tornado.netutil
from tornado.iostream import StreamClosedError
# pylint: disable=import-error,no-name-in-module
if six.PY2:
import urlparse
else:
import urllib.parse as urlparse
# pylint: enable=import-error,no-name-in-module
# Import third party libs
import msgpack
try:
from M2Crypto import RSA
HAS_M2 = True
except ImportError:
HAS_M2 = False
try:
from Cryptodome.Cipher import PKCS1_OAEP
except ImportError:
from Crypto.Cipher import PKCS1_OAEP
if six.PY3 and salt.utils.platform.is_windows():
USE_LOAD_BALANCER = True
else:
USE_LOAD_BALANCER = False
if USE_LOAD_BALANCER:
import threading
import multiprocessing
import tornado.util
from salt.utils.process import SignalHandlingMultiprocessingProcess
log = logging.getLogger(__name__)
if USE_LOAD_BALANCER:
class LoadBalancerServer(SignalHandlingMultiprocessingProcess):
'''
Raw TCP server which runs in its own process and will listen
for incoming connections. Each incoming connection will be
sent via multiprocessing queue to the workers.
Since the queue is shared amongst workers, only one worker will
handle a given connection.
'''
# TODO: opts!
# Based on default used in tornado.netutil.bind_sockets()
backlog = 128
def __init__(self, opts, socket_queue, **kwargs):
super(LoadBalancerServer, self).__init__(**kwargs)
self.opts = opts
self.socket_queue = socket_queue
self._socket = None
# __setstate__ and __getstate__ are only used on Windows.
# We do this so that __init__ will be invoked on Windows in the child
# process so that a register_after_fork() equivalent will work on
# Windows.
def __setstate__(self, state):
self._is_child = True
self.__init__(
state['opts'],
state['socket_queue'],
log_queue=state['log_queue'],
log_queue_level=state['log_queue_level']
)
def __getstate__(self):
return {
'opts': self.opts,
'socket_queue': self.socket_queue,
'log_queue': self.log_queue,
'log_queue_level': self.log_queue_level
}
def close(self):
if self._socket is not None:
self._socket.shutdown(socket.SHUT_RDWR)
self._socket.close()
self._socket = None
def __del__(self):
self.close()
def run(self):
'''
Start the load balancer
'''
self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
_set_tcp_keepalive(self._socket, self.opts)
self._socket.setblocking(1)
self._socket.bind((self.opts['interface'], int(self.opts['ret_port'])))
self._socket.listen(self.backlog)
while True:
try:
# Wait for a connection to occur since the socket is
# blocking.
connection, address = self._socket.accept()
# Wait for a free slot to be available to put
# the connection into.
# Sockets are picklable on Windows in Python 3.
self.socket_queue.put((connection, address), True, None)
except socket.error as e:
# ECONNABORTED indicates that there was a connection
# but it was closed while still in the accept queue.
# (observed on FreeBSD).
if tornado.util.errno_from_exception(e) == errno.ECONNABORTED:
continue
raise
# TODO: move serial down into message library
class AsyncTCPReqChannel(salt.transport.client.ReqChannel):
'''
Encapsulate sending routines to tcp.
Note: this class returns a singleton
'''
# This class is only a singleton per minion/master pair
# mapping of io_loop -> {key -> channel}
instance_map = weakref.WeakKeyDictionary()
def __new__(cls, opts, **kwargs):
'''
Only create one instance of channel per __key()
'''
# do we have any mapping for this io_loop
io_loop = kwargs.get('io_loop') or tornado.ioloop.IOLoop.current()
if io_loop not in cls.instance_map:
cls.instance_map[io_loop] = weakref.WeakValueDictionary()
loop_instance_map = cls.instance_map[io_loop]
key = cls.__key(opts, **kwargs)
obj = loop_instance_map.get(key)
if obj is None:
log.debug('Initializing new AsyncTCPReqChannel for %s', key)
# we need to make a local variable for this, as we are going to store
# it in a WeakValueDictionary-- which will remove the item if no one
# references it-- this forces a reference while we return to the caller
obj = object.__new__(cls)
obj.__singleton_init__(opts, **kwargs)
obj._instance_key = key
loop_instance_map[key] = obj
obj._refcount = 1
obj._refcount_lock = threading.RLock()
else:
with obj._refcount_lock:
obj._refcount += 1
log.debug('Re-using AsyncTCPReqChannel for %s', key)
return obj
@classmethod
def __key(cls, opts, **kwargs):
if 'master_uri' in kwargs:
opts['master_uri'] = kwargs['master_uri']
return (opts['pki_dir'], # where the keys are stored
opts['id'], # minion ID
opts['master_uri'],
kwargs.get('crypt', 'aes'), # TODO: use the same channel for crypt
)
# has to remain empty for singletons, since __init__ will *always* be called
def __init__(self, opts, **kwargs):
pass
# an init for the singleton instance to call
def __singleton_init__(self, opts, **kwargs):
self.opts = dict(opts)
self.serial = salt.payload.Serial(self.opts)
# crypt defaults to 'aes'
self.crypt = kwargs.get('crypt', 'aes')
self.io_loop = kwargs.get('io_loop') or tornado.ioloop.IOLoop.current()
if self.crypt != 'clear':
self.auth = salt.crypt.AsyncAuth(self.opts, io_loop=self.io_loop)
resolver = kwargs.get('resolver')
parse = urlparse.urlparse(self.opts['master_uri'])
master_host, master_port = parse.netloc.rsplit(':', 1)
self.master_addr = (master_host, int(master_port))
self._closing = False
self.message_client = SaltMessageClientPool(self.opts,
args=(self.opts, master_host, int(master_port),),
kwargs={'io_loop': self.io_loop, 'resolver': resolver,
'source_ip': self.opts.get('source_ip'),
'source_port': self.opts.get('source_ret_port')})
def close(self):
if self._closing:
return
if self._refcount > 1:
# Decrease refcount
with self._refcount_lock:
self._refcount -= 1
log.debug(
'This is not the last %s instance. Not closing yet.',
self.__class__.__name__
)
return
log.debug('Closing %s instance', self.__class__.__name__)
self._closing = True
self.message_client.close()
# Remove the entry from the instance map so that a closed entry may not
# be reused.
# This forces this operation even if the reference count of the entry
# has not yet gone to zero.
if self.io_loop in self.__class__.instance_map:
loop_instance_map = self.__class__.instance_map[self.io_loop]
if self._instance_key in loop_instance_map:
del loop_instance_map[self._instance_key]
if not loop_instance_map:
del self.__class__.instance_map[self.io_loop]
def __del__(self):
with self._refcount_lock:
# Make sure we actually close no matter if something
# went wrong with our ref counting
self._refcount = 1
try:
self.close()
except socket.error as exc:
if exc.errno != errno.EBADF:
# If its not a bad file descriptor error, raise
raise
def _package_load(self, load):
return {
'enc': self.crypt,
'load': load,
}
@tornado.gen.coroutine
def crypted_transfer_decode_dictentry(self, load, dictkey=None, tries=3, timeout=60):
if not self.auth.authenticated:
yield self.auth.authenticate()
ret = yield self.message_client.send(self._package_load(self.auth.crypticle.dumps(load)), timeout=timeout)
key = self.auth.get_keys()
if HAS_M2:
aes = key.private_decrypt(ret['key'], RSA.pkcs1_oaep_padding)
else:
cipher = PKCS1_OAEP.new(key)
aes = cipher.decrypt(ret['key'])
pcrypt = salt.crypt.Crypticle(self.opts, aes)
data = pcrypt.loads(ret[dictkey])
if six.PY3:
data = salt.transport.frame.decode_embedded_strs(data)
raise tornado.gen.Return(data)
@tornado.gen.coroutine
def _crypted_transfer(self, load, tries=3, timeout=60):
'''
In case of authentication errors, try to renegotiate authentication
and retry the method.
Indeed, we can fail too early in case of a master restart during a
minion state execution call
'''
@tornado.gen.coroutine
def _do_transfer():
data = yield self.message_client.send(self._package_load(self.auth.crypticle.dumps(load)),
timeout=timeout,
)
# we may not have always data
# as for example for saltcall ret submission, this is a blind
# communication, we do not subscribe to return events, we just
# upload the results to the master
if data:
data = self.auth.crypticle.loads(data)
if six.PY3:
data = salt.transport.frame.decode_embedded_strs(data)
raise tornado.gen.Return(data)
if not self.auth.authenticated:
yield self.auth.authenticate()
try:
ret = yield _do_transfer()
raise tornado.gen.Return(ret)
except salt.crypt.AuthenticationError:
yield self.auth.authenticate()
ret = yield _do_transfer()
raise tornado.gen.Return(ret)
@tornado.gen.coroutine
def _uncrypted_transfer(self, load, tries=3, timeout=60):
ret = yield self.message_client.send(self._package_load(load), timeout=timeout)
raise tornado.gen.Return(ret)
@tornado.gen.coroutine
def send(self, load, tries=3, timeout=60, raw=False):
'''
Send a request, return a future which will complete when we send the message
'''
try:
if self.crypt == 'clear':
ret = yield self._uncrypted_transfer(load, tries=tries, timeout=timeout)
else:
ret = yield self._crypted_transfer(load, tries=tries, timeout=timeout)
except StreamClosedError:
# Convert to 'SaltClientError' so that clients can handle this
# exception more appropriately.
raise SaltClientError('Connection to master lost')
raise tornado.gen.Return(ret)
class AsyncTCPPubChannel(salt.transport.mixins.auth.AESPubClientMixin, salt.transport.client.AsyncPubChannel):
def __init__(self,
opts,
**kwargs):
self.opts = opts
self.serial = salt.payload.Serial(self.opts)
self.crypt = kwargs.get('crypt', 'aes')
self.io_loop = kwargs.get('io_loop') or tornado.ioloop.IOLoop.current()
self.connected = False
self._closing = False
self._reconnected = False
self.event = salt.utils.event.get_event(
'minion',
opts=self.opts,
listen=False
)
def close(self):
if self._closing:
return
self._closing = True
if hasattr(self, 'message_client'):
self.message_client.close()
def __del__(self):
self.close()
def _package_load(self, load):
return {
'enc': self.crypt,
'load': load,
}
@tornado.gen.coroutine
def send_id(self, tok, force_auth):
'''
Send the minion id to the master so that the master may better
track the connection state of the minion.
In case of authentication errors, try to renegotiate authentication
and retry the method.
'''
load = {'id': self.opts['id'], 'tok': tok}
@tornado.gen.coroutine
def _do_transfer():
msg = self._package_load(self.auth.crypticle.dumps(load))
package = salt.transport.frame.frame_msg(msg, header=None)
yield self.message_client.write_to_stream(package)
raise tornado.gen.Return(True)
if force_auth or not self.auth.authenticated:
count = 0
while count <= self.opts['tcp_authentication_retries'] or self.opts['tcp_authentication_retries'] < 0:
try:
yield self.auth.authenticate()
break
except SaltClientError as exc:
log.debug(exc)
count += 1
try:
ret = yield _do_transfer()
raise tornado.gen.Return(ret)
except salt.crypt.AuthenticationError:
yield self.auth.authenticate()
ret = yield _do_transfer()
raise tornado.gen.Return(ret)
@tornado.gen.coroutine
def connect_callback(self, result):
if self._closing:
return
# Force re-auth on reconnect since the master
# may have been restarted
yield self.send_id(self.tok, self._reconnected)
self.connected = True
self.event.fire_event(
{'master': self.opts['master']},
'__master_connected'
)
if self._reconnected:
# On reconnects, fire a master event to notify that the minion is
# available.
if self.opts.get('__role') == 'syndic':
data = 'Syndic {0} started at {1}'.format(
self.opts['id'],
time.asctime()
)
tag = salt.utils.event.tagify(
[self.opts['id'], 'start'],
'syndic'
)
else:
data = 'Minion {0} started at {1}'.format(
self.opts['id'],
time.asctime()
)
tag = salt.utils.event.tagify(
[self.opts['id'], 'start'],
'minion'
)
load = {'id': self.opts['id'],
'cmd': '_minion_event',
'pretag': None,
'tok': self.tok,
'data': data,
'tag': tag}
req_channel = salt.utils.asynchronous.SyncWrapper(
AsyncTCPReqChannel, (self.opts,)
)
try:
req_channel.send(load, timeout=60)
except salt.exceptions.SaltReqTimeoutError:
log.info('fire_master failed: master could not be contacted. Request timed out.')
except Exception:
log.info('fire_master failed: %s', traceback.format_exc())
finally:
# SyncWrapper will call either close() or destroy(), whichever is available
del req_channel
else:
self._reconnected = True
def disconnect_callback(self):
if self._closing:
return
self.connected = False
self.event.fire_event(
{'master': self.opts['master']},
'__master_disconnected'
)
@tornado.gen.coroutine
def connect(self):
try:
self.auth = salt.crypt.AsyncAuth(self.opts, io_loop=self.io_loop)
self.tok = self.auth.gen_token(b'salt')
if not self.auth.authenticated:
yield self.auth.authenticate()
if self.auth.authenticated:
# if this is changed from the default, we assume it was intentional
if int(self.opts.get('publish_port', 4505)) != 4505:
self.publish_port = self.opts.get('publish_port')
# else take the relayed publish_port master reports
else:
self.publish_port = self.auth.creds['publish_port']
self.message_client = SaltMessageClientPool(
self.opts,
args=(self.opts, self.opts['master_ip'], int(self.publish_port),),
kwargs={'io_loop': self.io_loop,
'connect_callback': self.connect_callback,
'disconnect_callback': self.disconnect_callback,
'source_ip': self.opts.get('source_ip'),
'source_port': self.opts.get('source_publish_port')})
yield self.message_client.connect() # wait for the client to be connected
self.connected = True
# TODO: better exception handling...
except KeyboardInterrupt:
raise
except Exception as exc:
if '-|RETRY|-' not in six.text_type(exc):
raise SaltClientError('Unable to sign_in to master: {0}'.format(exc)) # TODO: better error message
def on_recv(self, callback):
'''
Register an on_recv callback
'''
if callback is None:
return self.message_client.on_recv(callback)
@tornado.gen.coroutine
def wrap_callback(body):
if not isinstance(body, dict):
# TODO: For some reason we need to decode here for things
# to work. Fix this.
body = salt.utils.msgpack.loads(body)
if six.PY3:
body = salt.transport.frame.decode_embedded_strs(body)
ret = yield self._decode_payload(body)
callback(ret)
return self.message_client.on_recv(wrap_callback)
class TCPReqServerChannel(salt.transport.mixins.auth.AESReqServerMixin, salt.transport.server.ReqServerChannel):
# TODO: opts!
backlog = 5
def __init__(self, opts):
salt.transport.server.ReqServerChannel.__init__(self, opts)
self._socket = None
@property
def socket(self):
return self._socket
def close(self):
if self._socket is not None:
try:
self._socket.shutdown(socket.SHUT_RDWR)
except socket.error as exc:
if exc.errno == errno.ENOTCONN:
# We may try to shutdown a socket which is already disconnected.
# Ignore this condition and continue.
pass
else:
raise exc
self._socket.close()
self._socket = None
if hasattr(self.req_server, 'stop'):
try:
self.req_server.stop()
except Exception as exc:
log.exception('TCPReqServerChannel close generated an exception: %s', str(exc))
def __del__(self):
self.close()
def pre_fork(self, process_manager):
'''
Pre-fork we need to create the zmq router device
'''
salt.transport.mixins.auth.AESReqServerMixin.pre_fork(self, process_manager)
if USE_LOAD_BALANCER:
self.socket_queue = multiprocessing.Queue()
process_manager.add_process(
LoadBalancerServer, args=(self.opts, self.socket_queue)
)
elif not salt.utils.platform.is_windows():
self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
_set_tcp_keepalive(self._socket, self.opts)
self._socket.setblocking(0)
self._socket.bind((self.opts['interface'], int(self.opts['ret_port'])))
def post_fork(self, payload_handler, io_loop):
'''
After forking we need to create all of the local sockets to listen to the
router
payload_handler: function to call with your payloads
'''
self.payload_handler = payload_handler
self.io_loop = io_loop
self.serial = salt.payload.Serial(self.opts)
with salt.utils.asynchronous.current_ioloop(self.io_loop):
if USE_LOAD_BALANCER:
self.req_server = LoadBalancerWorker(self.socket_queue,
self.handle_message,
ssl_options=self.opts.get('ssl'))
else:
if salt.utils.platform.is_windows():
self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
_set_tcp_keepalive(self._socket, self.opts)
self._socket.setblocking(0)
self._socket.bind((self.opts['interface'], int(self.opts['ret_port'])))
self.req_server = SaltMessageServer(self.handle_message,
ssl_options=self.opts.get('ssl'))
self.req_server.add_socket(self._socket)
self._socket.listen(self.backlog)
salt.transport.mixins.auth.AESReqServerMixin.post_fork(self, payload_handler, io_loop)
@tornado.gen.coroutine
def handle_message(self, stream, header, payload):
'''
Handle incoming messages from underylying tcp streams
'''
try:
try:
payload = self._decode_payload(payload)
except Exception:
stream.write(salt.transport.frame.frame_msg('bad load', header=header))
raise tornado.gen.Return()
# TODO helper functions to normalize payload?
if not isinstance(payload, dict) or not isinstance(payload.get('load'), dict):
yield stream.write(salt.transport.frame.frame_msg(
'payload and load must be a dict', header=header))
raise tornado.gen.Return()
try:
id_ = payload['load'].get('id', '')
if str('\0') in id_:
log.error('Payload contains an id with a null byte: %s', payload)
stream.send(self.serial.dumps('bad load: id contains a null byte'))
raise tornado.gen.Return()
except TypeError:
log.error('Payload contains non-string id: %s', payload)
stream.send(self.serial.dumps('bad load: id {0} is not a string'.format(id_)))
raise tornado.gen.Return()
# intercept the "_auth" commands, since the main daemon shouldn't know
# anything about our key auth
if payload['enc'] == 'clear' and payload.get('load', {}).get('cmd') == '_auth':
yield stream.write(salt.transport.frame.frame_msg(
self._auth(payload['load']), header=header))
raise tornado.gen.Return()
# TODO: test
try:
ret, req_opts = yield self.payload_handler(payload)
except Exception as e:
# always attempt to return an error to the minion
stream.write('Some exception handling minion payload')
log.error('Some exception handling a payload from minion', exc_info=True)
stream.close()
raise tornado.gen.Return()
req_fun = req_opts.get('fun', 'send')
if req_fun == 'send_clear':
stream.write(salt.transport.frame.frame_msg(ret, header=header))
elif req_fun == 'send':
stream.write(salt.transport.frame.frame_msg(self.crypticle.dumps(ret), header=header))
elif req_fun == 'send_private':
stream.write(salt.transport.frame.frame_msg(self._encrypt_private(ret,
req_opts['key'],
req_opts['tgt'],
), header=header))
else:
log.error('Unknown req_fun %s', req_fun)
# always attempt to return an error to the minion
stream.write('Server-side exception handling payload')
stream.close()
except tornado.gen.Return:
raise
except StreamClosedError:
# Stream was closed. This could happen if the remote side
# closed the connection on its end (eg in a timeout or shutdown
# situation).
log.error('Connection was unexpectedly closed', exc_info=True)
except Exception as exc: # pylint: disable=broad-except
# Absorb any other exceptions
log.error('Unexpected exception occurred: %s', exc, exc_info=True)
raise tornado.gen.Return()
class SaltMessageServer(tornado.tcpserver.TCPServer, object):
'''
Raw TCP server which will receive all of the TCP streams and re-assemble
messages that are sent through to us
'''
def __init__(self, message_handler, *args, **kwargs):
super(SaltMessageServer, self).__init__(*args, **kwargs)
self.io_loop = tornado.ioloop.IOLoop.current()
self.clients = []
self.message_handler = message_handler
@tornado.gen.coroutine
def handle_stream(self, stream, address):
'''
Handle incoming streams and add messages to the incoming queue
'''
log.trace('Req client %s connected', address)
self.clients.append((stream, address))
unpacker = msgpack.Unpacker()
try:
while True:
wire_bytes = yield stream.read_bytes(4096, partial=True)
unpacker.feed(wire_bytes)
for framed_msg in unpacker:
if six.PY3:
framed_msg = salt.transport.frame.decode_embedded_strs(
framed_msg
)
header = framed_msg['head']
self.io_loop.spawn_callback(self.message_handler, stream, header, framed_msg['body'])
except StreamClosedError:
log.trace('req client disconnected %s', address)
self.clients.remove((stream, address))
except Exception as e:
log.trace('other master-side exception: %s', e)
self.clients.remove((stream, address))
stream.close()
def shutdown(self):
'''
Shutdown the whole server
'''
for item in self.clients:
client, address = item
client.close()
self.clients.remove(item)
if USE_LOAD_BALANCER:
class LoadBalancerWorker(SaltMessageServer):
'''
This will receive TCP connections from 'LoadBalancerServer' via
a multiprocessing queue.
Since the queue is shared amongst workers, only one worker will handle
a given connection.
'''
def __init__(self, socket_queue, message_handler, *args, **kwargs):
super(LoadBalancerWorker, self).__init__(
message_handler, *args, **kwargs)
self.socket_queue = socket_queue
self._stop = threading.Event()
self.thread = threading.Thread(target=self.socket_queue_thread)
self.thread.start()
def stop(self):
self._stop.set()
self.thread.join()
def socket_queue_thread(self):
try:
while True:
try:
client_socket, address = self.socket_queue.get(True, 1)
except queue.Empty:
if self._stop.is_set():
break
continue
# 'self.io_loop' initialized in super class
# 'tornado.tcpserver.TCPServer'.
# 'self._handle_connection' defined in same super class.
self.io_loop.spawn_callback(
self._handle_connection, client_socket, address)
except (KeyboardInterrupt, SystemExit):
pass
class TCPClientKeepAlive(tornado.tcpclient.TCPClient):
'''
Override _create_stream() in TCPClient to enable keep alive support.
'''
def __init__(self, opts, resolver=None):
self.opts = opts
super(TCPClientKeepAlive, self).__init__(resolver=resolver)
def _create_stream(self, max_buffer_size, af, addr, **kwargs): # pylint: disable=unused-argument
'''
Override _create_stream() in TCPClient.
Tornado 4.5 added the kwargs 'source_ip' and 'source_port'.
Due to this, use **kwargs to swallow these and any future
kwargs to maintain compatibility.
'''
# Always connect in plaintext; we'll convert to ssl if necessary
# after one connection has completed.
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
_set_tcp_keepalive(sock, self.opts)
stream = tornado.iostream.IOStream(
sock,
max_buffer_size=max_buffer_size)
if tornado.version_info < (5,):
return stream.connect(addr)
return stream, stream.connect(addr)
class SaltMessageClientPool(salt.transport.MessageClientPool):
'''
Wrapper class of SaltMessageClient to avoid blocking waiting while writing data to socket.
'''
def __init__(self, opts, args=None, kwargs=None):
super(SaltMessageClientPool, self).__init__(SaltMessageClient, opts, args=args, kwargs=kwargs)
def __del__(self):
self.close()
def close(self):
for message_client in self.message_clients:
message_client.close()
self.message_clients = []
@tornado.gen.coroutine
def connect(self):
futures = []
for message_client in self.message_clients:
futures.append(message_client.connect())
for future in futures:
yield future
raise tornado.gen.Return(None)
def on_recv(self, *args, **kwargs):
for message_client in self.message_clients:
message_client.on_recv(*args, **kwargs)
def send(self, *args, **kwargs):
message_clients = sorted(self.message_clients, key=lambda x: len(x.send_queue))
return message_clients[0].send(*args, **kwargs)
def write_to_stream(self, *args, **kwargs):
message_clients = sorted(self.message_clients, key=lambda x: len(x.send_queue))
return message_clients[0]._stream.write(*args, **kwargs)
# TODO consolidate with IPCClient
# TODO: limit in-flight messages.
# TODO: singleton? Something to not re-create the tcp connection so much
class SaltMessageClient(object):
'''
Low-level message sending client
'''
def __init__(self, opts, host, port, io_loop=None, resolver=None,
connect_callback=None, disconnect_callback=None,
source_ip=None, source_port=None):
self.opts = opts
self.host = host
self.port = port
self.source_ip = source_ip
self.source_port = source_port
self.connect_callback = connect_callback
self.disconnect_callback = disconnect_callback
self.io_loop = io_loop or tornado.ioloop.IOLoop.current()
with salt.utils.asynchronous.current_ioloop(self.io_loop):
self._tcp_client = TCPClientKeepAlive(opts, resolver=resolver)
self._mid = 1
self._max_messages = int((1 << 31) - 2) # number of IDs before we wrap
# TODO: max queue size
self.send_queue = [] # queue of messages to be sent
self.send_future_map = {} # mapping of request_id -> Future
self.send_timeout_map = {} # request_id -> timeout_callback
self._read_until_future = None
self._on_recv = None
self._closing = False
self._connecting_future = self.connect()
self._stream_return_future = tornado.concurrent.Future()
self.io_loop.spawn_callback(self._stream_return)
# TODO: timeout inflight sessions
def close(self):
if self._closing:
return
self._closing = True
if hasattr(self, '_stream') and not self._stream.closed():
# If _stream_return() hasn't completed, it means the IO
# Loop is stopped (such as when using
# 'salt.utils.asynchronous.SyncWrapper'). Ensure that
# _stream_return() completes by restarting the IO Loop.
# This will prevent potential errors on shutdown.
try:
orig_loop = tornado.ioloop.IOLoop.current()
self.io_loop.make_current()
self._stream.close()
if self._read_until_future is not None:
# This will prevent this message from showing up:
# '[ERROR ] Future exception was never retrieved:
# StreamClosedError'
# This happens because the logic is always waiting to read
# the next message and the associated read future is marked
# 'StreamClosedError' when the stream is closed.
if self._read_until_future.done():
self._read_until_future.exception()
elif self.io_loop != tornado.ioloop.IOLoop.current(instance=False):
self.io_loop.add_future(
self._stream_return_future,
lambda future: self.io_loop.stop()
)
self.io_loop.start()
finally:
orig_loop.make_current()
self._tcp_client.close()
# Clear callback references to allow the object that they belong to
# to be deleted.
self.connect_callback = None
self.disconnect_callback = None
def __del__(self):
self.close()
def connect(self):
'''
Ask for this client to reconnect to the origin
'''
if hasattr(self, '_connecting_future') and not self._connecting_future.done():
future = self._connecting_future
else:
future = tornado.concurrent.Future()
self._connecting_future = future
self.io_loop.add_callback(self._connect)
# Add the callback only when a new future is created
if self.connect_callback is not None:
def handle_future(future):
response = future.result()
self.io_loop.add_callback(self.connect_callback, response)
future.add_done_callback(handle_future)
return future
# TODO: tcp backoff opts
@tornado.gen.coroutine
def _connect(self):
'''
Try to connect for the rest of time!
'''
while True:
if self._closing:
break
try:
kwargs = {}
if self.source_ip or self.source_port:
if tornado.version_info >= (4, 5):
### source_ip and source_port are supported only in Tornado >= 4.5
# See http://www.tornadoweb.org/en/stable/releases/v4.5.0.html
# Otherwise will just ignore these args
kwargs = {'source_ip': self.source_ip,
'source_port': self.source_port}
else:
log.warning('If you need a certain source IP/port, consider upgrading Tornado >= 4.5')
with salt.utils.asynchronous.current_ioloop(self.io_loop):
self._stream = yield self._tcp_client.connect(self.host,
self.port,
ssl_options=self.opts.get('ssl'),
**kwargs)
self._connecting_future.set_result(True)
break
except Exception as e:
yield tornado.gen.sleep(1) # TODO: backoff
#self._connecting_future.set_exception(e)
@tornado.gen.coroutine
def _stream_return(self):
try:
while not self._closing and (
not self._connecting_future.done() or
self._connecting_future.result() is not True):
yield self._connecting_future
unpacker = msgpack.Unpacker()
while not self._closing:
try:
self._read_until_future = self._stream.read_bytes(4096, partial=True)
wire_bytes = yield self._read_until_future
unpacker.feed(wire_bytes)
for framed_msg in unpacker:
if six.PY3:
framed_msg = salt.transport.frame.decode_embedded_strs(
framed_msg
)
header = framed_msg['head']
body = framed_msg['body']
message_id = header.get('mid')
if message_id in self.send_future_map:
self.send_future_map.pop(message_id).set_result(body)
self.remove_message_timeout(message_id)
else:
if self._on_recv is not None:
self.io_loop.spawn_callback(self._on_recv, header, body)
else:
log.error('Got response for message_id %s that we are not tracking', message_id)
except StreamClosedError as e:
log.debug('tcp stream to %s:%s closed, unable to recv', self.host, self.port)
for future in six.itervalues(self.send_future_map):
future.set_exception(e)
self.send_future_map = {}
if self._closing:
return
if self.disconnect_callback:
self.disconnect_callback()
# if the last connect finished, then we need to make a new one
if self._connecting_future.done():
self._connecting_future = self.connect()
yield self._connecting_future
except TypeError:
# This is an invalid transport
if 'detect_mode' in self.opts:
log.info('There was an error trying to use TCP transport; '
'attempting to fallback to another transport')
else:
raise SaltClientError
except Exception as e:
log.error('Exception parsing response', exc_info=True)
for future in six.itervalues(self.send_future_map):
future.set_exception(e)
self.send_future_map = {}
if self._closing:
return
if self.disconnect_callback:
self.disconnect_callback()
# if the last connect finished, then we need to make a new one
if self._connecting_future.done():
self._connecting_future = self.connect()
yield self._connecting_future
finally:
self._stream_return_future.set_result(True)
@tornado.gen.coroutine
def _stream_send(self):
while not self._connecting_future.done() or self._connecting_future.result() is not True:
yield self._connecting_future
while self.send_queue:
message_id, item = self.send_queue[0]
try:
yield self._stream.write(item)
del self.send_queue[0]
# if the connection is dead, lets fail this send, and make sure we
# attempt to reconnect
except StreamClosedError as e:
if message_id in self.send_future_map:
self.send_future_map.pop(message_id).set_exception(e)
self.remove_message_timeout(message_id)
del self.send_queue[0]
if self._closing:
return
if self.disconnect_callback:
self.disconnect_callback()
# if the last connect finished, then we need to make a new one
if self._connecting_future.done():
self._connecting_future = self.connect()
yield self._connecting_future
def _message_id(self):
wrap = False
while self._mid in self.send_future_map:
if self._mid >= self._max_messages:
if wrap:
# this shouldn't ever happen, but just in case
raise Exception('Unable to find available messageid')
self._mid = 1
wrap = True
else:
self._mid += 1
return self._mid
# TODO: return a message object which takes care of multiplexing?
def on_recv(self, callback):
'''
Register a callback for received messages (that we didn't initiate)
'''
if callback is None:
self._on_recv = callback
else:
def wrap_recv(header, body):
callback(body)
self._on_recv = wrap_recv
def remove_message_timeout(self, message_id):
if message_id not in self.send_timeout_map:
return
timeout = self.send_timeout_map.pop(message_id)
self.io_loop.remove_timeout(timeout)
def timeout_message(self, message_id):
if message_id in self.send_timeout_map:
del self.send_timeout_map[message_id]
if message_id in self.send_future_map:
self.send_future_map.pop(message_id).set_exception(
SaltReqTimeoutError('Message timed out')
)
def send(self, msg, timeout=None, callback=None, raw=False):
'''
Send given message, and return a future
'''
message_id = self._message_id()
header = {'mid': message_id}
future = tornado.concurrent.Future()
if callback is not None:
def handle_future(future):
response = future.result()
self.io_loop.add_callback(callback, response)
future.add_done_callback(handle_future)
# Add this future to the mapping
self.send_future_map[message_id] = future
if self.opts.get('detect_mode') is True:
timeout = 1
if timeout is not None:
send_timeout = self.io_loop.call_later(timeout, self.timeout_message, message_id)
self.send_timeout_map[message_id] = send_timeout
# if we don't have a send queue, we need to spawn the callback to do the sending
if not self.send_queue:
self.io_loop.spawn_callback(self._stream_send)
self.send_queue.append((message_id, salt.transport.frame.frame_msg(msg, header=header)))
return future
class Subscriber(object):
'''
Client object for use with the TCP publisher server
'''
def __init__(self, stream, address):
self.stream = stream
self.address = address
self._closing = False
self._read_until_future = None
self.id_ = None
def close(self):
if self._closing:
return
self._closing = True
if not self.stream.closed():
self.stream.close()
if self._read_until_future is not None and self._read_until_future.done():
# This will prevent this message from showing up:
# '[ERROR ] Future exception was never retrieved:
# StreamClosedError'
# This happens because the logic is always waiting to read
# the next message and the associated read future is marked
# 'StreamClosedError' when the stream is closed.
self._read_until_future.exception()
def __del__(self):
self.close()
class PubServer(tornado.tcpserver.TCPServer, object):
'''
TCP publisher
'''
def __init__(self, opts, io_loop=None):
super(PubServer, self).__init__(ssl_options=opts.get('ssl'))
self.io_loop = io_loop
self.opts = opts
self._closing = False
self.clients = set()
self.aes_funcs = salt.master.AESFuncs(self.opts)
self.present = {}
self.presence_events = False
if self.opts.get('presence_events', False):
tcp_only = True
for transport, _ in iter_transport_opts(self.opts):
if transport != 'tcp':
tcp_only = False
if tcp_only:
# Only when the transport is TCP only, the presence events will
# be handled here. Otherwise, it will be handled in the
# 'Maintenance' process.
self.presence_events = True
if self.presence_events:
self.event = salt.utils.event.get_event(
'master',
opts=self.opts,
listen=False
)
def close(self):
if self._closing:
return
self._closing = True
def __del__(self):
self.close()
def _add_client_present(self, client):
id_ = client.id_
if id_ in self.present:
clients = self.present[id_]
clients.add(client)
else:
self.present[id_] = {client}
if self.presence_events:
data = {'new': [id_],
'lost': []}
self.event.fire_event(
data,
salt.utils.event.tagify('change', 'presence')
)
data = {'present': list(self.present.keys())}
self.event.fire_event(
data,
salt.utils.event.tagify('present', 'presence')
)
def _remove_client_present(self, client):
id_ = client.id_
if id_ is None or id_ not in self.present:
# This is possible if _remove_client_present() is invoked
# before the minion's id is validated.
return
clients = self.present[id_]
if client not in clients:
# Since _remove_client_present() is potentially called from
# _stream_read() and/or publish_payload(), it is possible for
# it to be called twice, in which case we will get here.
# This is not an abnormal case, so no logging is required.
return
clients.remove(client)
if not clients:
del self.present[id_]
if self.presence_events:
data = {'new': [],
'lost': [id_]}
self.event.fire_event(
data,
salt.utils.event.tagify('change', 'presence')
)
data = {'present': list(self.present.keys())}
self.event.fire_event(
data,
salt.utils.event.tagify('present', 'presence')
)
@tornado.gen.coroutine
def _stream_read(self, client):
unpacker = msgpack.Unpacker()
while not self._closing:
try:
client._read_until_future = client.stream.read_bytes(4096, partial=True)
wire_bytes = yield client._read_until_future
unpacker.feed(wire_bytes)
for framed_msg in unpacker:
if six.PY3:
framed_msg = salt.transport.frame.decode_embedded_strs(
framed_msg
)
body = framed_msg['body']
if body['enc'] != 'aes':
# We only accept 'aes' encoded messages for 'id'
continue
crypticle = salt.crypt.Crypticle(self.opts, salt.master.SMaster.secrets['aes']['secret'].value)
load = crypticle.loads(body['load'])
if six.PY3:
load = salt.transport.frame.decode_embedded_strs(load)
if not self.aes_funcs.verify_minion(load['id'], load['tok']):
continue
client.id_ = load['id']
self._add_client_present(client)
except StreamClosedError as e:
log.debug('tcp stream to %s closed, unable to recv', client.address)
client.close()
self._remove_client_present(client)
self.clients.discard(client)
break
except Exception as e:
log.error('Exception parsing response from %s', client.address, exc_info=True)
continue
def handle_stream(self, stream, address):
log.trace('Subscriber at %s connected', address)
client = Subscriber(stream, address)
self.clients.add(client)
self.io_loop.spawn_callback(self._stream_read, client)
# TODO: ACK the publish through IPC
@tornado.gen.coroutine
def publish_payload(self, package, _):
log.debug('TCP PubServer sending payload: %s', package)
payload = salt.transport.frame.frame_msg(package['payload'])
to_remove = []
if 'topic_lst' in package:
topic_lst = package['topic_lst']
for topic in topic_lst:
if topic in self.present:
# This will rarely be a list of more than 1 item. It will
# be more than 1 item if the minion disconnects from the
# master in an unclean manner (eg cable yank), then
# restarts and the master is yet to detect the disconnect
# via TCP keep-alive.
for client in self.present[topic]:
try:
# Write the packed str
f = client.stream.write(payload)
self.io_loop.add_future(f, lambda f: True)
except StreamClosedError:
to_remove.append(client)
else:
log.debug('Publish target %s not connected', topic)
else:
for client in self.clients:
try:
# Write the packed str
f = client.stream.write(payload)
self.io_loop.add_future(f, lambda f: True)
except StreamClosedError:
to_remove.append(client)
for client in to_remove:
log.debug('Subscriber at %s has disconnected from publisher', client.address)
client.close()
self._remove_client_present(client)
self.clients.discard(client)
log.trace('TCP PubServer finished publishing payload')
class TCPPubServerChannel(salt.transport.server.PubServerChannel):
# TODO: opts!
# Based on default used in tornado.netutil.bind_sockets()
backlog = 128
def __init__(self, opts):
self.opts = opts
self.serial = salt.payload.Serial(self.opts) # TODO: in init?
self.ckminions = salt.utils.minions.CkMinions(opts)
self.io_loop = None
def __setstate__(self, state):
salt.master.SMaster.secrets = state['secrets']
self.__init__(state['opts'])
def __getstate__(self):
return {'opts': self.opts,
'secrets': salt.master.SMaster.secrets}
def _publish_daemon(self, **kwargs):
'''
Bind to the interface specified in the configuration file
'''
salt.utils.process.appendproctitle(self.__class__.__name__)
log_queue = kwargs.get('log_queue')
if log_queue is not None:
salt.log.setup.set_multiprocessing_logging_queue(log_queue)
log_queue_level = kwargs.get('log_queue_level')
if log_queue_level is not None:
salt.log.setup.set_multiprocessing_logging_level(log_queue_level)
salt.log.setup.setup_multiprocessing_logging(log_queue)
# Check if io_loop was set outside
if self.io_loop is None:
self.io_loop = tornado.ioloop.IOLoop.current()
# Spin up the publisher
pub_server = PubServer(self.opts, io_loop=self.io_loop)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
_set_tcp_keepalive(sock, self.opts)
sock.setblocking(0)
sock.bind((self.opts['interface'], int(self.opts['publish_port'])))
sock.listen(self.backlog)
# pub_server will take ownership of the socket
pub_server.add_socket(sock)
# Set up Salt IPC server
if self.opts.get('ipc_mode', '') == 'tcp':
pull_uri = int(self.opts.get('tcp_master_publish_pull', 4514))
else:
pull_uri = os.path.join(self.opts['sock_dir'], 'publish_pull.ipc')
pull_sock = salt.transport.ipc.IPCMessageServer(
self.opts,
pull_uri,
io_loop=self.io_loop,
payload_handler=pub_server.publish_payload,
)
# Securely create socket
log.info('Starting the Salt Puller on %s', pull_uri)
with salt.utils.files.set_umask(0o177):
pull_sock.start()
# run forever
try:
self.io_loop.start()
except (KeyboardInterrupt, SystemExit):
salt.log.setup.shutdown_multiprocessing_logging()
def pre_fork(self, process_manager, kwargs=None):
'''
Do anything necessary pre-fork. Since this is on the master side this will
primarily be used to create IPC channels and create our daemon process to
do the actual publishing
'''
process_manager.add_process(self._publish_daemon, kwargs=kwargs)
def publish(self, load):
'''
Publish "load" to minions
'''
payload = {'enc': 'aes'}
crypticle = salt.crypt.Crypticle(self.opts, salt.master.SMaster.secrets['aes']['secret'].value)
payload['load'] = crypticle.dumps(load)
if self.opts['sign_pub_messages']:
master_pem_path = os.path.join(self.opts['pki_dir'], 'master.pem')
log.debug("Signing data packet")
payload['sig'] = salt.crypt.sign_message(master_pem_path, payload['load'])
# Use the Salt IPC server
if self.opts.get('ipc_mode', '') == 'tcp':
pull_uri = int(self.opts.get('tcp_master_publish_pull', 4514))
else:
pull_uri = os.path.join(self.opts['sock_dir'], 'publish_pull.ipc')
# TODO: switch to the actual asynchronous interface
#pub_sock = salt.transport.ipc.IPCMessageClient(self.opts, io_loop=self.io_loop)
pub_sock = salt.utils.asynchronous.SyncWrapper(
salt.transport.ipc.IPCMessageClient,
(pull_uri,)
)
pub_sock.connect()
int_payload = {'payload': self.serial.dumps(payload)}
# add some targeting stuff for lists only (for now)
if load['tgt_type'] == 'list':
if isinstance(load['tgt'], six.string_types):
# Fetch a list of minions that match
_res = self.ckminions.check_minions(load['tgt'],
tgt_type=load['tgt_type'])
match_ids = _res['minions']
log.debug("Publish Side Match: %s", match_ids)
# Send list of miions thru so zmq can target them
int_payload['topic_lst'] = match_ids
else:
int_payload['topic_lst'] = load['tgt']
# Send it over IPC!
pub_sock.send(int_payload)
|
saltstack/salt
|
salt/transport/tcp.py
|
AsyncTCPReqChannel._crypted_transfer
|
python
|
def _crypted_transfer(self, load, tries=3, timeout=60):
'''
In case of authentication errors, try to renegotiate authentication
and retry the method.
Indeed, we can fail too early in case of a master restart during a
minion state execution call
'''
@tornado.gen.coroutine
def _do_transfer():
data = yield self.message_client.send(self._package_load(self.auth.crypticle.dumps(load)),
timeout=timeout,
)
# we may not have always data
# as for example for saltcall ret submission, this is a blind
# communication, we do not subscribe to return events, we just
# upload the results to the master
if data:
data = self.auth.crypticle.loads(data)
if six.PY3:
data = salt.transport.frame.decode_embedded_strs(data)
raise tornado.gen.Return(data)
if not self.auth.authenticated:
yield self.auth.authenticate()
try:
ret = yield _do_transfer()
raise tornado.gen.Return(ret)
except salt.crypt.AuthenticationError:
yield self.auth.authenticate()
ret = yield _do_transfer()
raise tornado.gen.Return(ret)
|
In case of authentication errors, try to renegotiate authentication
and retry the method.
Indeed, we can fail too early in case of a master restart during a
minion state execution call
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/tcp.py#L361-L391
| null |
class AsyncTCPReqChannel(salt.transport.client.ReqChannel):
'''
Encapsulate sending routines to tcp.
Note: this class returns a singleton
'''
# This class is only a singleton per minion/master pair
# mapping of io_loop -> {key -> channel}
instance_map = weakref.WeakKeyDictionary()
def __new__(cls, opts, **kwargs):
'''
Only create one instance of channel per __key()
'''
# do we have any mapping for this io_loop
io_loop = kwargs.get('io_loop') or tornado.ioloop.IOLoop.current()
if io_loop not in cls.instance_map:
cls.instance_map[io_loop] = weakref.WeakValueDictionary()
loop_instance_map = cls.instance_map[io_loop]
key = cls.__key(opts, **kwargs)
obj = loop_instance_map.get(key)
if obj is None:
log.debug('Initializing new AsyncTCPReqChannel for %s', key)
# we need to make a local variable for this, as we are going to store
# it in a WeakValueDictionary-- which will remove the item if no one
# references it-- this forces a reference while we return to the caller
obj = object.__new__(cls)
obj.__singleton_init__(opts, **kwargs)
obj._instance_key = key
loop_instance_map[key] = obj
obj._refcount = 1
obj._refcount_lock = threading.RLock()
else:
with obj._refcount_lock:
obj._refcount += 1
log.debug('Re-using AsyncTCPReqChannel for %s', key)
return obj
@classmethod
def __key(cls, opts, **kwargs):
if 'master_uri' in kwargs:
opts['master_uri'] = kwargs['master_uri']
return (opts['pki_dir'], # where the keys are stored
opts['id'], # minion ID
opts['master_uri'],
kwargs.get('crypt', 'aes'), # TODO: use the same channel for crypt
)
# has to remain empty for singletons, since __init__ will *always* be called
def __init__(self, opts, **kwargs):
pass
# an init for the singleton instance to call
def __singleton_init__(self, opts, **kwargs):
self.opts = dict(opts)
self.serial = salt.payload.Serial(self.opts)
# crypt defaults to 'aes'
self.crypt = kwargs.get('crypt', 'aes')
self.io_loop = kwargs.get('io_loop') or tornado.ioloop.IOLoop.current()
if self.crypt != 'clear':
self.auth = salt.crypt.AsyncAuth(self.opts, io_loop=self.io_loop)
resolver = kwargs.get('resolver')
parse = urlparse.urlparse(self.opts['master_uri'])
master_host, master_port = parse.netloc.rsplit(':', 1)
self.master_addr = (master_host, int(master_port))
self._closing = False
self.message_client = SaltMessageClientPool(self.opts,
args=(self.opts, master_host, int(master_port),),
kwargs={'io_loop': self.io_loop, 'resolver': resolver,
'source_ip': self.opts.get('source_ip'),
'source_port': self.opts.get('source_ret_port')})
def close(self):
if self._closing:
return
if self._refcount > 1:
# Decrease refcount
with self._refcount_lock:
self._refcount -= 1
log.debug(
'This is not the last %s instance. Not closing yet.',
self.__class__.__name__
)
return
log.debug('Closing %s instance', self.__class__.__name__)
self._closing = True
self.message_client.close()
# Remove the entry from the instance map so that a closed entry may not
# be reused.
# This forces this operation even if the reference count of the entry
# has not yet gone to zero.
if self.io_loop in self.__class__.instance_map:
loop_instance_map = self.__class__.instance_map[self.io_loop]
if self._instance_key in loop_instance_map:
del loop_instance_map[self._instance_key]
if not loop_instance_map:
del self.__class__.instance_map[self.io_loop]
def __del__(self):
with self._refcount_lock:
# Make sure we actually close no matter if something
# went wrong with our ref counting
self._refcount = 1
try:
self.close()
except socket.error as exc:
if exc.errno != errno.EBADF:
# If its not a bad file descriptor error, raise
raise
def _package_load(self, load):
return {
'enc': self.crypt,
'load': load,
}
@tornado.gen.coroutine
def crypted_transfer_decode_dictentry(self, load, dictkey=None, tries=3, timeout=60):
if not self.auth.authenticated:
yield self.auth.authenticate()
ret = yield self.message_client.send(self._package_load(self.auth.crypticle.dumps(load)), timeout=timeout)
key = self.auth.get_keys()
if HAS_M2:
aes = key.private_decrypt(ret['key'], RSA.pkcs1_oaep_padding)
else:
cipher = PKCS1_OAEP.new(key)
aes = cipher.decrypt(ret['key'])
pcrypt = salt.crypt.Crypticle(self.opts, aes)
data = pcrypt.loads(ret[dictkey])
if six.PY3:
data = salt.transport.frame.decode_embedded_strs(data)
raise tornado.gen.Return(data)
@tornado.gen.coroutine
@tornado.gen.coroutine
def _uncrypted_transfer(self, load, tries=3, timeout=60):
ret = yield self.message_client.send(self._package_load(load), timeout=timeout)
raise tornado.gen.Return(ret)
@tornado.gen.coroutine
def send(self, load, tries=3, timeout=60, raw=False):
'''
Send a request, return a future which will complete when we send the message
'''
try:
if self.crypt == 'clear':
ret = yield self._uncrypted_transfer(load, tries=tries, timeout=timeout)
else:
ret = yield self._crypted_transfer(load, tries=tries, timeout=timeout)
except StreamClosedError:
# Convert to 'SaltClientError' so that clients can handle this
# exception more appropriately.
raise SaltClientError('Connection to master lost')
raise tornado.gen.Return(ret)
|
saltstack/salt
|
salt/transport/tcp.py
|
AsyncTCPPubChannel.send_id
|
python
|
def send_id(self, tok, force_auth):
'''
Send the minion id to the master so that the master may better
track the connection state of the minion.
In case of authentication errors, try to renegotiate authentication
and retry the method.
'''
load = {'id': self.opts['id'], 'tok': tok}
@tornado.gen.coroutine
def _do_transfer():
msg = self._package_load(self.auth.crypticle.dumps(load))
package = salt.transport.frame.frame_msg(msg, header=None)
yield self.message_client.write_to_stream(package)
raise tornado.gen.Return(True)
if force_auth or not self.auth.authenticated:
count = 0
while count <= self.opts['tcp_authentication_retries'] or self.opts['tcp_authentication_retries'] < 0:
try:
yield self.auth.authenticate()
break
except SaltClientError as exc:
log.debug(exc)
count += 1
try:
ret = yield _do_transfer()
raise tornado.gen.Return(ret)
except salt.crypt.AuthenticationError:
yield self.auth.authenticate()
ret = yield _do_transfer()
raise tornado.gen.Return(ret)
|
Send the minion id to the master so that the master may better
track the connection state of the minion.
In case of authentication errors, try to renegotiate authentication
and retry the method.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/tcp.py#L451-L482
| null |
class AsyncTCPPubChannel(salt.transport.mixins.auth.AESPubClientMixin, salt.transport.client.AsyncPubChannel):
def __init__(self,
opts,
**kwargs):
self.opts = opts
self.serial = salt.payload.Serial(self.opts)
self.crypt = kwargs.get('crypt', 'aes')
self.io_loop = kwargs.get('io_loop') or tornado.ioloop.IOLoop.current()
self.connected = False
self._closing = False
self._reconnected = False
self.event = salt.utils.event.get_event(
'minion',
opts=self.opts,
listen=False
)
def close(self):
if self._closing:
return
self._closing = True
if hasattr(self, 'message_client'):
self.message_client.close()
def __del__(self):
self.close()
def _package_load(self, load):
return {
'enc': self.crypt,
'load': load,
}
@tornado.gen.coroutine
@tornado.gen.coroutine
def connect_callback(self, result):
if self._closing:
return
# Force re-auth on reconnect since the master
# may have been restarted
yield self.send_id(self.tok, self._reconnected)
self.connected = True
self.event.fire_event(
{'master': self.opts['master']},
'__master_connected'
)
if self._reconnected:
# On reconnects, fire a master event to notify that the minion is
# available.
if self.opts.get('__role') == 'syndic':
data = 'Syndic {0} started at {1}'.format(
self.opts['id'],
time.asctime()
)
tag = salt.utils.event.tagify(
[self.opts['id'], 'start'],
'syndic'
)
else:
data = 'Minion {0} started at {1}'.format(
self.opts['id'],
time.asctime()
)
tag = salt.utils.event.tagify(
[self.opts['id'], 'start'],
'minion'
)
load = {'id': self.opts['id'],
'cmd': '_minion_event',
'pretag': None,
'tok': self.tok,
'data': data,
'tag': tag}
req_channel = salt.utils.asynchronous.SyncWrapper(
AsyncTCPReqChannel, (self.opts,)
)
try:
req_channel.send(load, timeout=60)
except salt.exceptions.SaltReqTimeoutError:
log.info('fire_master failed: master could not be contacted. Request timed out.')
except Exception:
log.info('fire_master failed: %s', traceback.format_exc())
finally:
# SyncWrapper will call either close() or destroy(), whichever is available
del req_channel
else:
self._reconnected = True
def disconnect_callback(self):
if self._closing:
return
self.connected = False
self.event.fire_event(
{'master': self.opts['master']},
'__master_disconnected'
)
@tornado.gen.coroutine
def connect(self):
try:
self.auth = salt.crypt.AsyncAuth(self.opts, io_loop=self.io_loop)
self.tok = self.auth.gen_token(b'salt')
if not self.auth.authenticated:
yield self.auth.authenticate()
if self.auth.authenticated:
# if this is changed from the default, we assume it was intentional
if int(self.opts.get('publish_port', 4505)) != 4505:
self.publish_port = self.opts.get('publish_port')
# else take the relayed publish_port master reports
else:
self.publish_port = self.auth.creds['publish_port']
self.message_client = SaltMessageClientPool(
self.opts,
args=(self.opts, self.opts['master_ip'], int(self.publish_port),),
kwargs={'io_loop': self.io_loop,
'connect_callback': self.connect_callback,
'disconnect_callback': self.disconnect_callback,
'source_ip': self.opts.get('source_ip'),
'source_port': self.opts.get('source_publish_port')})
yield self.message_client.connect() # wait for the client to be connected
self.connected = True
# TODO: better exception handling...
except KeyboardInterrupt:
raise
except Exception as exc:
if '-|RETRY|-' not in six.text_type(exc):
raise SaltClientError('Unable to sign_in to master: {0}'.format(exc)) # TODO: better error message
def on_recv(self, callback):
'''
Register an on_recv callback
'''
if callback is None:
return self.message_client.on_recv(callback)
@tornado.gen.coroutine
def wrap_callback(body):
if not isinstance(body, dict):
# TODO: For some reason we need to decode here for things
# to work. Fix this.
body = salt.utils.msgpack.loads(body)
if six.PY3:
body = salt.transport.frame.decode_embedded_strs(body)
ret = yield self._decode_payload(body)
callback(ret)
return self.message_client.on_recv(wrap_callback)
|
saltstack/salt
|
salt/transport/tcp.py
|
AsyncTCPPubChannel.on_recv
|
python
|
def on_recv(self, callback):
'''
Register an on_recv callback
'''
if callback is None:
return self.message_client.on_recv(callback)
@tornado.gen.coroutine
def wrap_callback(body):
if not isinstance(body, dict):
# TODO: For some reason we need to decode here for things
# to work. Fix this.
body = salt.utils.msgpack.loads(body)
if six.PY3:
body = salt.transport.frame.decode_embedded_strs(body)
ret = yield self._decode_payload(body)
callback(ret)
return self.message_client.on_recv(wrap_callback)
|
Register an on_recv callback
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/tcp.py#L579-L596
| null |
class AsyncTCPPubChannel(salt.transport.mixins.auth.AESPubClientMixin, salt.transport.client.AsyncPubChannel):
def __init__(self,
opts,
**kwargs):
self.opts = opts
self.serial = salt.payload.Serial(self.opts)
self.crypt = kwargs.get('crypt', 'aes')
self.io_loop = kwargs.get('io_loop') or tornado.ioloop.IOLoop.current()
self.connected = False
self._closing = False
self._reconnected = False
self.event = salt.utils.event.get_event(
'minion',
opts=self.opts,
listen=False
)
def close(self):
if self._closing:
return
self._closing = True
if hasattr(self, 'message_client'):
self.message_client.close()
def __del__(self):
self.close()
def _package_load(self, load):
return {
'enc': self.crypt,
'load': load,
}
@tornado.gen.coroutine
def send_id(self, tok, force_auth):
'''
Send the minion id to the master so that the master may better
track the connection state of the minion.
In case of authentication errors, try to renegotiate authentication
and retry the method.
'''
load = {'id': self.opts['id'], 'tok': tok}
@tornado.gen.coroutine
def _do_transfer():
msg = self._package_load(self.auth.crypticle.dumps(load))
package = salt.transport.frame.frame_msg(msg, header=None)
yield self.message_client.write_to_stream(package)
raise tornado.gen.Return(True)
if force_auth or not self.auth.authenticated:
count = 0
while count <= self.opts['tcp_authentication_retries'] or self.opts['tcp_authentication_retries'] < 0:
try:
yield self.auth.authenticate()
break
except SaltClientError as exc:
log.debug(exc)
count += 1
try:
ret = yield _do_transfer()
raise tornado.gen.Return(ret)
except salt.crypt.AuthenticationError:
yield self.auth.authenticate()
ret = yield _do_transfer()
raise tornado.gen.Return(ret)
@tornado.gen.coroutine
def connect_callback(self, result):
if self._closing:
return
# Force re-auth on reconnect since the master
# may have been restarted
yield self.send_id(self.tok, self._reconnected)
self.connected = True
self.event.fire_event(
{'master': self.opts['master']},
'__master_connected'
)
if self._reconnected:
# On reconnects, fire a master event to notify that the minion is
# available.
if self.opts.get('__role') == 'syndic':
data = 'Syndic {0} started at {1}'.format(
self.opts['id'],
time.asctime()
)
tag = salt.utils.event.tagify(
[self.opts['id'], 'start'],
'syndic'
)
else:
data = 'Minion {0} started at {1}'.format(
self.opts['id'],
time.asctime()
)
tag = salt.utils.event.tagify(
[self.opts['id'], 'start'],
'minion'
)
load = {'id': self.opts['id'],
'cmd': '_minion_event',
'pretag': None,
'tok': self.tok,
'data': data,
'tag': tag}
req_channel = salt.utils.asynchronous.SyncWrapper(
AsyncTCPReqChannel, (self.opts,)
)
try:
req_channel.send(load, timeout=60)
except salt.exceptions.SaltReqTimeoutError:
log.info('fire_master failed: master could not be contacted. Request timed out.')
except Exception:
log.info('fire_master failed: %s', traceback.format_exc())
finally:
# SyncWrapper will call either close() or destroy(), whichever is available
del req_channel
else:
self._reconnected = True
def disconnect_callback(self):
if self._closing:
return
self.connected = False
self.event.fire_event(
{'master': self.opts['master']},
'__master_disconnected'
)
@tornado.gen.coroutine
def connect(self):
try:
self.auth = salt.crypt.AsyncAuth(self.opts, io_loop=self.io_loop)
self.tok = self.auth.gen_token(b'salt')
if not self.auth.authenticated:
yield self.auth.authenticate()
if self.auth.authenticated:
# if this is changed from the default, we assume it was intentional
if int(self.opts.get('publish_port', 4505)) != 4505:
self.publish_port = self.opts.get('publish_port')
# else take the relayed publish_port master reports
else:
self.publish_port = self.auth.creds['publish_port']
self.message_client = SaltMessageClientPool(
self.opts,
args=(self.opts, self.opts['master_ip'], int(self.publish_port),),
kwargs={'io_loop': self.io_loop,
'connect_callback': self.connect_callback,
'disconnect_callback': self.disconnect_callback,
'source_ip': self.opts.get('source_ip'),
'source_port': self.opts.get('source_publish_port')})
yield self.message_client.connect() # wait for the client to be connected
self.connected = True
# TODO: better exception handling...
except KeyboardInterrupt:
raise
except Exception as exc:
if '-|RETRY|-' not in six.text_type(exc):
raise SaltClientError('Unable to sign_in to master: {0}'.format(exc)) # TODO: better error message
|
saltstack/salt
|
salt/transport/tcp.py
|
TCPReqServerChannel.pre_fork
|
python
|
def pre_fork(self, process_manager):
'''
Pre-fork we need to create the zmq router device
'''
salt.transport.mixins.auth.AESReqServerMixin.pre_fork(self, process_manager)
if USE_LOAD_BALANCER:
self.socket_queue = multiprocessing.Queue()
process_manager.add_process(
LoadBalancerServer, args=(self.opts, self.socket_queue)
)
elif not salt.utils.platform.is_windows():
self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
_set_tcp_keepalive(self._socket, self.opts)
self._socket.setblocking(0)
self._socket.bind((self.opts['interface'], int(self.opts['ret_port'])))
|
Pre-fork we need to create the zmq router device
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/tcp.py#L633-L648
|
[
"def _set_tcp_keepalive(sock, opts):\n '''\n Ensure that TCP keepalives are set for the socket.\n '''\n if hasattr(socket, 'SO_KEEPALIVE'):\n if opts.get('tcp_keepalive', False):\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)\n if hasattr(socket, 'SOL_TCP'):\n if hasattr(socket, 'TCP_KEEPIDLE'):\n tcp_keepalive_idle = opts.get('tcp_keepalive_idle', -1)\n if tcp_keepalive_idle > 0:\n sock.setsockopt(\n socket.SOL_TCP, socket.TCP_KEEPIDLE,\n int(tcp_keepalive_idle))\n if hasattr(socket, 'TCP_KEEPCNT'):\n tcp_keepalive_cnt = opts.get('tcp_keepalive_cnt', -1)\n if tcp_keepalive_cnt > 0:\n sock.setsockopt(\n socket.SOL_TCP, socket.TCP_KEEPCNT,\n int(tcp_keepalive_cnt))\n if hasattr(socket, 'TCP_KEEPINTVL'):\n tcp_keepalive_intvl = opts.get('tcp_keepalive_intvl', -1)\n if tcp_keepalive_intvl > 0:\n sock.setsockopt(\n socket.SOL_TCP, socket.TCP_KEEPINTVL,\n int(tcp_keepalive_intvl))\n if hasattr(socket, 'SIO_KEEPALIVE_VALS'):\n # Windows doesn't support TCP_KEEPIDLE, TCP_KEEPCNT, nor\n # TCP_KEEPINTVL. Instead, it has its own proprietary\n # SIO_KEEPALIVE_VALS.\n tcp_keepalive_idle = opts.get('tcp_keepalive_idle', -1)\n tcp_keepalive_intvl = opts.get('tcp_keepalive_intvl', -1)\n # Windows doesn't support changing something equivalent to\n # TCP_KEEPCNT.\n if tcp_keepalive_idle > 0 or tcp_keepalive_intvl > 0:\n # Windows defaults may be found by using the link below.\n # Search for 'KeepAliveTime' and 'KeepAliveInterval'.\n # https://technet.microsoft.com/en-us/library/bb726981.aspx#EDAA\n # If one value is set and the other isn't, we still need\n # to send both values to SIO_KEEPALIVE_VALS and they both\n # need to be valid. So in that case, use the Windows\n # default.\n if tcp_keepalive_idle <= 0:\n tcp_keepalive_idle = 7200\n if tcp_keepalive_intvl <= 0:\n tcp_keepalive_intvl = 1\n # The values expected are in milliseconds, so multiply by\n # 1000.\n sock.ioctl(socket.SIO_KEEPALIVE_VALS, (\n 1, int(tcp_keepalive_idle * 1000),\n int(tcp_keepalive_intvl * 1000)))\n else:\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 0)\n",
"def pre_fork(self, _):\n '''\n Pre-fork we need to create the zmq router device\n '''\n if 'aes' not in salt.master.SMaster.secrets:\n # TODO: This is still needed only for the unit tests\n # 'tcp_test.py' and 'zeromq_test.py'. Fix that. In normal\n # cases, 'aes' is already set in the secrets.\n salt.master.SMaster.secrets['aes'] = {\n 'secret': multiprocessing.Array(\n ctypes.c_char,\n salt.utils.stringutils.to_bytes(salt.crypt.Crypticle.generate_key_string())\n ),\n 'reload': salt.crypt.Crypticle.generate_key_string\n }\n"
] |
class TCPReqServerChannel(salt.transport.mixins.auth.AESReqServerMixin, salt.transport.server.ReqServerChannel):
# TODO: opts!
backlog = 5
def __init__(self, opts):
salt.transport.server.ReqServerChannel.__init__(self, opts)
self._socket = None
@property
def socket(self):
return self._socket
def close(self):
if self._socket is not None:
try:
self._socket.shutdown(socket.SHUT_RDWR)
except socket.error as exc:
if exc.errno == errno.ENOTCONN:
# We may try to shutdown a socket which is already disconnected.
# Ignore this condition and continue.
pass
else:
raise exc
self._socket.close()
self._socket = None
if hasattr(self.req_server, 'stop'):
try:
self.req_server.stop()
except Exception as exc:
log.exception('TCPReqServerChannel close generated an exception: %s', str(exc))
def __del__(self):
self.close()
def post_fork(self, payload_handler, io_loop):
'''
After forking we need to create all of the local sockets to listen to the
router
payload_handler: function to call with your payloads
'''
self.payload_handler = payload_handler
self.io_loop = io_loop
self.serial = salt.payload.Serial(self.opts)
with salt.utils.asynchronous.current_ioloop(self.io_loop):
if USE_LOAD_BALANCER:
self.req_server = LoadBalancerWorker(self.socket_queue,
self.handle_message,
ssl_options=self.opts.get('ssl'))
else:
if salt.utils.platform.is_windows():
self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
_set_tcp_keepalive(self._socket, self.opts)
self._socket.setblocking(0)
self._socket.bind((self.opts['interface'], int(self.opts['ret_port'])))
self.req_server = SaltMessageServer(self.handle_message,
ssl_options=self.opts.get('ssl'))
self.req_server.add_socket(self._socket)
self._socket.listen(self.backlog)
salt.transport.mixins.auth.AESReqServerMixin.post_fork(self, payload_handler, io_loop)
@tornado.gen.coroutine
def handle_message(self, stream, header, payload):
'''
Handle incoming messages from underylying tcp streams
'''
try:
try:
payload = self._decode_payload(payload)
except Exception:
stream.write(salt.transport.frame.frame_msg('bad load', header=header))
raise tornado.gen.Return()
# TODO helper functions to normalize payload?
if not isinstance(payload, dict) or not isinstance(payload.get('load'), dict):
yield stream.write(salt.transport.frame.frame_msg(
'payload and load must be a dict', header=header))
raise tornado.gen.Return()
try:
id_ = payload['load'].get('id', '')
if str('\0') in id_:
log.error('Payload contains an id with a null byte: %s', payload)
stream.send(self.serial.dumps('bad load: id contains a null byte'))
raise tornado.gen.Return()
except TypeError:
log.error('Payload contains non-string id: %s', payload)
stream.send(self.serial.dumps('bad load: id {0} is not a string'.format(id_)))
raise tornado.gen.Return()
# intercept the "_auth" commands, since the main daemon shouldn't know
# anything about our key auth
if payload['enc'] == 'clear' and payload.get('load', {}).get('cmd') == '_auth':
yield stream.write(salt.transport.frame.frame_msg(
self._auth(payload['load']), header=header))
raise tornado.gen.Return()
# TODO: test
try:
ret, req_opts = yield self.payload_handler(payload)
except Exception as e:
# always attempt to return an error to the minion
stream.write('Some exception handling minion payload')
log.error('Some exception handling a payload from minion', exc_info=True)
stream.close()
raise tornado.gen.Return()
req_fun = req_opts.get('fun', 'send')
if req_fun == 'send_clear':
stream.write(salt.transport.frame.frame_msg(ret, header=header))
elif req_fun == 'send':
stream.write(salt.transport.frame.frame_msg(self.crypticle.dumps(ret), header=header))
elif req_fun == 'send_private':
stream.write(salt.transport.frame.frame_msg(self._encrypt_private(ret,
req_opts['key'],
req_opts['tgt'],
), header=header))
else:
log.error('Unknown req_fun %s', req_fun)
# always attempt to return an error to the minion
stream.write('Server-side exception handling payload')
stream.close()
except tornado.gen.Return:
raise
except StreamClosedError:
# Stream was closed. This could happen if the remote side
# closed the connection on its end (eg in a timeout or shutdown
# situation).
log.error('Connection was unexpectedly closed', exc_info=True)
except Exception as exc: # pylint: disable=broad-except
# Absorb any other exceptions
log.error('Unexpected exception occurred: %s', exc, exc_info=True)
raise tornado.gen.Return()
|
saltstack/salt
|
salt/transport/tcp.py
|
TCPReqServerChannel.post_fork
|
python
|
def post_fork(self, payload_handler, io_loop):
'''
After forking we need to create all of the local sockets to listen to the
router
payload_handler: function to call with your payloads
'''
self.payload_handler = payload_handler
self.io_loop = io_loop
self.serial = salt.payload.Serial(self.opts)
with salt.utils.asynchronous.current_ioloop(self.io_loop):
if USE_LOAD_BALANCER:
self.req_server = LoadBalancerWorker(self.socket_queue,
self.handle_message,
ssl_options=self.opts.get('ssl'))
else:
if salt.utils.platform.is_windows():
self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
_set_tcp_keepalive(self._socket, self.opts)
self._socket.setblocking(0)
self._socket.bind((self.opts['interface'], int(self.opts['ret_port'])))
self.req_server = SaltMessageServer(self.handle_message,
ssl_options=self.opts.get('ssl'))
self.req_server.add_socket(self._socket)
self._socket.listen(self.backlog)
salt.transport.mixins.auth.AESReqServerMixin.post_fork(self, payload_handler, io_loop)
|
After forking we need to create all of the local sockets to listen to the
router
payload_handler: function to call with your payloads
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/tcp.py#L650-L676
|
[
"def _set_tcp_keepalive(sock, opts):\n '''\n Ensure that TCP keepalives are set for the socket.\n '''\n if hasattr(socket, 'SO_KEEPALIVE'):\n if opts.get('tcp_keepalive', False):\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)\n if hasattr(socket, 'SOL_TCP'):\n if hasattr(socket, 'TCP_KEEPIDLE'):\n tcp_keepalive_idle = opts.get('tcp_keepalive_idle', -1)\n if tcp_keepalive_idle > 0:\n sock.setsockopt(\n socket.SOL_TCP, socket.TCP_KEEPIDLE,\n int(tcp_keepalive_idle))\n if hasattr(socket, 'TCP_KEEPCNT'):\n tcp_keepalive_cnt = opts.get('tcp_keepalive_cnt', -1)\n if tcp_keepalive_cnt > 0:\n sock.setsockopt(\n socket.SOL_TCP, socket.TCP_KEEPCNT,\n int(tcp_keepalive_cnt))\n if hasattr(socket, 'TCP_KEEPINTVL'):\n tcp_keepalive_intvl = opts.get('tcp_keepalive_intvl', -1)\n if tcp_keepalive_intvl > 0:\n sock.setsockopt(\n socket.SOL_TCP, socket.TCP_KEEPINTVL,\n int(tcp_keepalive_intvl))\n if hasattr(socket, 'SIO_KEEPALIVE_VALS'):\n # Windows doesn't support TCP_KEEPIDLE, TCP_KEEPCNT, nor\n # TCP_KEEPINTVL. Instead, it has its own proprietary\n # SIO_KEEPALIVE_VALS.\n tcp_keepalive_idle = opts.get('tcp_keepalive_idle', -1)\n tcp_keepalive_intvl = opts.get('tcp_keepalive_intvl', -1)\n # Windows doesn't support changing something equivalent to\n # TCP_KEEPCNT.\n if tcp_keepalive_idle > 0 or tcp_keepalive_intvl > 0:\n # Windows defaults may be found by using the link below.\n # Search for 'KeepAliveTime' and 'KeepAliveInterval'.\n # https://technet.microsoft.com/en-us/library/bb726981.aspx#EDAA\n # If one value is set and the other isn't, we still need\n # to send both values to SIO_KEEPALIVE_VALS and they both\n # need to be valid. So in that case, use the Windows\n # default.\n if tcp_keepalive_idle <= 0:\n tcp_keepalive_idle = 7200\n if tcp_keepalive_intvl <= 0:\n tcp_keepalive_intvl = 1\n # The values expected are in milliseconds, so multiply by\n # 1000.\n sock.ioctl(socket.SIO_KEEPALIVE_VALS, (\n 1, int(tcp_keepalive_idle * 1000),\n int(tcp_keepalive_intvl * 1000)))\n else:\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 0)\n",
"def post_fork(self, _, __):\n self.serial = salt.payload.Serial(self.opts)\n self.crypticle = salt.crypt.Crypticle(self.opts, salt.master.SMaster.secrets['aes']['secret'].value)\n\n # other things needed for _auth\n # Create the event manager\n self.event = salt.utils.event.get_master_event(self.opts, self.opts['sock_dir'], listen=False)\n self.auto_key = salt.daemons.masterapi.AutoKey(self.opts)\n\n # only create a con_cache-client if the con_cache is active\n if self.opts['con_cache']:\n self.cache_cli = CacheCli(self.opts)\n else:\n self.cache_cli = False\n # Make an minion checker object\n self.ckminions = salt.utils.minions.CkMinions(self.opts)\n\n self.master_key = salt.crypt.MasterKeys(self.opts)\n"
] |
class TCPReqServerChannel(salt.transport.mixins.auth.AESReqServerMixin, salt.transport.server.ReqServerChannel):
# TODO: opts!
backlog = 5
def __init__(self, opts):
salt.transport.server.ReqServerChannel.__init__(self, opts)
self._socket = None
@property
def socket(self):
return self._socket
def close(self):
if self._socket is not None:
try:
self._socket.shutdown(socket.SHUT_RDWR)
except socket.error as exc:
if exc.errno == errno.ENOTCONN:
# We may try to shutdown a socket which is already disconnected.
# Ignore this condition and continue.
pass
else:
raise exc
self._socket.close()
self._socket = None
if hasattr(self.req_server, 'stop'):
try:
self.req_server.stop()
except Exception as exc:
log.exception('TCPReqServerChannel close generated an exception: %s', str(exc))
def __del__(self):
self.close()
def pre_fork(self, process_manager):
'''
Pre-fork we need to create the zmq router device
'''
salt.transport.mixins.auth.AESReqServerMixin.pre_fork(self, process_manager)
if USE_LOAD_BALANCER:
self.socket_queue = multiprocessing.Queue()
process_manager.add_process(
LoadBalancerServer, args=(self.opts, self.socket_queue)
)
elif not salt.utils.platform.is_windows():
self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
_set_tcp_keepalive(self._socket, self.opts)
self._socket.setblocking(0)
self._socket.bind((self.opts['interface'], int(self.opts['ret_port'])))
@tornado.gen.coroutine
def handle_message(self, stream, header, payload):
'''
Handle incoming messages from underylying tcp streams
'''
try:
try:
payload = self._decode_payload(payload)
except Exception:
stream.write(salt.transport.frame.frame_msg('bad load', header=header))
raise tornado.gen.Return()
# TODO helper functions to normalize payload?
if not isinstance(payload, dict) or not isinstance(payload.get('load'), dict):
yield stream.write(salt.transport.frame.frame_msg(
'payload and load must be a dict', header=header))
raise tornado.gen.Return()
try:
id_ = payload['load'].get('id', '')
if str('\0') in id_:
log.error('Payload contains an id with a null byte: %s', payload)
stream.send(self.serial.dumps('bad load: id contains a null byte'))
raise tornado.gen.Return()
except TypeError:
log.error('Payload contains non-string id: %s', payload)
stream.send(self.serial.dumps('bad load: id {0} is not a string'.format(id_)))
raise tornado.gen.Return()
# intercept the "_auth" commands, since the main daemon shouldn't know
# anything about our key auth
if payload['enc'] == 'clear' and payload.get('load', {}).get('cmd') == '_auth':
yield stream.write(salt.transport.frame.frame_msg(
self._auth(payload['load']), header=header))
raise tornado.gen.Return()
# TODO: test
try:
ret, req_opts = yield self.payload_handler(payload)
except Exception as e:
# always attempt to return an error to the minion
stream.write('Some exception handling minion payload')
log.error('Some exception handling a payload from minion', exc_info=True)
stream.close()
raise tornado.gen.Return()
req_fun = req_opts.get('fun', 'send')
if req_fun == 'send_clear':
stream.write(salt.transport.frame.frame_msg(ret, header=header))
elif req_fun == 'send':
stream.write(salt.transport.frame.frame_msg(self.crypticle.dumps(ret), header=header))
elif req_fun == 'send_private':
stream.write(salt.transport.frame.frame_msg(self._encrypt_private(ret,
req_opts['key'],
req_opts['tgt'],
), header=header))
else:
log.error('Unknown req_fun %s', req_fun)
# always attempt to return an error to the minion
stream.write('Server-side exception handling payload')
stream.close()
except tornado.gen.Return:
raise
except StreamClosedError:
# Stream was closed. This could happen if the remote side
# closed the connection on its end (eg in a timeout or shutdown
# situation).
log.error('Connection was unexpectedly closed', exc_info=True)
except Exception as exc: # pylint: disable=broad-except
# Absorb any other exceptions
log.error('Unexpected exception occurred: %s', exc, exc_info=True)
raise tornado.gen.Return()
|
saltstack/salt
|
salt/transport/tcp.py
|
TCPReqServerChannel.handle_message
|
python
|
def handle_message(self, stream, header, payload):
'''
Handle incoming messages from underylying tcp streams
'''
try:
try:
payload = self._decode_payload(payload)
except Exception:
stream.write(salt.transport.frame.frame_msg('bad load', header=header))
raise tornado.gen.Return()
# TODO helper functions to normalize payload?
if not isinstance(payload, dict) or not isinstance(payload.get('load'), dict):
yield stream.write(salt.transport.frame.frame_msg(
'payload and load must be a dict', header=header))
raise tornado.gen.Return()
try:
id_ = payload['load'].get('id', '')
if str('\0') in id_:
log.error('Payload contains an id with a null byte: %s', payload)
stream.send(self.serial.dumps('bad load: id contains a null byte'))
raise tornado.gen.Return()
except TypeError:
log.error('Payload contains non-string id: %s', payload)
stream.send(self.serial.dumps('bad load: id {0} is not a string'.format(id_)))
raise tornado.gen.Return()
# intercept the "_auth" commands, since the main daemon shouldn't know
# anything about our key auth
if payload['enc'] == 'clear' and payload.get('load', {}).get('cmd') == '_auth':
yield stream.write(salt.transport.frame.frame_msg(
self._auth(payload['load']), header=header))
raise tornado.gen.Return()
# TODO: test
try:
ret, req_opts = yield self.payload_handler(payload)
except Exception as e:
# always attempt to return an error to the minion
stream.write('Some exception handling minion payload')
log.error('Some exception handling a payload from minion', exc_info=True)
stream.close()
raise tornado.gen.Return()
req_fun = req_opts.get('fun', 'send')
if req_fun == 'send_clear':
stream.write(salt.transport.frame.frame_msg(ret, header=header))
elif req_fun == 'send':
stream.write(salt.transport.frame.frame_msg(self.crypticle.dumps(ret), header=header))
elif req_fun == 'send_private':
stream.write(salt.transport.frame.frame_msg(self._encrypt_private(ret,
req_opts['key'],
req_opts['tgt'],
), header=header))
else:
log.error('Unknown req_fun %s', req_fun)
# always attempt to return an error to the minion
stream.write('Server-side exception handling payload')
stream.close()
except tornado.gen.Return:
raise
except StreamClosedError:
# Stream was closed. This could happen if the remote side
# closed the connection on its end (eg in a timeout or shutdown
# situation).
log.error('Connection was unexpectedly closed', exc_info=True)
except Exception as exc: # pylint: disable=broad-except
# Absorb any other exceptions
log.error('Unexpected exception occurred: %s', exc, exc_info=True)
raise tornado.gen.Return()
|
Handle incoming messages from underylying tcp streams
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/tcp.py#L679-L750
|
[
"def frame_msg(body, header=None, raw_body=False): # pylint: disable=unused-argument\n '''\n Frame the given message with our wire protocol\n '''\n framed_msg = {}\n if header is None:\n header = {}\n\n framed_msg['head'] = header\n framed_msg['body'] = body\n return salt.utils.msgpack.dumps(framed_msg)\n",
"def _decode_payload(self, payload):\n # we need to decrypt it\n if payload['enc'] == 'aes':\n try:\n payload['load'] = self.crypticle.loads(payload['load'])\n except salt.crypt.AuthenticationError:\n if not self._update_aes():\n raise\n payload['load'] = self.crypticle.loads(payload['load'])\n return payload\n"
] |
class TCPReqServerChannel(salt.transport.mixins.auth.AESReqServerMixin, salt.transport.server.ReqServerChannel):
# TODO: opts!
backlog = 5
def __init__(self, opts):
salt.transport.server.ReqServerChannel.__init__(self, opts)
self._socket = None
@property
def socket(self):
return self._socket
def close(self):
if self._socket is not None:
try:
self._socket.shutdown(socket.SHUT_RDWR)
except socket.error as exc:
if exc.errno == errno.ENOTCONN:
# We may try to shutdown a socket which is already disconnected.
# Ignore this condition and continue.
pass
else:
raise exc
self._socket.close()
self._socket = None
if hasattr(self.req_server, 'stop'):
try:
self.req_server.stop()
except Exception as exc:
log.exception('TCPReqServerChannel close generated an exception: %s', str(exc))
def __del__(self):
self.close()
def pre_fork(self, process_manager):
'''
Pre-fork we need to create the zmq router device
'''
salt.transport.mixins.auth.AESReqServerMixin.pre_fork(self, process_manager)
if USE_LOAD_BALANCER:
self.socket_queue = multiprocessing.Queue()
process_manager.add_process(
LoadBalancerServer, args=(self.opts, self.socket_queue)
)
elif not salt.utils.platform.is_windows():
self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
_set_tcp_keepalive(self._socket, self.opts)
self._socket.setblocking(0)
self._socket.bind((self.opts['interface'], int(self.opts['ret_port'])))
def post_fork(self, payload_handler, io_loop):
'''
After forking we need to create all of the local sockets to listen to the
router
payload_handler: function to call with your payloads
'''
self.payload_handler = payload_handler
self.io_loop = io_loop
self.serial = salt.payload.Serial(self.opts)
with salt.utils.asynchronous.current_ioloop(self.io_loop):
if USE_LOAD_BALANCER:
self.req_server = LoadBalancerWorker(self.socket_queue,
self.handle_message,
ssl_options=self.opts.get('ssl'))
else:
if salt.utils.platform.is_windows():
self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
_set_tcp_keepalive(self._socket, self.opts)
self._socket.setblocking(0)
self._socket.bind((self.opts['interface'], int(self.opts['ret_port'])))
self.req_server = SaltMessageServer(self.handle_message,
ssl_options=self.opts.get('ssl'))
self.req_server.add_socket(self._socket)
self._socket.listen(self.backlog)
salt.transport.mixins.auth.AESReqServerMixin.post_fork(self, payload_handler, io_loop)
@tornado.gen.coroutine
|
saltstack/salt
|
salt/transport/tcp.py
|
SaltMessageServer.handle_stream
|
python
|
def handle_stream(self, stream, address):
'''
Handle incoming streams and add messages to the incoming queue
'''
log.trace('Req client %s connected', address)
self.clients.append((stream, address))
unpacker = msgpack.Unpacker()
try:
while True:
wire_bytes = yield stream.read_bytes(4096, partial=True)
unpacker.feed(wire_bytes)
for framed_msg in unpacker:
if six.PY3:
framed_msg = salt.transport.frame.decode_embedded_strs(
framed_msg
)
header = framed_msg['head']
self.io_loop.spawn_callback(self.message_handler, stream, header, framed_msg['body'])
except StreamClosedError:
log.trace('req client disconnected %s', address)
self.clients.remove((stream, address))
except Exception as e:
log.trace('other master-side exception: %s', e)
self.clients.remove((stream, address))
stream.close()
|
Handle incoming streams and add messages to the incoming queue
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/tcp.py#L766-L791
| null |
class SaltMessageServer(tornado.tcpserver.TCPServer, object):
'''
Raw TCP server which will receive all of the TCP streams and re-assemble
messages that are sent through to us
'''
def __init__(self, message_handler, *args, **kwargs):
super(SaltMessageServer, self).__init__(*args, **kwargs)
self.io_loop = tornado.ioloop.IOLoop.current()
self.clients = []
self.message_handler = message_handler
@tornado.gen.coroutine
def shutdown(self):
'''
Shutdown the whole server
'''
for item in self.clients:
client, address = item
client.close()
self.clients.remove(item)
|
saltstack/salt
|
salt/transport/tcp.py
|
SaltMessageServer.shutdown
|
python
|
def shutdown(self):
'''
Shutdown the whole server
'''
for item in self.clients:
client, address = item
client.close()
self.clients.remove(item)
|
Shutdown the whole server
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/tcp.py#L793-L800
| null |
class SaltMessageServer(tornado.tcpserver.TCPServer, object):
'''
Raw TCP server which will receive all of the TCP streams and re-assemble
messages that are sent through to us
'''
def __init__(self, message_handler, *args, **kwargs):
super(SaltMessageServer, self).__init__(*args, **kwargs)
self.io_loop = tornado.ioloop.IOLoop.current()
self.clients = []
self.message_handler = message_handler
@tornado.gen.coroutine
def handle_stream(self, stream, address):
'''
Handle incoming streams and add messages to the incoming queue
'''
log.trace('Req client %s connected', address)
self.clients.append((stream, address))
unpacker = msgpack.Unpacker()
try:
while True:
wire_bytes = yield stream.read_bytes(4096, partial=True)
unpacker.feed(wire_bytes)
for framed_msg in unpacker:
if six.PY3:
framed_msg = salt.transport.frame.decode_embedded_strs(
framed_msg
)
header = framed_msg['head']
self.io_loop.spawn_callback(self.message_handler, stream, header, framed_msg['body'])
except StreamClosedError:
log.trace('req client disconnected %s', address)
self.clients.remove((stream, address))
except Exception as e:
log.trace('other master-side exception: %s', e)
self.clients.remove((stream, address))
stream.close()
|
saltstack/salt
|
salt/transport/tcp.py
|
TCPClientKeepAlive._create_stream
|
python
|
def _create_stream(self, max_buffer_size, af, addr, **kwargs): # pylint: disable=unused-argument
'''
Override _create_stream() in TCPClient.
Tornado 4.5 added the kwargs 'source_ip' and 'source_port'.
Due to this, use **kwargs to swallow these and any future
kwargs to maintain compatibility.
'''
# Always connect in plaintext; we'll convert to ssl if necessary
# after one connection has completed.
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
_set_tcp_keepalive(sock, self.opts)
stream = tornado.iostream.IOStream(
sock,
max_buffer_size=max_buffer_size)
if tornado.version_info < (5,):
return stream.connect(addr)
return stream, stream.connect(addr)
|
Override _create_stream() in TCPClient.
Tornado 4.5 added the kwargs 'source_ip' and 'source_port'.
Due to this, use **kwargs to swallow these and any future
kwargs to maintain compatibility.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/tcp.py#L849-L866
| null |
class TCPClientKeepAlive(tornado.tcpclient.TCPClient):
'''
Override _create_stream() in TCPClient to enable keep alive support.
'''
def __init__(self, opts, resolver=None):
self.opts = opts
super(TCPClientKeepAlive, self).__init__(resolver=resolver)
|
saltstack/salt
|
salt/transport/tcp.py
|
SaltMessageClient._connect
|
python
|
def _connect(self):
'''
Try to connect for the rest of time!
'''
while True:
if self._closing:
break
try:
kwargs = {}
if self.source_ip or self.source_port:
if tornado.version_info >= (4, 5):
### source_ip and source_port are supported only in Tornado >= 4.5
# See http://www.tornadoweb.org/en/stable/releases/v4.5.0.html
# Otherwise will just ignore these args
kwargs = {'source_ip': self.source_ip,
'source_port': self.source_port}
else:
log.warning('If you need a certain source IP/port, consider upgrading Tornado >= 4.5')
with salt.utils.asynchronous.current_ioloop(self.io_loop):
self._stream = yield self._tcp_client.connect(self.host,
self.port,
ssl_options=self.opts.get('ssl'),
**kwargs)
self._connecting_future.set_result(True)
break
except Exception as e:
yield tornado.gen.sleep(1)
|
Try to connect for the rest of time!
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/tcp.py#L1007-L1033
| null |
class SaltMessageClient(object):
'''
Low-level message sending client
'''
def __init__(self, opts, host, port, io_loop=None, resolver=None,
connect_callback=None, disconnect_callback=None,
source_ip=None, source_port=None):
self.opts = opts
self.host = host
self.port = port
self.source_ip = source_ip
self.source_port = source_port
self.connect_callback = connect_callback
self.disconnect_callback = disconnect_callback
self.io_loop = io_loop or tornado.ioloop.IOLoop.current()
with salt.utils.asynchronous.current_ioloop(self.io_loop):
self._tcp_client = TCPClientKeepAlive(opts, resolver=resolver)
self._mid = 1
self._max_messages = int((1 << 31) - 2) # number of IDs before we wrap
# TODO: max queue size
self.send_queue = [] # queue of messages to be sent
self.send_future_map = {} # mapping of request_id -> Future
self.send_timeout_map = {} # request_id -> timeout_callback
self._read_until_future = None
self._on_recv = None
self._closing = False
self._connecting_future = self.connect()
self._stream_return_future = tornado.concurrent.Future()
self.io_loop.spawn_callback(self._stream_return)
# TODO: timeout inflight sessions
def close(self):
if self._closing:
return
self._closing = True
if hasattr(self, '_stream') and not self._stream.closed():
# If _stream_return() hasn't completed, it means the IO
# Loop is stopped (such as when using
# 'salt.utils.asynchronous.SyncWrapper'). Ensure that
# _stream_return() completes by restarting the IO Loop.
# This will prevent potential errors on shutdown.
try:
orig_loop = tornado.ioloop.IOLoop.current()
self.io_loop.make_current()
self._stream.close()
if self._read_until_future is not None:
# This will prevent this message from showing up:
# '[ERROR ] Future exception was never retrieved:
# StreamClosedError'
# This happens because the logic is always waiting to read
# the next message and the associated read future is marked
# 'StreamClosedError' when the stream is closed.
if self._read_until_future.done():
self._read_until_future.exception()
elif self.io_loop != tornado.ioloop.IOLoop.current(instance=False):
self.io_loop.add_future(
self._stream_return_future,
lambda future: self.io_loop.stop()
)
self.io_loop.start()
finally:
orig_loop.make_current()
self._tcp_client.close()
# Clear callback references to allow the object that they belong to
# to be deleted.
self.connect_callback = None
self.disconnect_callback = None
def __del__(self):
self.close()
def connect(self):
'''
Ask for this client to reconnect to the origin
'''
if hasattr(self, '_connecting_future') and not self._connecting_future.done():
future = self._connecting_future
else:
future = tornado.concurrent.Future()
self._connecting_future = future
self.io_loop.add_callback(self._connect)
# Add the callback only when a new future is created
if self.connect_callback is not None:
def handle_future(future):
response = future.result()
self.io_loop.add_callback(self.connect_callback, response)
future.add_done_callback(handle_future)
return future
# TODO: tcp backoff opts
@tornado.gen.coroutine
# TODO: backoff
#self._connecting_future.set_exception(e)
@tornado.gen.coroutine
def _stream_return(self):
try:
while not self._closing and (
not self._connecting_future.done() or
self._connecting_future.result() is not True):
yield self._connecting_future
unpacker = msgpack.Unpacker()
while not self._closing:
try:
self._read_until_future = self._stream.read_bytes(4096, partial=True)
wire_bytes = yield self._read_until_future
unpacker.feed(wire_bytes)
for framed_msg in unpacker:
if six.PY3:
framed_msg = salt.transport.frame.decode_embedded_strs(
framed_msg
)
header = framed_msg['head']
body = framed_msg['body']
message_id = header.get('mid')
if message_id in self.send_future_map:
self.send_future_map.pop(message_id).set_result(body)
self.remove_message_timeout(message_id)
else:
if self._on_recv is not None:
self.io_loop.spawn_callback(self._on_recv, header, body)
else:
log.error('Got response for message_id %s that we are not tracking', message_id)
except StreamClosedError as e:
log.debug('tcp stream to %s:%s closed, unable to recv', self.host, self.port)
for future in six.itervalues(self.send_future_map):
future.set_exception(e)
self.send_future_map = {}
if self._closing:
return
if self.disconnect_callback:
self.disconnect_callback()
# if the last connect finished, then we need to make a new one
if self._connecting_future.done():
self._connecting_future = self.connect()
yield self._connecting_future
except TypeError:
# This is an invalid transport
if 'detect_mode' in self.opts:
log.info('There was an error trying to use TCP transport; '
'attempting to fallback to another transport')
else:
raise SaltClientError
except Exception as e:
log.error('Exception parsing response', exc_info=True)
for future in six.itervalues(self.send_future_map):
future.set_exception(e)
self.send_future_map = {}
if self._closing:
return
if self.disconnect_callback:
self.disconnect_callback()
# if the last connect finished, then we need to make a new one
if self._connecting_future.done():
self._connecting_future = self.connect()
yield self._connecting_future
finally:
self._stream_return_future.set_result(True)
@tornado.gen.coroutine
def _stream_send(self):
while not self._connecting_future.done() or self._connecting_future.result() is not True:
yield self._connecting_future
while self.send_queue:
message_id, item = self.send_queue[0]
try:
yield self._stream.write(item)
del self.send_queue[0]
# if the connection is dead, lets fail this send, and make sure we
# attempt to reconnect
except StreamClosedError as e:
if message_id in self.send_future_map:
self.send_future_map.pop(message_id).set_exception(e)
self.remove_message_timeout(message_id)
del self.send_queue[0]
if self._closing:
return
if self.disconnect_callback:
self.disconnect_callback()
# if the last connect finished, then we need to make a new one
if self._connecting_future.done():
self._connecting_future = self.connect()
yield self._connecting_future
def _message_id(self):
wrap = False
while self._mid in self.send_future_map:
if self._mid >= self._max_messages:
if wrap:
# this shouldn't ever happen, but just in case
raise Exception('Unable to find available messageid')
self._mid = 1
wrap = True
else:
self._mid += 1
return self._mid
# TODO: return a message object which takes care of multiplexing?
def on_recv(self, callback):
'''
Register a callback for received messages (that we didn't initiate)
'''
if callback is None:
self._on_recv = callback
else:
def wrap_recv(header, body):
callback(body)
self._on_recv = wrap_recv
def remove_message_timeout(self, message_id):
if message_id not in self.send_timeout_map:
return
timeout = self.send_timeout_map.pop(message_id)
self.io_loop.remove_timeout(timeout)
def timeout_message(self, message_id):
if message_id in self.send_timeout_map:
del self.send_timeout_map[message_id]
if message_id in self.send_future_map:
self.send_future_map.pop(message_id).set_exception(
SaltReqTimeoutError('Message timed out')
)
def send(self, msg, timeout=None, callback=None, raw=False):
'''
Send given message, and return a future
'''
message_id = self._message_id()
header = {'mid': message_id}
future = tornado.concurrent.Future()
if callback is not None:
def handle_future(future):
response = future.result()
self.io_loop.add_callback(callback, response)
future.add_done_callback(handle_future)
# Add this future to the mapping
self.send_future_map[message_id] = future
if self.opts.get('detect_mode') is True:
timeout = 1
if timeout is not None:
send_timeout = self.io_loop.call_later(timeout, self.timeout_message, message_id)
self.send_timeout_map[message_id] = send_timeout
# if we don't have a send queue, we need to spawn the callback to do the sending
if not self.send_queue:
self.io_loop.spawn_callback(self._stream_send)
self.send_queue.append((message_id, salt.transport.frame.frame_msg(msg, header=header)))
return future
|
saltstack/salt
|
salt/transport/tcp.py
|
SaltMessageClient.on_recv
|
python
|
def on_recv(self, callback):
'''
Register a callback for received messages (that we didn't initiate)
'''
if callback is None:
self._on_recv = callback
else:
def wrap_recv(header, body):
callback(body)
self._on_recv = wrap_recv
|
Register a callback for received messages (that we didn't initiate)
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/tcp.py#L1142-L1151
| null |
class SaltMessageClient(object):
'''
Low-level message sending client
'''
def __init__(self, opts, host, port, io_loop=None, resolver=None,
connect_callback=None, disconnect_callback=None,
source_ip=None, source_port=None):
self.opts = opts
self.host = host
self.port = port
self.source_ip = source_ip
self.source_port = source_port
self.connect_callback = connect_callback
self.disconnect_callback = disconnect_callback
self.io_loop = io_loop or tornado.ioloop.IOLoop.current()
with salt.utils.asynchronous.current_ioloop(self.io_loop):
self._tcp_client = TCPClientKeepAlive(opts, resolver=resolver)
self._mid = 1
self._max_messages = int((1 << 31) - 2) # number of IDs before we wrap
# TODO: max queue size
self.send_queue = [] # queue of messages to be sent
self.send_future_map = {} # mapping of request_id -> Future
self.send_timeout_map = {} # request_id -> timeout_callback
self._read_until_future = None
self._on_recv = None
self._closing = False
self._connecting_future = self.connect()
self._stream_return_future = tornado.concurrent.Future()
self.io_loop.spawn_callback(self._stream_return)
# TODO: timeout inflight sessions
def close(self):
if self._closing:
return
self._closing = True
if hasattr(self, '_stream') and not self._stream.closed():
# If _stream_return() hasn't completed, it means the IO
# Loop is stopped (such as when using
# 'salt.utils.asynchronous.SyncWrapper'). Ensure that
# _stream_return() completes by restarting the IO Loop.
# This will prevent potential errors on shutdown.
try:
orig_loop = tornado.ioloop.IOLoop.current()
self.io_loop.make_current()
self._stream.close()
if self._read_until_future is not None:
# This will prevent this message from showing up:
# '[ERROR ] Future exception was never retrieved:
# StreamClosedError'
# This happens because the logic is always waiting to read
# the next message and the associated read future is marked
# 'StreamClosedError' when the stream is closed.
if self._read_until_future.done():
self._read_until_future.exception()
elif self.io_loop != tornado.ioloop.IOLoop.current(instance=False):
self.io_loop.add_future(
self._stream_return_future,
lambda future: self.io_loop.stop()
)
self.io_loop.start()
finally:
orig_loop.make_current()
self._tcp_client.close()
# Clear callback references to allow the object that they belong to
# to be deleted.
self.connect_callback = None
self.disconnect_callback = None
def __del__(self):
self.close()
def connect(self):
'''
Ask for this client to reconnect to the origin
'''
if hasattr(self, '_connecting_future') and not self._connecting_future.done():
future = self._connecting_future
else:
future = tornado.concurrent.Future()
self._connecting_future = future
self.io_loop.add_callback(self._connect)
# Add the callback only when a new future is created
if self.connect_callback is not None:
def handle_future(future):
response = future.result()
self.io_loop.add_callback(self.connect_callback, response)
future.add_done_callback(handle_future)
return future
# TODO: tcp backoff opts
@tornado.gen.coroutine
def _connect(self):
'''
Try to connect for the rest of time!
'''
while True:
if self._closing:
break
try:
kwargs = {}
if self.source_ip or self.source_port:
if tornado.version_info >= (4, 5):
### source_ip and source_port are supported only in Tornado >= 4.5
# See http://www.tornadoweb.org/en/stable/releases/v4.5.0.html
# Otherwise will just ignore these args
kwargs = {'source_ip': self.source_ip,
'source_port': self.source_port}
else:
log.warning('If you need a certain source IP/port, consider upgrading Tornado >= 4.5')
with salt.utils.asynchronous.current_ioloop(self.io_loop):
self._stream = yield self._tcp_client.connect(self.host,
self.port,
ssl_options=self.opts.get('ssl'),
**kwargs)
self._connecting_future.set_result(True)
break
except Exception as e:
yield tornado.gen.sleep(1) # TODO: backoff
#self._connecting_future.set_exception(e)
@tornado.gen.coroutine
def _stream_return(self):
try:
while not self._closing and (
not self._connecting_future.done() or
self._connecting_future.result() is not True):
yield self._connecting_future
unpacker = msgpack.Unpacker()
while not self._closing:
try:
self._read_until_future = self._stream.read_bytes(4096, partial=True)
wire_bytes = yield self._read_until_future
unpacker.feed(wire_bytes)
for framed_msg in unpacker:
if six.PY3:
framed_msg = salt.transport.frame.decode_embedded_strs(
framed_msg
)
header = framed_msg['head']
body = framed_msg['body']
message_id = header.get('mid')
if message_id in self.send_future_map:
self.send_future_map.pop(message_id).set_result(body)
self.remove_message_timeout(message_id)
else:
if self._on_recv is not None:
self.io_loop.spawn_callback(self._on_recv, header, body)
else:
log.error('Got response for message_id %s that we are not tracking', message_id)
except StreamClosedError as e:
log.debug('tcp stream to %s:%s closed, unable to recv', self.host, self.port)
for future in six.itervalues(self.send_future_map):
future.set_exception(e)
self.send_future_map = {}
if self._closing:
return
if self.disconnect_callback:
self.disconnect_callback()
# if the last connect finished, then we need to make a new one
if self._connecting_future.done():
self._connecting_future = self.connect()
yield self._connecting_future
except TypeError:
# This is an invalid transport
if 'detect_mode' in self.opts:
log.info('There was an error trying to use TCP transport; '
'attempting to fallback to another transport')
else:
raise SaltClientError
except Exception as e:
log.error('Exception parsing response', exc_info=True)
for future in six.itervalues(self.send_future_map):
future.set_exception(e)
self.send_future_map = {}
if self._closing:
return
if self.disconnect_callback:
self.disconnect_callback()
# if the last connect finished, then we need to make a new one
if self._connecting_future.done():
self._connecting_future = self.connect()
yield self._connecting_future
finally:
self._stream_return_future.set_result(True)
@tornado.gen.coroutine
def _stream_send(self):
while not self._connecting_future.done() or self._connecting_future.result() is not True:
yield self._connecting_future
while self.send_queue:
message_id, item = self.send_queue[0]
try:
yield self._stream.write(item)
del self.send_queue[0]
# if the connection is dead, lets fail this send, and make sure we
# attempt to reconnect
except StreamClosedError as e:
if message_id in self.send_future_map:
self.send_future_map.pop(message_id).set_exception(e)
self.remove_message_timeout(message_id)
del self.send_queue[0]
if self._closing:
return
if self.disconnect_callback:
self.disconnect_callback()
# if the last connect finished, then we need to make a new one
if self._connecting_future.done():
self._connecting_future = self.connect()
yield self._connecting_future
def _message_id(self):
wrap = False
while self._mid in self.send_future_map:
if self._mid >= self._max_messages:
if wrap:
# this shouldn't ever happen, but just in case
raise Exception('Unable to find available messageid')
self._mid = 1
wrap = True
else:
self._mid += 1
return self._mid
# TODO: return a message object which takes care of multiplexing?
def remove_message_timeout(self, message_id):
if message_id not in self.send_timeout_map:
return
timeout = self.send_timeout_map.pop(message_id)
self.io_loop.remove_timeout(timeout)
def timeout_message(self, message_id):
if message_id in self.send_timeout_map:
del self.send_timeout_map[message_id]
if message_id in self.send_future_map:
self.send_future_map.pop(message_id).set_exception(
SaltReqTimeoutError('Message timed out')
)
def send(self, msg, timeout=None, callback=None, raw=False):
'''
Send given message, and return a future
'''
message_id = self._message_id()
header = {'mid': message_id}
future = tornado.concurrent.Future()
if callback is not None:
def handle_future(future):
response = future.result()
self.io_loop.add_callback(callback, response)
future.add_done_callback(handle_future)
# Add this future to the mapping
self.send_future_map[message_id] = future
if self.opts.get('detect_mode') is True:
timeout = 1
if timeout is not None:
send_timeout = self.io_loop.call_later(timeout, self.timeout_message, message_id)
self.send_timeout_map[message_id] = send_timeout
# if we don't have a send queue, we need to spawn the callback to do the sending
if not self.send_queue:
self.io_loop.spawn_callback(self._stream_send)
self.send_queue.append((message_id, salt.transport.frame.frame_msg(msg, header=header)))
return future
|
saltstack/salt
|
salt/transport/tcp.py
|
SaltMessageClient.send
|
python
|
def send(self, msg, timeout=None, callback=None, raw=False):
'''
Send given message, and return a future
'''
message_id = self._message_id()
header = {'mid': message_id}
future = tornado.concurrent.Future()
if callback is not None:
def handle_future(future):
response = future.result()
self.io_loop.add_callback(callback, response)
future.add_done_callback(handle_future)
# Add this future to the mapping
self.send_future_map[message_id] = future
if self.opts.get('detect_mode') is True:
timeout = 1
if timeout is not None:
send_timeout = self.io_loop.call_later(timeout, self.timeout_message, message_id)
self.send_timeout_map[message_id] = send_timeout
# if we don't have a send queue, we need to spawn the callback to do the sending
if not self.send_queue:
self.io_loop.spawn_callback(self._stream_send)
self.send_queue.append((message_id, salt.transport.frame.frame_msg(msg, header=header)))
return future
|
Send given message, and return a future
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/tcp.py#L1167-L1194
|
[
"def frame_msg(body, header=None, raw_body=False): # pylint: disable=unused-argument\n '''\n Frame the given message with our wire protocol\n '''\n framed_msg = {}\n if header is None:\n header = {}\n\n framed_msg['head'] = header\n framed_msg['body'] = body\n return salt.utils.msgpack.dumps(framed_msg)\n",
"def _message_id(self):\n wrap = False\n while self._mid in self.send_future_map:\n if self._mid >= self._max_messages:\n if wrap:\n # this shouldn't ever happen, but just in case\n raise Exception('Unable to find available messageid')\n self._mid = 1\n wrap = True\n else:\n self._mid += 1\n\n return self._mid\n"
] |
class SaltMessageClient(object):
'''
Low-level message sending client
'''
def __init__(self, opts, host, port, io_loop=None, resolver=None,
connect_callback=None, disconnect_callback=None,
source_ip=None, source_port=None):
self.opts = opts
self.host = host
self.port = port
self.source_ip = source_ip
self.source_port = source_port
self.connect_callback = connect_callback
self.disconnect_callback = disconnect_callback
self.io_loop = io_loop or tornado.ioloop.IOLoop.current()
with salt.utils.asynchronous.current_ioloop(self.io_loop):
self._tcp_client = TCPClientKeepAlive(opts, resolver=resolver)
self._mid = 1
self._max_messages = int((1 << 31) - 2) # number of IDs before we wrap
# TODO: max queue size
self.send_queue = [] # queue of messages to be sent
self.send_future_map = {} # mapping of request_id -> Future
self.send_timeout_map = {} # request_id -> timeout_callback
self._read_until_future = None
self._on_recv = None
self._closing = False
self._connecting_future = self.connect()
self._stream_return_future = tornado.concurrent.Future()
self.io_loop.spawn_callback(self._stream_return)
# TODO: timeout inflight sessions
def close(self):
if self._closing:
return
self._closing = True
if hasattr(self, '_stream') and not self._stream.closed():
# If _stream_return() hasn't completed, it means the IO
# Loop is stopped (such as when using
# 'salt.utils.asynchronous.SyncWrapper'). Ensure that
# _stream_return() completes by restarting the IO Loop.
# This will prevent potential errors on shutdown.
try:
orig_loop = tornado.ioloop.IOLoop.current()
self.io_loop.make_current()
self._stream.close()
if self._read_until_future is not None:
# This will prevent this message from showing up:
# '[ERROR ] Future exception was never retrieved:
# StreamClosedError'
# This happens because the logic is always waiting to read
# the next message and the associated read future is marked
# 'StreamClosedError' when the stream is closed.
if self._read_until_future.done():
self._read_until_future.exception()
elif self.io_loop != tornado.ioloop.IOLoop.current(instance=False):
self.io_loop.add_future(
self._stream_return_future,
lambda future: self.io_loop.stop()
)
self.io_loop.start()
finally:
orig_loop.make_current()
self._tcp_client.close()
# Clear callback references to allow the object that they belong to
# to be deleted.
self.connect_callback = None
self.disconnect_callback = None
def __del__(self):
self.close()
def connect(self):
'''
Ask for this client to reconnect to the origin
'''
if hasattr(self, '_connecting_future') and not self._connecting_future.done():
future = self._connecting_future
else:
future = tornado.concurrent.Future()
self._connecting_future = future
self.io_loop.add_callback(self._connect)
# Add the callback only when a new future is created
if self.connect_callback is not None:
def handle_future(future):
response = future.result()
self.io_loop.add_callback(self.connect_callback, response)
future.add_done_callback(handle_future)
return future
# TODO: tcp backoff opts
@tornado.gen.coroutine
def _connect(self):
'''
Try to connect for the rest of time!
'''
while True:
if self._closing:
break
try:
kwargs = {}
if self.source_ip or self.source_port:
if tornado.version_info >= (4, 5):
### source_ip and source_port are supported only in Tornado >= 4.5
# See http://www.tornadoweb.org/en/stable/releases/v4.5.0.html
# Otherwise will just ignore these args
kwargs = {'source_ip': self.source_ip,
'source_port': self.source_port}
else:
log.warning('If you need a certain source IP/port, consider upgrading Tornado >= 4.5')
with salt.utils.asynchronous.current_ioloop(self.io_loop):
self._stream = yield self._tcp_client.connect(self.host,
self.port,
ssl_options=self.opts.get('ssl'),
**kwargs)
self._connecting_future.set_result(True)
break
except Exception as e:
yield tornado.gen.sleep(1) # TODO: backoff
#self._connecting_future.set_exception(e)
@tornado.gen.coroutine
def _stream_return(self):
try:
while not self._closing and (
not self._connecting_future.done() or
self._connecting_future.result() is not True):
yield self._connecting_future
unpacker = msgpack.Unpacker()
while not self._closing:
try:
self._read_until_future = self._stream.read_bytes(4096, partial=True)
wire_bytes = yield self._read_until_future
unpacker.feed(wire_bytes)
for framed_msg in unpacker:
if six.PY3:
framed_msg = salt.transport.frame.decode_embedded_strs(
framed_msg
)
header = framed_msg['head']
body = framed_msg['body']
message_id = header.get('mid')
if message_id in self.send_future_map:
self.send_future_map.pop(message_id).set_result(body)
self.remove_message_timeout(message_id)
else:
if self._on_recv is not None:
self.io_loop.spawn_callback(self._on_recv, header, body)
else:
log.error('Got response for message_id %s that we are not tracking', message_id)
except StreamClosedError as e:
log.debug('tcp stream to %s:%s closed, unable to recv', self.host, self.port)
for future in six.itervalues(self.send_future_map):
future.set_exception(e)
self.send_future_map = {}
if self._closing:
return
if self.disconnect_callback:
self.disconnect_callback()
# if the last connect finished, then we need to make a new one
if self._connecting_future.done():
self._connecting_future = self.connect()
yield self._connecting_future
except TypeError:
# This is an invalid transport
if 'detect_mode' in self.opts:
log.info('There was an error trying to use TCP transport; '
'attempting to fallback to another transport')
else:
raise SaltClientError
except Exception as e:
log.error('Exception parsing response', exc_info=True)
for future in six.itervalues(self.send_future_map):
future.set_exception(e)
self.send_future_map = {}
if self._closing:
return
if self.disconnect_callback:
self.disconnect_callback()
# if the last connect finished, then we need to make a new one
if self._connecting_future.done():
self._connecting_future = self.connect()
yield self._connecting_future
finally:
self._stream_return_future.set_result(True)
@tornado.gen.coroutine
def _stream_send(self):
while not self._connecting_future.done() or self._connecting_future.result() is not True:
yield self._connecting_future
while self.send_queue:
message_id, item = self.send_queue[0]
try:
yield self._stream.write(item)
del self.send_queue[0]
# if the connection is dead, lets fail this send, and make sure we
# attempt to reconnect
except StreamClosedError as e:
if message_id in self.send_future_map:
self.send_future_map.pop(message_id).set_exception(e)
self.remove_message_timeout(message_id)
del self.send_queue[0]
if self._closing:
return
if self.disconnect_callback:
self.disconnect_callback()
# if the last connect finished, then we need to make a new one
if self._connecting_future.done():
self._connecting_future = self.connect()
yield self._connecting_future
def _message_id(self):
wrap = False
while self._mid in self.send_future_map:
if self._mid >= self._max_messages:
if wrap:
# this shouldn't ever happen, but just in case
raise Exception('Unable to find available messageid')
self._mid = 1
wrap = True
else:
self._mid += 1
return self._mid
# TODO: return a message object which takes care of multiplexing?
def on_recv(self, callback):
'''
Register a callback for received messages (that we didn't initiate)
'''
if callback is None:
self._on_recv = callback
else:
def wrap_recv(header, body):
callback(body)
self._on_recv = wrap_recv
def remove_message_timeout(self, message_id):
if message_id not in self.send_timeout_map:
return
timeout = self.send_timeout_map.pop(message_id)
self.io_loop.remove_timeout(timeout)
def timeout_message(self, message_id):
if message_id in self.send_timeout_map:
del self.send_timeout_map[message_id]
if message_id in self.send_future_map:
self.send_future_map.pop(message_id).set_exception(
SaltReqTimeoutError('Message timed out')
)
|
saltstack/salt
|
salt/transport/tcp.py
|
TCPPubServerChannel._publish_daemon
|
python
|
def _publish_daemon(self, **kwargs):
'''
Bind to the interface specified in the configuration file
'''
salt.utils.process.appendproctitle(self.__class__.__name__)
log_queue = kwargs.get('log_queue')
if log_queue is not None:
salt.log.setup.set_multiprocessing_logging_queue(log_queue)
log_queue_level = kwargs.get('log_queue_level')
if log_queue_level is not None:
salt.log.setup.set_multiprocessing_logging_level(log_queue_level)
salt.log.setup.setup_multiprocessing_logging(log_queue)
# Check if io_loop was set outside
if self.io_loop is None:
self.io_loop = tornado.ioloop.IOLoop.current()
# Spin up the publisher
pub_server = PubServer(self.opts, io_loop=self.io_loop)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
_set_tcp_keepalive(sock, self.opts)
sock.setblocking(0)
sock.bind((self.opts['interface'], int(self.opts['publish_port'])))
sock.listen(self.backlog)
# pub_server will take ownership of the socket
pub_server.add_socket(sock)
# Set up Salt IPC server
if self.opts.get('ipc_mode', '') == 'tcp':
pull_uri = int(self.opts.get('tcp_master_publish_pull', 4514))
else:
pull_uri = os.path.join(self.opts['sock_dir'], 'publish_pull.ipc')
pull_sock = salt.transport.ipc.IPCMessageServer(
self.opts,
pull_uri,
io_loop=self.io_loop,
payload_handler=pub_server.publish_payload,
)
# Securely create socket
log.info('Starting the Salt Puller on %s', pull_uri)
with salt.utils.files.set_umask(0o177):
pull_sock.start()
# run forever
try:
self.io_loop.start()
except (KeyboardInterrupt, SystemExit):
salt.log.setup.shutdown_multiprocessing_logging()
|
Bind to the interface specified in the configuration file
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/tcp.py#L1418-L1469
| null |
class TCPPubServerChannel(salt.transport.server.PubServerChannel):
# TODO: opts!
# Based on default used in tornado.netutil.bind_sockets()
backlog = 128
def __init__(self, opts):
self.opts = opts
self.serial = salt.payload.Serial(self.opts) # TODO: in init?
self.ckminions = salt.utils.minions.CkMinions(opts)
self.io_loop = None
def __setstate__(self, state):
salt.master.SMaster.secrets = state['secrets']
self.__init__(state['opts'])
def __getstate__(self):
return {'opts': self.opts,
'secrets': salt.master.SMaster.secrets}
def pre_fork(self, process_manager, kwargs=None):
'''
Do anything necessary pre-fork. Since this is on the master side this will
primarily be used to create IPC channels and create our daemon process to
do the actual publishing
'''
process_manager.add_process(self._publish_daemon, kwargs=kwargs)
def publish(self, load):
'''
Publish "load" to minions
'''
payload = {'enc': 'aes'}
crypticle = salt.crypt.Crypticle(self.opts, salt.master.SMaster.secrets['aes']['secret'].value)
payload['load'] = crypticle.dumps(load)
if self.opts['sign_pub_messages']:
master_pem_path = os.path.join(self.opts['pki_dir'], 'master.pem')
log.debug("Signing data packet")
payload['sig'] = salt.crypt.sign_message(master_pem_path, payload['load'])
# Use the Salt IPC server
if self.opts.get('ipc_mode', '') == 'tcp':
pull_uri = int(self.opts.get('tcp_master_publish_pull', 4514))
else:
pull_uri = os.path.join(self.opts['sock_dir'], 'publish_pull.ipc')
# TODO: switch to the actual asynchronous interface
#pub_sock = salt.transport.ipc.IPCMessageClient(self.opts, io_loop=self.io_loop)
pub_sock = salt.utils.asynchronous.SyncWrapper(
salt.transport.ipc.IPCMessageClient,
(pull_uri,)
)
pub_sock.connect()
int_payload = {'payload': self.serial.dumps(payload)}
# add some targeting stuff for lists only (for now)
if load['tgt_type'] == 'list':
if isinstance(load['tgt'], six.string_types):
# Fetch a list of minions that match
_res = self.ckminions.check_minions(load['tgt'],
tgt_type=load['tgt_type'])
match_ids = _res['minions']
log.debug("Publish Side Match: %s", match_ids)
# Send list of miions thru so zmq can target them
int_payload['topic_lst'] = match_ids
else:
int_payload['topic_lst'] = load['tgt']
# Send it over IPC!
pub_sock.send(int_payload)
|
saltstack/salt
|
salt/transport/tcp.py
|
TCPPubServerChannel.pre_fork
|
python
|
def pre_fork(self, process_manager, kwargs=None):
'''
Do anything necessary pre-fork. Since this is on the master side this will
primarily be used to create IPC channels and create our daemon process to
do the actual publishing
'''
process_manager.add_process(self._publish_daemon, kwargs=kwargs)
|
Do anything necessary pre-fork. Since this is on the master side this will
primarily be used to create IPC channels and create our daemon process to
do the actual publishing
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/tcp.py#L1471-L1477
| null |
class TCPPubServerChannel(salt.transport.server.PubServerChannel):
# TODO: opts!
# Based on default used in tornado.netutil.bind_sockets()
backlog = 128
def __init__(self, opts):
self.opts = opts
self.serial = salt.payload.Serial(self.opts) # TODO: in init?
self.ckminions = salt.utils.minions.CkMinions(opts)
self.io_loop = None
def __setstate__(self, state):
salt.master.SMaster.secrets = state['secrets']
self.__init__(state['opts'])
def __getstate__(self):
return {'opts': self.opts,
'secrets': salt.master.SMaster.secrets}
def _publish_daemon(self, **kwargs):
'''
Bind to the interface specified in the configuration file
'''
salt.utils.process.appendproctitle(self.__class__.__name__)
log_queue = kwargs.get('log_queue')
if log_queue is not None:
salt.log.setup.set_multiprocessing_logging_queue(log_queue)
log_queue_level = kwargs.get('log_queue_level')
if log_queue_level is not None:
salt.log.setup.set_multiprocessing_logging_level(log_queue_level)
salt.log.setup.setup_multiprocessing_logging(log_queue)
# Check if io_loop was set outside
if self.io_loop is None:
self.io_loop = tornado.ioloop.IOLoop.current()
# Spin up the publisher
pub_server = PubServer(self.opts, io_loop=self.io_loop)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
_set_tcp_keepalive(sock, self.opts)
sock.setblocking(0)
sock.bind((self.opts['interface'], int(self.opts['publish_port'])))
sock.listen(self.backlog)
# pub_server will take ownership of the socket
pub_server.add_socket(sock)
# Set up Salt IPC server
if self.opts.get('ipc_mode', '') == 'tcp':
pull_uri = int(self.opts.get('tcp_master_publish_pull', 4514))
else:
pull_uri = os.path.join(self.opts['sock_dir'], 'publish_pull.ipc')
pull_sock = salt.transport.ipc.IPCMessageServer(
self.opts,
pull_uri,
io_loop=self.io_loop,
payload_handler=pub_server.publish_payload,
)
# Securely create socket
log.info('Starting the Salt Puller on %s', pull_uri)
with salt.utils.files.set_umask(0o177):
pull_sock.start()
# run forever
try:
self.io_loop.start()
except (KeyboardInterrupt, SystemExit):
salt.log.setup.shutdown_multiprocessing_logging()
def publish(self, load):
'''
Publish "load" to minions
'''
payload = {'enc': 'aes'}
crypticle = salt.crypt.Crypticle(self.opts, salt.master.SMaster.secrets['aes']['secret'].value)
payload['load'] = crypticle.dumps(load)
if self.opts['sign_pub_messages']:
master_pem_path = os.path.join(self.opts['pki_dir'], 'master.pem')
log.debug("Signing data packet")
payload['sig'] = salt.crypt.sign_message(master_pem_path, payload['load'])
# Use the Salt IPC server
if self.opts.get('ipc_mode', '') == 'tcp':
pull_uri = int(self.opts.get('tcp_master_publish_pull', 4514))
else:
pull_uri = os.path.join(self.opts['sock_dir'], 'publish_pull.ipc')
# TODO: switch to the actual asynchronous interface
#pub_sock = salt.transport.ipc.IPCMessageClient(self.opts, io_loop=self.io_loop)
pub_sock = salt.utils.asynchronous.SyncWrapper(
salt.transport.ipc.IPCMessageClient,
(pull_uri,)
)
pub_sock.connect()
int_payload = {'payload': self.serial.dumps(payload)}
# add some targeting stuff for lists only (for now)
if load['tgt_type'] == 'list':
if isinstance(load['tgt'], six.string_types):
# Fetch a list of minions that match
_res = self.ckminions.check_minions(load['tgt'],
tgt_type=load['tgt_type'])
match_ids = _res['minions']
log.debug("Publish Side Match: %s", match_ids)
# Send list of miions thru so zmq can target them
int_payload['topic_lst'] = match_ids
else:
int_payload['topic_lst'] = load['tgt']
# Send it over IPC!
pub_sock.send(int_payload)
|
saltstack/salt
|
salt/transport/tcp.py
|
TCPPubServerChannel.publish
|
python
|
def publish(self, load):
'''
Publish "load" to minions
'''
payload = {'enc': 'aes'}
crypticle = salt.crypt.Crypticle(self.opts, salt.master.SMaster.secrets['aes']['secret'].value)
payload['load'] = crypticle.dumps(load)
if self.opts['sign_pub_messages']:
master_pem_path = os.path.join(self.opts['pki_dir'], 'master.pem')
log.debug("Signing data packet")
payload['sig'] = salt.crypt.sign_message(master_pem_path, payload['load'])
# Use the Salt IPC server
if self.opts.get('ipc_mode', '') == 'tcp':
pull_uri = int(self.opts.get('tcp_master_publish_pull', 4514))
else:
pull_uri = os.path.join(self.opts['sock_dir'], 'publish_pull.ipc')
# TODO: switch to the actual asynchronous interface
#pub_sock = salt.transport.ipc.IPCMessageClient(self.opts, io_loop=self.io_loop)
pub_sock = salt.utils.asynchronous.SyncWrapper(
salt.transport.ipc.IPCMessageClient,
(pull_uri,)
)
pub_sock.connect()
int_payload = {'payload': self.serial.dumps(payload)}
# add some targeting stuff for lists only (for now)
if load['tgt_type'] == 'list':
if isinstance(load['tgt'], six.string_types):
# Fetch a list of minions that match
_res = self.ckminions.check_minions(load['tgt'],
tgt_type=load['tgt_type'])
match_ids = _res['minions']
log.debug("Publish Side Match: %s", match_ids)
# Send list of miions thru so zmq can target them
int_payload['topic_lst'] = match_ids
else:
int_payload['topic_lst'] = load['tgt']
# Send it over IPC!
pub_sock.send(int_payload)
|
Publish "load" to minions
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/tcp.py#L1479-L1520
|
[
"def sign_message(privkey_path, message, passphrase=None):\n '''\n Use Crypto.Signature.PKCS1_v1_5 to sign a message. Returns the signature.\n '''\n key = get_rsa_key(privkey_path, passphrase)\n log.debug('salt.crypt.sign_message: Signing message.')\n if HAS_M2:\n md = EVP.MessageDigest('sha1')\n md.update(salt.utils.stringutils.to_bytes(message))\n digest = md.final()\n return key.sign(digest)\n else:\n signer = PKCS1_v1_5.new(key)\n return signer.sign(SHA.new(salt.utils.stringutils.to_bytes(message)))\n",
"def dumps(self, obj):\n '''\n Serialize and encrypt a python object\n '''\n return self.encrypt(self.PICKLE_PAD + self.serial.dumps(obj))\n"
] |
class TCPPubServerChannel(salt.transport.server.PubServerChannel):
# TODO: opts!
# Based on default used in tornado.netutil.bind_sockets()
backlog = 128
def __init__(self, opts):
self.opts = opts
self.serial = salt.payload.Serial(self.opts) # TODO: in init?
self.ckminions = salt.utils.minions.CkMinions(opts)
self.io_loop = None
def __setstate__(self, state):
salt.master.SMaster.secrets = state['secrets']
self.__init__(state['opts'])
def __getstate__(self):
return {'opts': self.opts,
'secrets': salt.master.SMaster.secrets}
def _publish_daemon(self, **kwargs):
'''
Bind to the interface specified in the configuration file
'''
salt.utils.process.appendproctitle(self.__class__.__name__)
log_queue = kwargs.get('log_queue')
if log_queue is not None:
salt.log.setup.set_multiprocessing_logging_queue(log_queue)
log_queue_level = kwargs.get('log_queue_level')
if log_queue_level is not None:
salt.log.setup.set_multiprocessing_logging_level(log_queue_level)
salt.log.setup.setup_multiprocessing_logging(log_queue)
# Check if io_loop was set outside
if self.io_loop is None:
self.io_loop = tornado.ioloop.IOLoop.current()
# Spin up the publisher
pub_server = PubServer(self.opts, io_loop=self.io_loop)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
_set_tcp_keepalive(sock, self.opts)
sock.setblocking(0)
sock.bind((self.opts['interface'], int(self.opts['publish_port'])))
sock.listen(self.backlog)
# pub_server will take ownership of the socket
pub_server.add_socket(sock)
# Set up Salt IPC server
if self.opts.get('ipc_mode', '') == 'tcp':
pull_uri = int(self.opts.get('tcp_master_publish_pull', 4514))
else:
pull_uri = os.path.join(self.opts['sock_dir'], 'publish_pull.ipc')
pull_sock = salt.transport.ipc.IPCMessageServer(
self.opts,
pull_uri,
io_loop=self.io_loop,
payload_handler=pub_server.publish_payload,
)
# Securely create socket
log.info('Starting the Salt Puller on %s', pull_uri)
with salt.utils.files.set_umask(0o177):
pull_sock.start()
# run forever
try:
self.io_loop.start()
except (KeyboardInterrupt, SystemExit):
salt.log.setup.shutdown_multiprocessing_logging()
def pre_fork(self, process_manager, kwargs=None):
'''
Do anything necessary pre-fork. Since this is on the master side this will
primarily be used to create IPC channels and create our daemon process to
do the actual publishing
'''
process_manager.add_process(self._publish_daemon, kwargs=kwargs)
|
saltstack/salt
|
salt/fileserver/gitfs.py
|
find_file
|
python
|
def find_file(path, tgt_env='base', **kwargs): # pylint: disable=W0613
'''
Find the first file to match the path and ref, read the file out of git
and send the path to the newly cached file
'''
return _gitfs().find_file(path, tgt_env=tgt_env, **kwargs)
|
Find the first file to match the path and ref, read the file out of git
and send the path to the newly cached file
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/gitfs.py#L150-L155
|
[
"def _gitfs(init_remotes=True):\n return salt.utils.gitfs.GitFS(\n __opts__,\n __opts__['gitfs_remotes'],\n per_remote_overrides=PER_REMOTE_OVERRIDES,\n per_remote_only=PER_REMOTE_ONLY,\n init_remotes=init_remotes)\n"
] |
# -*- coding: utf-8 -*-
'''
Git Fileserver Backend
With this backend, branches and tags in a remote git repository are exposed to
salt as different environments.
To enable, add ``gitfs`` to the :conf_master:`fileserver_backend` option in the
Master config file.
.. code-block:: yaml
fileserver_backend:
- gitfs
.. note::
``git`` also works here. Prior to the 2018.3.0 release, *only* ``git``
would work.
The Git fileserver backend supports both pygit2_ and GitPython_, to provide the
Python interface to git. If both are present, the order of preference for which
one will be chosen is the same as the order in which they were listed: pygit2,
then GitPython.
An optional master config parameter (:conf_master:`gitfs_provider`) can be used
to specify which provider should be used, in the event that compatible versions
of both pygit2_ and GitPython_ are installed.
More detailed information on how to use GitFS can be found in the :ref:`GitFS
Walkthrough <tutorial-gitfs>`.
.. note:: Minimum requirements
To use pygit2_ for GitFS requires a minimum pygit2_ version of 0.20.3.
pygit2_ 0.20.3 requires libgit2_ 0.20.0. pygit2_ and libgit2_ are developed
alongside one another, so it is recommended to keep them both at the same
major release to avoid unexpected behavior. For example, pygit2_ 0.21.x
requires libgit2_ 0.21.x, pygit2_ 0.22.x will require libgit2_ 0.22.x, etc.
To use GitPython_ for GitFS requires a minimum GitPython version of 0.3.0,
as well as the git CLI utility. Instructions for installing GitPython can
be found :ref:`here <gitfs-dependencies>`.
To clear stale refs the git CLI utility must also be installed.
.. _pygit2: https://github.com/libgit2/pygit2
.. _libgit2: https://libgit2.github.com/
.. _GitPython: https://github.com/gitpython-developers/GitPython
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
PER_REMOTE_OVERRIDES = (
'base', 'mountpoint', 'root', 'ssl_verify',
'saltenv_whitelist', 'saltenv_blacklist',
'env_whitelist', 'env_blacklist', 'refspecs',
'disable_saltenv_mapping', 'ref_types', 'update_interval',
)
PER_REMOTE_ONLY = ('all_saltenvs', 'name', 'saltenv')
# Auth support (auth params can be global or per-remote, too)
AUTH_PROVIDERS = ('pygit2',)
AUTH_PARAMS = ('user', 'password', 'pubkey', 'privkey', 'passphrase',
'insecure_auth')
# Import salt libs
import salt.utils.gitfs
from salt.exceptions import FileserverConfigError
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'gitfs'
def _gitfs(init_remotes=True):
return salt.utils.gitfs.GitFS(
__opts__,
__opts__['gitfs_remotes'],
per_remote_overrides=PER_REMOTE_OVERRIDES,
per_remote_only=PER_REMOTE_ONLY,
init_remotes=init_remotes)
def __virtual__():
'''
Only load if the desired provider module is present and gitfs is enabled
properly in the master config file.
'''
if __virtualname__ not in __opts__['fileserver_backend']:
return False
try:
_gitfs(init_remotes=False)
# Initialization of the GitFS object did not fail, so we know we have
# valid configuration syntax and that a valid provider was detected.
return __virtualname__
except FileserverConfigError:
pass
return False
def clear_cache():
'''
Completely clear gitfs cache
'''
return _gitfs(init_remotes=False).clear_cache()
def clear_lock(remote=None, lock_type='update'):
'''
Clear update.lk
'''
return _gitfs().clear_lock(remote=remote, lock_type=lock_type)
def lock(remote=None):
'''
Place an update.lk
``remote`` can either be a dictionary containing repo configuration
information, or a pattern. If the latter, then remotes for which the URL
matches the pattern will be locked.
'''
return _gitfs().lock(remote=remote)
def update(remotes=None):
'''
Execute a git fetch on all of the repos
'''
_gitfs().update(remotes)
def update_intervals():
'''
Returns the update intervals for each configured remote
'''
return _gitfs().update_intervals()
def envs(ignore_cache=False):
'''
Return a list of refs that can be used as environments
'''
return _gitfs().envs(ignore_cache=ignore_cache)
def init():
'''
Initialize remotes. This is only used by the master's pre-flight checks,
and is not invoked by GitFS.
'''
_gitfs()
def serve_file(load, fnd):
'''
Return a chunk from a file based on the data received
'''
return _gitfs().serve_file(load, fnd)
def file_hash(load, fnd):
'''
Return a file hash, the hash type is set in the master config file
'''
return _gitfs().file_hash(load, fnd)
def file_list(load):
'''
Return a list of all files on the file server in a specified
environment (specified as a key within the load dict).
'''
return _gitfs().file_list(load)
def file_list_emptydirs(load): # pylint: disable=W0613
'''
Return a list of all empty directories on the master
'''
# Cannot have empty dirs in git
return []
def dir_list(load):
'''
Return a list of all directories on the master
'''
return _gitfs().dir_list(load)
def symlink_list(load):
'''
Return a dict of all symlinks based on a given path in the repo
'''
return _gitfs().symlink_list(load)
|
saltstack/salt
|
salt/modules/debian_ip.py
|
_error_msg_iface
|
python
|
def _error_msg_iface(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, '|'.join(str(e) for e in expected))
|
Build an appropriate error message from a given option and
a list of expected values.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_ip.py#L155-L161
| null |
# -*- coding: utf-8 -*-
'''
The networking module for Debian-based distros
References:
* http://www.debian.org/doc/manuals/debian-reference/ch05.en.html
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import functools
import logging
import os.path
import os
import re
import time
# Import third party libs
import jinja2
import jinja2.exceptions
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error,no-name-in-module
# Import salt libs
import salt.utils.dns
import salt.utils.files
import salt.utils.odict
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.validate.net
# Set up logging
log = logging.getLogger(__name__)
# Set up template environment
JINJA = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'debian_ip')
)
)
# Define the module's virtual name
__virtualname__ = 'ip'
def __virtual__():
'''
Confine this module to Debian-based distros
'''
if __grains__['os_family'] == 'Debian':
return __virtualname__
return (False, 'The debian_ip module could not be loaded: '
'unsupported OS family')
_ETHTOOL_CONFIG_OPTS = {
'speed': 'link-speed',
'duplex': 'link-duplex',
'autoneg': 'ethernet-autoneg',
'ethernet-port': 'ethernet-port',
'wol': 'ethernet-wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'rx': 'offload-rx',
'tx': 'offload-tx',
'sg': 'offload-sg',
'tso': 'offload-tso',
'ufo': 'offload-ufo',
'gso': 'offload-gso',
'gro': 'offload-gro',
'lro': 'offload-lro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_REV_ETHTOOL_CONFIG_OPTS = {
'link-speed': 'speed',
'link-duplex': 'duplex',
'ethernet-autoneg': 'autoneg',
'ethernet-port': 'ethernet-port',
'ethernet-wol': 'wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'offload-rx': 'rx',
'offload-tx': 'tx',
'offload-sg': 'sg',
'offload-tso': 'tso',
'offload-ufo': 'ufo',
'offload-gso': 'gso',
'offload-lro': 'lro',
'offload-gro': 'gro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_DEB_CONFIG_PPPOE_OPTS = {
'user': 'user',
'password': 'password',
'provider': 'provider',
'pppoe_iface': 'pppoe_iface',
'noipdefault': 'noipdefault',
'usepeerdns': 'usepeerdns',
'defaultroute': 'defaultroute',
'holdoff': 'holdoff',
'maxfail': 'maxfail',
'hide-password': 'hide-password',
'lcp-echo-interval': 'lcp-echo-interval',
'lcp-echo-failure': 'lcp-echo-failure',
'connect': 'connect',
'noauth': 'noauth',
'persist': 'persist',
'mtu': 'mtu',
'noaccomp': 'noaccomp',
'linkname': 'linkname',
}
_DEB_ROUTES_FILE = '/etc/network/routes'
_DEB_NETWORK_FILE = '/etc/network/interfaces'
_DEB_NETWORK_DIR = '/etc/network/interfaces.d/'
_DEB_NETWORK_UP_DIR = '/etc/network/if-up.d/'
_DEB_NETWORK_DOWN_DIR = '/etc/network/if-down.d/'
_DEB_NETWORK_CONF_FILES = '/etc/modprobe.d/'
_DEB_NETWORKING_FILE = '/etc/default/networking'
_DEB_HOSTNAME_FILE = '/etc/hostname'
_DEB_RESOLV_FILE = '/etc/resolv.conf'
_DEB_PPP_DIR = '/etc/ppp/peers/'
_CONFIG_TRUE = ['yes', 'on', 'true', '1', True]
_CONFIG_FALSE = ['no', 'off', 'false', '0', False]
_IFACE_TYPES = [
'eth', 'bond', 'alias', 'clone',
'ipsec', 'dialup', 'bridge', 'slave',
'vlan', 'pppoe', 'source',
]
def _error_msg_routes(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, expected)
def _log_default_iface(iface, opt, value):
log.info(
'Using default option -- Interface: %s Option: %s Value: %s',
iface, opt, value
)
def _error_msg_network(option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]'
return msg.format(option, '|'.join(str(e) for e in expected))
def _log_default_network(opt, value):
log.info('Using existing setting -- Setting: %s Value: %s', opt, value)
def _raise_error_iface(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_iface(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_network(option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_network(option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_routes(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_routes(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _read_file(path):
'''
Reads and returns the contents of a text file
'''
try:
with salt.utils.files.flopen(path, 'rb') as contents:
return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]
except (OSError, IOError):
return ''
def _parse_resolve():
'''
Parse /etc/resolv.conf
'''
return salt.utils.dns.parse_resolv(_DEB_RESOLV_FILE)
def _parse_domainname():
'''
Parse /etc/resolv.conf and return domainname
'''
return _parse_resolve().get('domain', '')
def _parse_searchdomain():
'''
Parse /etc/resolv.conf and return searchdomain
'''
return _parse_resolve().get('search', '')
def _parse_hostname():
'''
Parse /etc/hostname and return hostname
'''
contents = _read_file(_DEB_HOSTNAME_FILE)
if contents:
return contents[0].split('\n')[0]
else:
return ''
def _parse_current_network_settings():
'''
Parse /etc/default/networking and return current configuration
'''
opts = salt.utils.odict.OrderedDict()
opts['networking'] = ''
if os.path.isfile(_DEB_NETWORKING_FILE):
with salt.utils.files.fopen(_DEB_NETWORKING_FILE) as contents:
for line in contents:
salt.utils.stringutils.to_unicode(line)
if line.startswith('#'):
continue
elif line.startswith('CONFIGURE_INTERFACES'):
opts['networking'] = line.split('=', 1)[1].strip()
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
opts['hostname'] = hostname
opts['domainname'] = domainname
opts['searchdomain'] = searchdomain
return opts
# def __validator_func(value):
# return (valid: True/False, (transformed) value, error message)
def __ipv4_quad(value):
'''validate an IPv4 address'''
return (salt.utils.validate.net.ipv4_addr(value), value,
'dotted IPv4 address')
def __ipv6(value):
'''validate an IPv6 address'''
return (salt.utils.validate.net.ipv6_addr(value), value,
'IPv6 address')
def __mac(value):
'''validate a mac address'''
return (salt.utils.validate.net.mac(value), value,
'MAC address')
def __anything(value):
return (True, value, None)
def __int(value):
'''validate an integer'''
valid, _value = False, value
try:
_value = int(value)
valid = True
except ValueError:
pass
return (valid, _value, 'integer')
def __float(value):
'''validate a float'''
valid, _value = False, value
try:
_value = float(value)
valid = True
except ValueError:
pass
return (valid, _value, 'float')
def __ipv4_netmask(value):
'''validate an IPv4 dotted quad or integer CIDR netmask'''
valid, errmsg = False, 'dotted quad or integer CIDR (0->32)'
valid, value, _ = __int(value)
if not (valid and 0 <= value <= 32):
valid = salt.utils.validate.net.netmask(value)
return (valid, value, errmsg)
def __ipv6_netmask(value):
'''validate an IPv6 integer netmask'''
valid, errmsg = False, 'IPv6 netmask (0->128)'
valid, value, _ = __int(value)
valid = (valid and 0 <= value <= 128)
return (valid, value, errmsg)
def __within2(value, within=None, errmsg=None, dtype=None):
'''validate that a value is in ``within`` and optionally a ``dtype``'''
valid, _value = False, value
if dtype:
try:
_value = dtype(value) # TODO: this is a bit loose when dtype is a class
valid = _value in within
except ValueError:
pass
else:
valid = _value in within
if errmsg is None:
if dtype:
typename = getattr(dtype, '__name__',
hasattr(dtype, '__class__')
and getattr(dtype.__class__, 'name', dtype))
errmsg = '{0} within \'{1}\''.format(typename, within)
else:
errmsg = 'within \'{0}\''.format(within)
return (valid, _value, errmsg)
def __within(within=None, errmsg=None, dtype=None):
return functools.partial(__within2, within=within,
errmsg=errmsg, dtype=dtype)
def __space_delimited_list(value):
'''validate that a value contains one or more space-delimited values'''
if isinstance(value, six.string_types):
value = value.strip().split()
if hasattr(value, '__iter__') and value != []:
return (True, value, 'space-delimited string')
else:
return (False, value, '{0} is not a valid space-delimited value.\n'.format(value))
SALT_ATTR_TO_DEBIAN_ATTR_MAP = {
'dns': 'dns-nameservers',
'search': 'dns-search',
'hwaddr': 'hwaddress', # TODO: this limits bootp functionality
'ipaddr': 'address',
'ipaddrs': 'addresses',
}
DEBIAN_ATTR_TO_SALT_ATTR_MAP = dict(
(v, k) for (k, v) in six.iteritems(SALT_ATTR_TO_DEBIAN_ATTR_MAP))
# TODO
DEBIAN_ATTR_TO_SALT_ATTR_MAP['address'] = 'address'
DEBIAN_ATTR_TO_SALT_ATTR_MAP['hwaddress'] = 'hwaddress'
IPV4_VALID_PROTO = ['bootp', 'dhcp', 'static', 'manual', 'loopback', 'ppp']
IPV4_ATTR_MAP = {
'proto': __within(IPV4_VALID_PROTO, dtype=six.text_type),
# ipv4 static & manual
'address': __ipv4_quad,
'addresses': __anything,
'netmask': __ipv4_netmask,
'broadcast': __ipv4_quad,
'metric': __int,
'gateway': __ipv4_quad, # supports a colon-delimited list
'pointopoint': __ipv4_quad,
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'link', 'host'], dtype=six.text_type),
# dhcp
'hostname': __anything,
'leasehours': __int,
'leasetime': __int,
'vendor': __anything,
'client': __anything,
# bootp
'bootfile': __anything,
'server': __ipv4_quad,
'hwaddr': __mac,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'dstaddr': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# bond
'slaves': __anything,
# ppp
'provider': __anything,
'unit': __int,
'options': __anything,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
#
'network': __anything, # i don't know what this is
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
IPV6_VALID_PROTO = ['auto', 'loopback', 'static', 'manual',
'dhcp', 'v4tunnel', '6to4']
IPV6_ATTR_MAP = {
'proto': __within(IPV6_VALID_PROTO),
# ipv6 static & manual
'address': __ipv6,
'addresses': __anything,
'netmask': __ipv6_netmask,
'broadcast': __ipv6,
'gateway': __ipv6, # supports a colon-delimited list
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'site', 'link', 'host'], dtype=six.text_type),
# inet6 auto
'privext': __within([0, 1, 2], dtype=int),
'dhcp': __within([0, 1], dtype=int),
# inet6 static & manual & dhcp
'media': __anything,
'accept_ra': __within([0, 1], dtype=int),
'autoconf': __within([0, 1], dtype=int),
'preferred-lifetime': __int,
'dad-attempts': __int, # 0 to disable
'dad-interval': __float,
# bond
'slaves': __anything,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
WIRELESS_ATTR_MAP = {
'wireless-essid': __anything,
'wireless-mode': __anything, # TODO
'wpa-ap-scan': __within([0, 1, 2], dtype=int), # TODO
'wpa-conf': __anything,
'wpa-driver': __anything,
'wpa-group': __anything,
'wpa-key-mgmt': __anything,
'wpa-pairwise': __anything,
'wpa-psk': __anything,
'wpa-proto': __anything, # partial(__within,
'wpa-roam': __anything,
'wpa-ssid': __anything, # TODO
}
ATTRMAPS = {
'inet': [IPV4_ATTR_MAP, WIRELESS_ATTR_MAP],
'inet6': [IPV6_ATTR_MAP, WIRELESS_ATTR_MAP]
}
def _validate_interface_option(attr, value, addrfam='inet'):
'''lookup the validation function for a [addrfam][attr] and
return the results
:param attr: attribute name
:param value: raw setting value
:param addrfam: address family (inet, inet6,
'''
valid, _value, errmsg = False, value, 'Unknown validator'
attrmaps = ATTRMAPS.get(addrfam, [])
for attrmap in attrmaps:
if attr in attrmap:
validate_func = attrmap[attr]
(valid, _value, errmsg) = validate_func(value)
break
return (valid, _value, errmsg)
def _attrmaps_contain_attr(attr):
return (
attr in WIRELESS_ATTR_MAP or
attr in IPV4_ATTR_MAP or
attr in IPV6_ATTR_MAP)
def _parse_interfaces(interface_files=None):
'''
Parse /etc/network/interfaces and return current configured interfaces
'''
if interface_files is None:
interface_files = []
# Add this later.
if os.path.exists(_DEB_NETWORK_DIR):
interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]
if os.path.isfile(_DEB_NETWORK_FILE):
interface_files.insert(0, _DEB_NETWORK_FILE)
adapters = salt.utils.odict.OrderedDict()
method = -1
for interface_file in interface_files:
with salt.utils.files.fopen(interface_file) as interfaces:
# This ensures iface_dict exists, but does not ensure we're not reading a new interface.
iface_dict = {}
for line in interfaces:
line = salt.utils.stringutils.to_unicode(line)
# Identify the clauses by the first word of each line.
# Go to the next line if the current line is a comment
# or all spaces.
if line.lstrip().startswith('#') or line.isspace():
continue
# Parse the iface clause
if line.startswith('iface'):
sline = line.split()
if len(sline) != 4:
msg = 'Interface file malformed: {0}.'
msg = msg.format(sline)
log.error(msg)
raise AttributeError(msg)
iface_name = sline[1]
addrfam = sline[2]
method = sline[3]
# Create item in dict, if not already there
if iface_name not in adapters:
adapters[iface_name] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters[iface_name]:
adapters[iface_name]['data'] = salt.utils.odict.OrderedDict()
if addrfam not in adapters[iface_name]['data']:
adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict()
iface_dict = adapters[iface_name]['data'][addrfam]
iface_dict['addrfam'] = addrfam
iface_dict['proto'] = method
iface_dict['filename'] = interface_file
# Parse the detail clauses.
elif line[0].isspace():
sline = line.split()
# conf file attr: dns-nameservers
# salt states.network attr: dns
attr, valuestr = line.rstrip().split(None, 1)
if _attrmaps_contain_attr(attr):
if '-' in attr:
attrname = attr.replace('-', '_')
else:
attrname = attr
(valid, value, errmsg) = _validate_interface_option(
attr, valuestr, addrfam)
if attrname == 'address' and 'address' in iface_dict:
if 'addresses' not in iface_dict:
iface_dict['addresses'] = []
iface_dict['addresses'].append(value)
else:
iface_dict[attrname] = value
elif attr in _REV_ETHTOOL_CONFIG_OPTS:
if 'ethtool' not in iface_dict:
iface_dict['ethtool'] = salt.utils.odict.OrderedDict()
iface_dict['ethtool'][attr] = valuestr
elif attr.startswith('bond'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bonding' not in iface_dict:
iface_dict['bonding'] = salt.utils.odict.OrderedDict()
iface_dict['bonding'][opt] = valuestr
elif attr.startswith('bridge'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bridging' not in iface_dict:
iface_dict['bridging'] = salt.utils.odict.OrderedDict()
iface_dict['bridging'][opt] = valuestr
elif attr in ['up', 'pre-up', 'post-up',
'down', 'pre-down', 'post-down']:
cmd = valuestr
cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr))
if cmd_key not in iface_dict:
iface_dict[cmd_key] = []
iface_dict[cmd_key].append(cmd)
elif line.startswith('auto'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['enabled'] = True
elif line.startswith('allow-hotplug'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['hotplug'] = True
elif line.startswith('source'):
if 'source' not in adapters:
adapters['source'] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters['source']:
adapters['source']['data'] = salt.utils.odict.OrderedDict()
adapters['source']['data']['sources'] = []
adapters['source']['data']['sources'].append(line.split()[1])
# Return a sorted list of the keys for bond, bridge and ethtool options to
# ensure a consistent order
for iface_name in adapters:
if iface_name == 'source':
continue
if 'data' not in adapters[iface_name]:
msg = 'Interface file malformed for interface: {0}.'.format(iface_name)
log.error(msg)
adapters.pop(iface_name)
continue
for opt in ['ethtool', 'bonding', 'bridging']:
for inet in ['inet', 'inet6']:
if inet in adapters[iface_name]['data']:
if opt in adapters[iface_name]['data'][inet]:
opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys())
adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys
return adapters
def _parse_ethtool_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
if 'autoneg' in opts:
if opts['autoneg'] in _CONFIG_TRUE:
config.update({'autoneg': 'on'})
elif opts['autoneg'] in _CONFIG_FALSE:
config.update({'autoneg': 'off'})
else:
_raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE)
if 'duplex' in opts:
valid = ['full', 'half']
if opts['duplex'] in valid:
config.update({'duplex': opts['duplex']})
else:
_raise_error_iface(iface, 'duplex', valid)
if 'speed' in opts:
valid = ['10', '100', '1000', '10000']
if six.text_type(opts['speed']) in valid:
config.update({'speed': opts['speed']})
else:
_raise_error_iface(iface, opts['speed'], valid)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'on'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'off'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_ethtool_pppoe_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
for opt in _DEB_CONFIG_PPPOE_OPTS:
if opt in opts:
config[opt] = opts[opt]
if 'provider' in opts and not opts['provider']:
_raise_error_iface(iface, 'provider', _CONFIG_TRUE + _CONFIG_FALSE)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('noipdefault', 'usepeerdns', 'defaultroute', 'hide-password', 'noauth', 'persist', 'noaccomp'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'True'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'False'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_settings_bond(opts, iface):
'''
Filters given options and outputs valid settings for requested
operation. If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond_def = {
# 803.ad aggregation selection logic
# 0 for stable (default)
# 1 for bandwidth
# 2 for count
'ad_select': '0',
# Max number of transmit queues (default = 16)
'tx_queues': '16',
# Link monitoring in milliseconds. Most NICs support this
'miimon': '100',
# ARP interval in milliseconds
'arp_interval': '250',
# Delay before considering link down in milliseconds (miimon * 2)
'downdelay': '200',
# lacp_rate 0: Slow - every 30 seconds
# lacp_rate 1: Fast - every 1 second
'lacp_rate': '0',
# Max bonds for this driver
'max_bonds': '1',
# Specifies the time, in milliseconds, to wait before
# enabling a slave after a link recovery has been
# detected. Only used with miimon.
'updelay': '0',
# Used with miimon.
# On: driver sends mii
# Off: ethtool sends mii
'use_carrier': 'on',
# Default. Don't change unless you know what you are doing.
'xmit_hash_policy': 'layer2',
}
if opts['mode'] in ['balance-rr', '0']:
log.info('Device: %s Bonding Mode: load balancing (round-robin)', iface)
return _parse_settings_bond_0(opts, iface, bond_def)
elif opts['mode'] in ['active-backup', '1']:
log.info('Device: %s Bonding Mode: fault-tolerance (active-backup)', iface)
return _parse_settings_bond_1(opts, iface, bond_def)
elif opts['mode'] in ['balance-xor', '2']:
log.info('Device: %s Bonding Mode: load balancing (xor)', iface)
return _parse_settings_bond_2(opts, iface, bond_def)
elif opts['mode'] in ['broadcast', '3']:
log.info('Device: %s Bonding Mode: fault-tolerance (broadcast)', iface)
return _parse_settings_bond_3(opts, iface, bond_def)
elif opts['mode'] in ['802.3ad', '4']:
log.info('Device: %s Bonding Mode: IEEE 802.3ad Dynamic link '
'aggregation', iface)
return _parse_settings_bond_4(opts, iface, bond_def)
elif opts['mode'] in ['balance-tlb', '5']:
log.info('Device: %s Bonding Mode: transmit load balancing', iface)
return _parse_settings_bond_5(opts, iface, bond_def)
elif opts['mode'] in ['balance-alb', '6']:
log.info('Device: %s Bonding Mode: adaptive load balancing', iface)
return _parse_settings_bond_6(opts, iface, bond_def)
else:
valid = [
'0', '1', '2', '3', '4', '5', '6',
'balance-rr', 'active-backup', 'balance-xor',
'broadcast', '802.3ad', 'balance-tlb', 'balance-alb'
]
_raise_error_iface(iface, 'mode', valid)
def _parse_settings_bond_0(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond0.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '0'}
# ARP targets in n.n.n.n form
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
return bond
def _parse_settings_bond_1(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '1'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
if not (__grains__['os'] == "Ubuntu" and __grains__['osrelease_info'][0] >= 16):
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_2(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond2.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '2'}
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_3(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond3.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '3'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_4(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond4.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '4'}
for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']:
if binding in opts:
if binding == 'lacp_rate':
if opts[binding] == 'fast':
opts.update({binding: '1'})
if opts[binding] == 'slow':
opts.update({binding: '0'})
valid = ['fast', '1', 'slow', '0']
else:
valid = ['integer']
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, valid)
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_5(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond5.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '5'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_settings_bond_6(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond6.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '6'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_bridge_opts(opts, iface):
'''
Filters given options and outputs valid settings for BRIDGING_OPTS
If an option has a value that is not expected, this
function will log the Interface, Setting and what was expected.
'''
config = {}
if 'ports' in opts:
if isinstance(opts['ports'], list):
opts['ports'] = ' '.join(opts['ports'])
config.update({'ports': opts['ports']})
for opt in ['ageing', 'fd', 'gcint', 'hello', 'maxage']:
if opt in opts:
try:
float(opts[opt])
config.update({opt: opts[opt]})
except ValueError:
_raise_error_iface(iface, opt, ['float'])
for opt in ['bridgeprio', 'maxwait']:
if opt in opts:
if isinstance(opts[opt], int):
config.update({opt: opts[opt]})
else:
_raise_error_iface(iface, opt, ['integer'])
if 'hw' in opts:
# match 12 hex digits with either : or - as separators between pairs
if re.match('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$',
opts['hw'].lower()):
config.update({'hw': opts['hw']})
else:
_raise_error_iface(iface, 'hw', ['valid MAC address'])
for opt in ['pathcost', 'portprio']:
if opt in opts:
try:
port, cost_or_prio = opts[opt].split()
int(cost_or_prio)
config.update({opt: '{0} {1}'.format(port, cost_or_prio)})
except ValueError:
_raise_error_iface(iface, opt, ['interface integer'])
if 'stp' in opts:
if opts['stp'] in _CONFIG_TRUE:
config.update({'stp': 'on'})
elif opts['stp'] in _CONFIG_FALSE:
config.update({'stp': 'off'})
else:
_raise_error_iface(iface, 'stp', _CONFIG_TRUE + _CONFIG_FALSE)
if 'waitport' in opts:
if isinstance(opts['waitport'], int):
config.update({'waitport': opts['waitport']})
else:
values = opts['waitport'].split()
waitport_time = values.pop(0)
if waitport_time.isdigit() and values:
config.update({
'waitport': '{0} {1}'.format(
waitport_time, ' '.join(values)
)
})
else:
_raise_error_iface(iface, opt, ['integer [interfaces]'])
return config
def _parse_settings_eth(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['inet'] = salt.utils.odict.OrderedDict()
iface_data['inet6'] = salt.utils.odict.OrderedDict()
if enabled:
adapters[iface]['enabled'] = True
if opts.get('hotplug', False):
adapters[iface]['hotplug'] = True
if opts.get('enable_ipv6', None) and opts.get('iface_type', '') == 'vlan':
iface_data['inet6']['vlan_raw_device'] = (
re.sub(r'\.\d*', '', iface))
for addrfam in ['inet', 'inet6']:
if iface_type not in ['bridge']:
tmp_ethtool = _parse_ethtool_opts(opts, iface)
if tmp_ethtool:
ethtool = {}
for item in tmp_ethtool:
ethtool[_ETHTOOL_CONFIG_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['ethtool'] = ethtool
# return a list of sorted keys to ensure consistent order
iface_data[addrfam]['ethtool_keys'] = sorted(ethtool)
if iface_type == 'bridge':
bridging = _parse_bridge_opts(opts, iface)
if bridging:
iface_data[addrfam]['bridging'] = bridging
iface_data[addrfam]['bridging_keys'] = sorted(bridging)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'bond':
bonding = _parse_settings_bond(opts, iface)
if bonding:
iface_data[addrfam]['bonding'] = bonding
iface_data[addrfam]['bonding']['slaves'] = opts['slaves']
iface_data[addrfam]['bonding_keys'] = sorted(bonding)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'slave':
adapters[iface]['master'] = opts['master']
opts['proto'] = 'manual'
iface_data[addrfam]['master'] = adapters[iface]['master']
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'vlan':
iface_data[addrfam]['vlan_raw_device'] = re.sub(r'\.\d*', '', iface)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'pppoe':
tmp_ethtool = _parse_ethtool_pppoe_opts(opts, iface)
if tmp_ethtool:
for item in tmp_ethtool:
adapters[iface]['data'][addrfam][_DEB_CONFIG_PPPOE_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['addrfam'] = addrfam
opts.pop('mode', None)
for opt, val in opts.items():
inet = None
if opt.startswith('ipv4'):
opt = opt[4:]
inet = 'inet'
iface_data['inet']['addrfam'] = 'inet'
elif opt.startswith('ipv6'):
iface_data['inet6']['addrfam'] = 'inet6'
opt = opt[4:]
inet = 'inet6'
elif opt in ['ipaddr', 'address', 'ipaddresses', 'addresses', 'gateway', 'proto']:
iface_data['inet']['addrfam'] = 'inet'
inet = 'inet'
_opt = SALT_ATTR_TO_DEBIAN_ATTR_MAP.get(opt, opt)
_debopt = _opt.replace('-', '_')
for addrfam in ['inet', 'inet6']:
(valid, value, errmsg) = _validate_interface_option(_opt, val, addrfam=addrfam)
if not valid:
continue
if inet is None and _debopt not in iface_data[addrfam]:
iface_data[addrfam][_debopt] = value
elif inet == addrfam:
iface_data[addrfam][_debopt] = value
for opt in ['up_cmds', 'pre_up_cmds', 'post_up_cmds',
'down_cmds', 'pre_down_cmds', 'post_down_cmds']:
if opt in opts:
iface_data['inet'][opt] = opts[opt]
iface_data['inet6'][opt] = opts[opt]
# Remove incomplete/disabled inet blocks
for (addrfam, opt) in [('inet', 'enable_ipv4'), ('inet6', 'enable_ipv6')]:
if opts.get(opt, None) is False:
iface_data.pop(addrfam)
elif iface_data[addrfam].get('addrfam', '') != addrfam:
iface_data.pop(addrfam)
return adapters
def _parse_settings_source(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['sources'] = [opts['source']]
return adapters
def _parse_network_settings(opts, current):
'''
Filters given options and outputs valid settings for
the global network settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
current = dict((k.lower(), v) for (k, v) in six.iteritems(current))
result = {}
valid = _CONFIG_TRUE + _CONFIG_FALSE
if 'enabled' not in opts:
try:
opts['networking'] = current['networking']
_log_default_network('networking', current['networking'])
except ValueError:
_raise_error_network('networking', valid)
else:
opts['networking'] = opts['enabled']
if opts['networking'] in valid:
if opts['networking'] in _CONFIG_TRUE:
result['networking'] = 'yes'
elif opts['networking'] in _CONFIG_FALSE:
result['networking'] = 'no'
else:
_raise_error_network('networking', valid)
if 'hostname' not in opts:
try:
opts['hostname'] = current['hostname']
_log_default_network('hostname', current['hostname'])
except ValueError:
_raise_error_network('hostname', ['server1.example.com'])
if opts['hostname']:
result['hostname'] = opts['hostname']
else:
_raise_error_network('hostname', ['server1.example.com'])
if 'search' in opts:
result['search'] = opts['search']
return result
def _parse_routes(iface, opts):
'''
Filters given options and outputs valid settings for
the route settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
result = {}
if 'routes' not in opts:
_raise_error_routes(iface, 'routes', 'List of routes')
for opt in opts:
result[opt] = opts[opt]
return result
def _write_file(iface, data, folder, pattern):
'''
Writes a file to disk
'''
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
return filename
def _write_file_routes(iface, data, folder, pattern):
'''
Writes a file to disk
'''
# ifup / ifdown is executing given folder via run-parts.
# according to run-parts man-page, only filenames with this pattern are
# executed: (^[a-zA-Z0-9_-]+$)
# In order to make the routes file work for vlan interfaces
# (default would have been in example /etc/network/if-up.d/route-bond0.12)
# these dots in the iface name need to be replaced by underscores, so it
# can be executed by run-parts
iface = iface.replace('.', '_')
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
__salt__['file.set_mode'](filename, '0755')
return filename
def _write_file_network(data, filename, create=False):
'''
Writes a file to disk
If file does not exist, only create if create
argument is True
'''
if not os.path.exists(filename) and not create:
msg = '{0} cannot be written. {0} does not exist\
and create is set to False'
msg = msg.format(filename)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
def _read_temp(data):
'''
Return what would be written to disk
'''
tout = StringIO()
tout.write(data)
tout.seek(0)
output = tout.readlines()
tout.close()
return output
def _read_temp_ifaces(iface, data):
'''
Return what would be written to disk for interfaces
'''
try:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': data})
# Return as an array so the difflib works
return [item + '\n' for item in ifcfg.split('\n')]
def _write_file_ifaces(iface, data, **settings):
'''
Writes a file to disk
'''
try:
eth_template = JINJA.get_template('debian_eth.jinja')
source_template = JINJA.get_template('debian_source.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
# Read /etc/network/interfaces into a dict
adapters = _parse_interfaces()
# Apply supplied settings over on-disk settings
adapters[iface] = data
ifcfg = ''
for adapter in adapters:
if 'type' in adapters[adapter] and adapters[adapter]['type'] == 'source':
tmp = source_template.render({'name': adapter, 'data': adapters[adapter]})
else:
tmp = eth_template.render({'name': adapter, 'data': adapters[adapter]})
ifcfg = ifcfg + tmp
if adapter == iface:
saved_ifcfg = tmp
_SEPARATE_FILE = False
if 'filename' in settings:
if not settings['filename'].startswith('/'):
filename = '{0}/{1}'.format(_DEB_NETWORK_DIR, settings['filename'])
else:
filename = settings['filename']
_SEPARATE_FILE = True
else:
if 'filename' in adapters[adapter]['data']:
filename = adapters[adapter]['data']
else:
filename = _DEB_NETWORK_FILE
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
if _SEPARATE_FILE:
fout.write(salt.utils.stringutils.to_str(saved_ifcfg))
else:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return saved_ifcfg.split('\n')
def _write_file_ppp_ifaces(iface, data):
'''
Writes a file to disk
'''
try:
template = JINJA.get_template('debian_ppp_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_ppp_eth.jinja')
return ''
adapters = _parse_interfaces()
adapters[iface] = data
ifcfg = ''
tmp = template.render({'data': adapters[iface]})
ifcfg = tmp + ifcfg
filename = _DEB_PPP_DIR + '/' + adapters[iface]['data']['inet']['provider']
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.fopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return filename
def build_bond(iface, **settings):
'''
Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb
'''
deb_major = __grains__['osrelease'][:1]
opts = _parse_settings_bond(settings, iface)
try:
template = JINJA.get_template('conf.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template conf.jinja')
return ''
data = template.render({'name': iface, 'bonding': opts})
if 'test' in settings and settings['test']:
return _read_temp(data)
_write_file(iface, data, _DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
if deb_major == '5':
for line_type in ('alias', 'options'):
cmd = ['sed', '-i', '-e', r'/^{0}\s{1}.*/d'.format(line_type, iface),
'/etc/modprobe.conf']
__salt__['cmd.run'](cmd, python_shell=False)
__salt__['file.append']('/etc/modprobe.conf', path)
# Load kernel module
__salt__['kmod.load']('bonding')
# install ifenslave-2.6
__salt__['pkg.install']('ifenslave-2.6')
return _read_file(path)
def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'vlan':
settings['vlan'] = 'yes'
__salt__['pkg.install']('vlan')
elif iface_type == 'pppoe':
settings['pppoe'] = 'yes'
if not __salt__['pkg.version']('ppp'):
inst = __salt__['pkg.install']('ppp')
elif iface_type == 'bond':
if 'slaves' not in settings:
msg = 'slaves is a required setting for bond interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'bridge':
if 'ports' not in settings:
msg = (
'ports is a required setting for bridge interfaces on Debian '
'or Ubuntu based systems'
)
log.error(msg)
raise AttributeError(msg)
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'pppoe']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
if iface_type in ['source']:
opts = _parse_settings_source(settings, iface_type, enabled, iface)
if 'test' in settings and settings['test']:
return _read_temp_ifaces(iface, opts[iface])
ifcfg = _write_file_ifaces(iface, opts[iface], **settings)
if iface_type == 'pppoe':
_write_file_ppp_ifaces(iface, opts[iface])
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg]
def build_routes(iface, **settings):
'''
Add route scripts for a network interface using up commands.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
'''
opts = _parse_routes(iface, settings)
try:
template = JINJA.get_template('route_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template route_eth.jinja')
return ''
add_routecfg = template.render(route_type='add',
routes=opts['routes'],
iface=iface)
del_routecfg = template.render(route_type='del',
routes=opts['routes'],
iface=iface)
if 'test' in settings and settings['test']:
return _read_temp(add_routecfg + del_routecfg)
filename = _write_file_routes(iface,
add_routecfg,
_DEB_NETWORK_UP_DIR,
'route-{0}')
results = _read_file(filename)
filename = _write_file_routes(iface,
del_routecfg,
_DEB_NETWORK_DOWN_DIR,
'route-{0}')
results += _read_file(filename)
return results
def down(iface, iface_type):
'''
Shutdown a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.down eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought down.
if iface_type not in ['slave', 'source']:
return __salt__['cmd.run'](['ifdown', iface])
return None
def get_bond(iface):
'''
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
'''
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
return _read_file(path)
def get_interface(iface):
'''
Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
adapters = _parse_interfaces()
if iface in adapters:
try:
if iface == 'source':
template = JINJA.get_template('debian_source.jinja')
else:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': adapters[iface]})
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg.split('\n')]
else:
return []
def up(iface, iface_type): # pylint: disable=C0103
'''
Start up a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.up eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought up.
if iface_type not in ('slave', 'source'):
return __salt__['cmd.run'](['ifup', iface])
return None
def get_network_settings():
'''
Return the contents of the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_network_settings
'''
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
settings = {}
if __salt__['service.available']('networking'):
if __salt__['service.status']('networking'):
settings['networking'] = "yes"
else:
settings['networking'] = "no"
else:
settings['networking'] = "no"
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
settings['hostname'] = hostname
settings['domainname'] = domainname
settings['searchdomain'] = searchdomain
else:
settings = _parse_current_network_settings()
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(settings)
return _read_temp(network)
def get_routes(iface):
'''
Return the routes for the interface
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0
'''
filename = os.path.join(_DEB_NETWORK_UP_DIR, 'route-{0}'.format(iface))
results = _read_file(filename)
filename = os.path.join(_DEB_NETWORK_DOWN_DIR, 'route-{0}'.format(iface))
results += _read_file(filename)
return results
def apply_network_settings(**settings):
'''
Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings
'''
if 'require_reboot' not in settings:
settings['require_reboot'] = False
if 'apply_hostname' not in settings:
settings['apply_hostname'] = False
hostname_res = True
if settings['apply_hostname'] in _CONFIG_TRUE:
if 'hostname' in settings:
hostname_res = __salt__['network.mod_hostname'](settings['hostname'])
else:
log.warning(
'The network state sls is trying to apply hostname '
'changes but no hostname is defined.'
)
hostname_res = False
res = True
if settings['require_reboot'] in _CONFIG_TRUE:
log.warning(
'The network state sls is requiring a reboot of the system to '
'properly apply network configuration.'
)
res = True
else:
stop = __salt__['service.stop']('networking')
time.sleep(2)
res = stop and __salt__['service.start']('networking')
return hostname_res and res
def build_network_settings(**settings):
'''
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
'''
changes = []
# Read current configuration and store default values
current_network_settings = _parse_current_network_settings()
# Build settings
opts = _parse_network_settings(settings, current_network_settings)
# Ubuntu has moved away from /etc/default/networking
# beginning with the 12.04 release so we disable or enable
# the networking related services on boot
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
if opts['networking'] == 'yes':
service_cmd = 'service.enable'
else:
service_cmd = 'service.disable'
if __salt__['service.available']('NetworkManager'):
__salt__[service_cmd]('NetworkManager')
if __salt__['service.available']('networking'):
__salt__[service_cmd]('networking')
else:
try:
template = JINJA.get_template('network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template network.jinja')
return ''
network = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(network)
# Write settings
_write_file_network(network, _DEB_NETWORKING_FILE, True)
# Get hostname and domain from opts
sline = opts['hostname'].split('.', 1)
opts['hostname'] = sline[0]
current_domainname = current_network_settings['domainname']
current_searchdomain = current_network_settings['searchdomain']
new_domain = False
if len(sline) > 1:
new_domainname = sline[1]
if new_domainname != current_domainname:
domainname = new_domainname
opts['domainname'] = new_domainname
new_domain = True
else:
domainname = current_domainname
opts['domainname'] = domainname
else:
domainname = current_domainname
opts['domainname'] = domainname
new_search = False
if 'search' in opts:
new_searchdomain = opts['search']
if new_searchdomain != current_searchdomain:
searchdomain = new_searchdomain
opts['searchdomain'] = new_searchdomain
new_search = True
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
# If the domain changes, then we should write the resolv.conf file.
if new_domain or new_search:
# Look for existing domain line and update if necessary
resolve = _parse_resolve()
domain_prog = re.compile(r'domain\s+')
search_prog = re.compile(r'search\s+')
new_contents = []
for item in _read_file(_DEB_RESOLV_FILE):
if domain_prog.match(item):
item = 'domain {0}'.format(domainname)
elif search_prog.match(item):
item = 'search {0}'.format(searchdomain)
new_contents.append(item)
# A domain line didn't exist so we'll add one in
# with the new domainname
if 'domain' not in resolve:
new_contents.insert(0, 'domain {0}' . format(domainname))
# A search line didn't exist so we'll add one in
# with the new search domain
if 'search' not in resolve:
new_contents.insert('domain' in resolve, 'search {0}'.format(searchdomain))
new_resolv = '\n'.join(new_contents)
# Write /etc/resolv.conf
if not ('test' in settings and settings['test']):
_write_file_network(new_resolv, _DEB_RESOLV_FILE)
# used for returning the results back
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(opts)
changes.extend(_read_temp(network))
return changes
|
saltstack/salt
|
salt/modules/debian_ip.py
|
_error_msg_routes
|
python
|
def _error_msg_routes(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, expected)
|
Build an appropriate error message from a given option and
a list of expected values.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_ip.py#L164-L170
| null |
# -*- coding: utf-8 -*-
'''
The networking module for Debian-based distros
References:
* http://www.debian.org/doc/manuals/debian-reference/ch05.en.html
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import functools
import logging
import os.path
import os
import re
import time
# Import third party libs
import jinja2
import jinja2.exceptions
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error,no-name-in-module
# Import salt libs
import salt.utils.dns
import salt.utils.files
import salt.utils.odict
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.validate.net
# Set up logging
log = logging.getLogger(__name__)
# Set up template environment
JINJA = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'debian_ip')
)
)
# Define the module's virtual name
__virtualname__ = 'ip'
def __virtual__():
'''
Confine this module to Debian-based distros
'''
if __grains__['os_family'] == 'Debian':
return __virtualname__
return (False, 'The debian_ip module could not be loaded: '
'unsupported OS family')
_ETHTOOL_CONFIG_OPTS = {
'speed': 'link-speed',
'duplex': 'link-duplex',
'autoneg': 'ethernet-autoneg',
'ethernet-port': 'ethernet-port',
'wol': 'ethernet-wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'rx': 'offload-rx',
'tx': 'offload-tx',
'sg': 'offload-sg',
'tso': 'offload-tso',
'ufo': 'offload-ufo',
'gso': 'offload-gso',
'gro': 'offload-gro',
'lro': 'offload-lro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_REV_ETHTOOL_CONFIG_OPTS = {
'link-speed': 'speed',
'link-duplex': 'duplex',
'ethernet-autoneg': 'autoneg',
'ethernet-port': 'ethernet-port',
'ethernet-wol': 'wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'offload-rx': 'rx',
'offload-tx': 'tx',
'offload-sg': 'sg',
'offload-tso': 'tso',
'offload-ufo': 'ufo',
'offload-gso': 'gso',
'offload-lro': 'lro',
'offload-gro': 'gro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_DEB_CONFIG_PPPOE_OPTS = {
'user': 'user',
'password': 'password',
'provider': 'provider',
'pppoe_iface': 'pppoe_iface',
'noipdefault': 'noipdefault',
'usepeerdns': 'usepeerdns',
'defaultroute': 'defaultroute',
'holdoff': 'holdoff',
'maxfail': 'maxfail',
'hide-password': 'hide-password',
'lcp-echo-interval': 'lcp-echo-interval',
'lcp-echo-failure': 'lcp-echo-failure',
'connect': 'connect',
'noauth': 'noauth',
'persist': 'persist',
'mtu': 'mtu',
'noaccomp': 'noaccomp',
'linkname': 'linkname',
}
_DEB_ROUTES_FILE = '/etc/network/routes'
_DEB_NETWORK_FILE = '/etc/network/interfaces'
_DEB_NETWORK_DIR = '/etc/network/interfaces.d/'
_DEB_NETWORK_UP_DIR = '/etc/network/if-up.d/'
_DEB_NETWORK_DOWN_DIR = '/etc/network/if-down.d/'
_DEB_NETWORK_CONF_FILES = '/etc/modprobe.d/'
_DEB_NETWORKING_FILE = '/etc/default/networking'
_DEB_HOSTNAME_FILE = '/etc/hostname'
_DEB_RESOLV_FILE = '/etc/resolv.conf'
_DEB_PPP_DIR = '/etc/ppp/peers/'
_CONFIG_TRUE = ['yes', 'on', 'true', '1', True]
_CONFIG_FALSE = ['no', 'off', 'false', '0', False]
_IFACE_TYPES = [
'eth', 'bond', 'alias', 'clone',
'ipsec', 'dialup', 'bridge', 'slave',
'vlan', 'pppoe', 'source',
]
def _error_msg_iface(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, '|'.join(str(e) for e in expected))
def _log_default_iface(iface, opt, value):
log.info(
'Using default option -- Interface: %s Option: %s Value: %s',
iface, opt, value
)
def _error_msg_network(option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]'
return msg.format(option, '|'.join(str(e) for e in expected))
def _log_default_network(opt, value):
log.info('Using existing setting -- Setting: %s Value: %s', opt, value)
def _raise_error_iface(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_iface(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_network(option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_network(option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_routes(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_routes(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _read_file(path):
'''
Reads and returns the contents of a text file
'''
try:
with salt.utils.files.flopen(path, 'rb') as contents:
return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]
except (OSError, IOError):
return ''
def _parse_resolve():
'''
Parse /etc/resolv.conf
'''
return salt.utils.dns.parse_resolv(_DEB_RESOLV_FILE)
def _parse_domainname():
'''
Parse /etc/resolv.conf and return domainname
'''
return _parse_resolve().get('domain', '')
def _parse_searchdomain():
'''
Parse /etc/resolv.conf and return searchdomain
'''
return _parse_resolve().get('search', '')
def _parse_hostname():
'''
Parse /etc/hostname and return hostname
'''
contents = _read_file(_DEB_HOSTNAME_FILE)
if contents:
return contents[0].split('\n')[0]
else:
return ''
def _parse_current_network_settings():
'''
Parse /etc/default/networking and return current configuration
'''
opts = salt.utils.odict.OrderedDict()
opts['networking'] = ''
if os.path.isfile(_DEB_NETWORKING_FILE):
with salt.utils.files.fopen(_DEB_NETWORKING_FILE) as contents:
for line in contents:
salt.utils.stringutils.to_unicode(line)
if line.startswith('#'):
continue
elif line.startswith('CONFIGURE_INTERFACES'):
opts['networking'] = line.split('=', 1)[1].strip()
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
opts['hostname'] = hostname
opts['domainname'] = domainname
opts['searchdomain'] = searchdomain
return opts
# def __validator_func(value):
# return (valid: True/False, (transformed) value, error message)
def __ipv4_quad(value):
'''validate an IPv4 address'''
return (salt.utils.validate.net.ipv4_addr(value), value,
'dotted IPv4 address')
def __ipv6(value):
'''validate an IPv6 address'''
return (salt.utils.validate.net.ipv6_addr(value), value,
'IPv6 address')
def __mac(value):
'''validate a mac address'''
return (salt.utils.validate.net.mac(value), value,
'MAC address')
def __anything(value):
return (True, value, None)
def __int(value):
'''validate an integer'''
valid, _value = False, value
try:
_value = int(value)
valid = True
except ValueError:
pass
return (valid, _value, 'integer')
def __float(value):
'''validate a float'''
valid, _value = False, value
try:
_value = float(value)
valid = True
except ValueError:
pass
return (valid, _value, 'float')
def __ipv4_netmask(value):
'''validate an IPv4 dotted quad or integer CIDR netmask'''
valid, errmsg = False, 'dotted quad or integer CIDR (0->32)'
valid, value, _ = __int(value)
if not (valid and 0 <= value <= 32):
valid = salt.utils.validate.net.netmask(value)
return (valid, value, errmsg)
def __ipv6_netmask(value):
'''validate an IPv6 integer netmask'''
valid, errmsg = False, 'IPv6 netmask (0->128)'
valid, value, _ = __int(value)
valid = (valid and 0 <= value <= 128)
return (valid, value, errmsg)
def __within2(value, within=None, errmsg=None, dtype=None):
'''validate that a value is in ``within`` and optionally a ``dtype``'''
valid, _value = False, value
if dtype:
try:
_value = dtype(value) # TODO: this is a bit loose when dtype is a class
valid = _value in within
except ValueError:
pass
else:
valid = _value in within
if errmsg is None:
if dtype:
typename = getattr(dtype, '__name__',
hasattr(dtype, '__class__')
and getattr(dtype.__class__, 'name', dtype))
errmsg = '{0} within \'{1}\''.format(typename, within)
else:
errmsg = 'within \'{0}\''.format(within)
return (valid, _value, errmsg)
def __within(within=None, errmsg=None, dtype=None):
return functools.partial(__within2, within=within,
errmsg=errmsg, dtype=dtype)
def __space_delimited_list(value):
'''validate that a value contains one or more space-delimited values'''
if isinstance(value, six.string_types):
value = value.strip().split()
if hasattr(value, '__iter__') and value != []:
return (True, value, 'space-delimited string')
else:
return (False, value, '{0} is not a valid space-delimited value.\n'.format(value))
SALT_ATTR_TO_DEBIAN_ATTR_MAP = {
'dns': 'dns-nameservers',
'search': 'dns-search',
'hwaddr': 'hwaddress', # TODO: this limits bootp functionality
'ipaddr': 'address',
'ipaddrs': 'addresses',
}
DEBIAN_ATTR_TO_SALT_ATTR_MAP = dict(
(v, k) for (k, v) in six.iteritems(SALT_ATTR_TO_DEBIAN_ATTR_MAP))
# TODO
DEBIAN_ATTR_TO_SALT_ATTR_MAP['address'] = 'address'
DEBIAN_ATTR_TO_SALT_ATTR_MAP['hwaddress'] = 'hwaddress'
IPV4_VALID_PROTO = ['bootp', 'dhcp', 'static', 'manual', 'loopback', 'ppp']
IPV4_ATTR_MAP = {
'proto': __within(IPV4_VALID_PROTO, dtype=six.text_type),
# ipv4 static & manual
'address': __ipv4_quad,
'addresses': __anything,
'netmask': __ipv4_netmask,
'broadcast': __ipv4_quad,
'metric': __int,
'gateway': __ipv4_quad, # supports a colon-delimited list
'pointopoint': __ipv4_quad,
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'link', 'host'], dtype=six.text_type),
# dhcp
'hostname': __anything,
'leasehours': __int,
'leasetime': __int,
'vendor': __anything,
'client': __anything,
# bootp
'bootfile': __anything,
'server': __ipv4_quad,
'hwaddr': __mac,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'dstaddr': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# bond
'slaves': __anything,
# ppp
'provider': __anything,
'unit': __int,
'options': __anything,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
#
'network': __anything, # i don't know what this is
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
IPV6_VALID_PROTO = ['auto', 'loopback', 'static', 'manual',
'dhcp', 'v4tunnel', '6to4']
IPV6_ATTR_MAP = {
'proto': __within(IPV6_VALID_PROTO),
# ipv6 static & manual
'address': __ipv6,
'addresses': __anything,
'netmask': __ipv6_netmask,
'broadcast': __ipv6,
'gateway': __ipv6, # supports a colon-delimited list
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'site', 'link', 'host'], dtype=six.text_type),
# inet6 auto
'privext': __within([0, 1, 2], dtype=int),
'dhcp': __within([0, 1], dtype=int),
# inet6 static & manual & dhcp
'media': __anything,
'accept_ra': __within([0, 1], dtype=int),
'autoconf': __within([0, 1], dtype=int),
'preferred-lifetime': __int,
'dad-attempts': __int, # 0 to disable
'dad-interval': __float,
# bond
'slaves': __anything,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
WIRELESS_ATTR_MAP = {
'wireless-essid': __anything,
'wireless-mode': __anything, # TODO
'wpa-ap-scan': __within([0, 1, 2], dtype=int), # TODO
'wpa-conf': __anything,
'wpa-driver': __anything,
'wpa-group': __anything,
'wpa-key-mgmt': __anything,
'wpa-pairwise': __anything,
'wpa-psk': __anything,
'wpa-proto': __anything, # partial(__within,
'wpa-roam': __anything,
'wpa-ssid': __anything, # TODO
}
ATTRMAPS = {
'inet': [IPV4_ATTR_MAP, WIRELESS_ATTR_MAP],
'inet6': [IPV6_ATTR_MAP, WIRELESS_ATTR_MAP]
}
def _validate_interface_option(attr, value, addrfam='inet'):
'''lookup the validation function for a [addrfam][attr] and
return the results
:param attr: attribute name
:param value: raw setting value
:param addrfam: address family (inet, inet6,
'''
valid, _value, errmsg = False, value, 'Unknown validator'
attrmaps = ATTRMAPS.get(addrfam, [])
for attrmap in attrmaps:
if attr in attrmap:
validate_func = attrmap[attr]
(valid, _value, errmsg) = validate_func(value)
break
return (valid, _value, errmsg)
def _attrmaps_contain_attr(attr):
return (
attr in WIRELESS_ATTR_MAP or
attr in IPV4_ATTR_MAP or
attr in IPV6_ATTR_MAP)
def _parse_interfaces(interface_files=None):
'''
Parse /etc/network/interfaces and return current configured interfaces
'''
if interface_files is None:
interface_files = []
# Add this later.
if os.path.exists(_DEB_NETWORK_DIR):
interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]
if os.path.isfile(_DEB_NETWORK_FILE):
interface_files.insert(0, _DEB_NETWORK_FILE)
adapters = salt.utils.odict.OrderedDict()
method = -1
for interface_file in interface_files:
with salt.utils.files.fopen(interface_file) as interfaces:
# This ensures iface_dict exists, but does not ensure we're not reading a new interface.
iface_dict = {}
for line in interfaces:
line = salt.utils.stringutils.to_unicode(line)
# Identify the clauses by the first word of each line.
# Go to the next line if the current line is a comment
# or all spaces.
if line.lstrip().startswith('#') or line.isspace():
continue
# Parse the iface clause
if line.startswith('iface'):
sline = line.split()
if len(sline) != 4:
msg = 'Interface file malformed: {0}.'
msg = msg.format(sline)
log.error(msg)
raise AttributeError(msg)
iface_name = sline[1]
addrfam = sline[2]
method = sline[3]
# Create item in dict, if not already there
if iface_name not in adapters:
adapters[iface_name] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters[iface_name]:
adapters[iface_name]['data'] = salt.utils.odict.OrderedDict()
if addrfam not in adapters[iface_name]['data']:
adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict()
iface_dict = adapters[iface_name]['data'][addrfam]
iface_dict['addrfam'] = addrfam
iface_dict['proto'] = method
iface_dict['filename'] = interface_file
# Parse the detail clauses.
elif line[0].isspace():
sline = line.split()
# conf file attr: dns-nameservers
# salt states.network attr: dns
attr, valuestr = line.rstrip().split(None, 1)
if _attrmaps_contain_attr(attr):
if '-' in attr:
attrname = attr.replace('-', '_')
else:
attrname = attr
(valid, value, errmsg) = _validate_interface_option(
attr, valuestr, addrfam)
if attrname == 'address' and 'address' in iface_dict:
if 'addresses' not in iface_dict:
iface_dict['addresses'] = []
iface_dict['addresses'].append(value)
else:
iface_dict[attrname] = value
elif attr in _REV_ETHTOOL_CONFIG_OPTS:
if 'ethtool' not in iface_dict:
iface_dict['ethtool'] = salt.utils.odict.OrderedDict()
iface_dict['ethtool'][attr] = valuestr
elif attr.startswith('bond'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bonding' not in iface_dict:
iface_dict['bonding'] = salt.utils.odict.OrderedDict()
iface_dict['bonding'][opt] = valuestr
elif attr.startswith('bridge'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bridging' not in iface_dict:
iface_dict['bridging'] = salt.utils.odict.OrderedDict()
iface_dict['bridging'][opt] = valuestr
elif attr in ['up', 'pre-up', 'post-up',
'down', 'pre-down', 'post-down']:
cmd = valuestr
cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr))
if cmd_key not in iface_dict:
iface_dict[cmd_key] = []
iface_dict[cmd_key].append(cmd)
elif line.startswith('auto'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['enabled'] = True
elif line.startswith('allow-hotplug'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['hotplug'] = True
elif line.startswith('source'):
if 'source' not in adapters:
adapters['source'] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters['source']:
adapters['source']['data'] = salt.utils.odict.OrderedDict()
adapters['source']['data']['sources'] = []
adapters['source']['data']['sources'].append(line.split()[1])
# Return a sorted list of the keys for bond, bridge and ethtool options to
# ensure a consistent order
for iface_name in adapters:
if iface_name == 'source':
continue
if 'data' not in adapters[iface_name]:
msg = 'Interface file malformed for interface: {0}.'.format(iface_name)
log.error(msg)
adapters.pop(iface_name)
continue
for opt in ['ethtool', 'bonding', 'bridging']:
for inet in ['inet', 'inet6']:
if inet in adapters[iface_name]['data']:
if opt in adapters[iface_name]['data'][inet]:
opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys())
adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys
return adapters
def _parse_ethtool_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
if 'autoneg' in opts:
if opts['autoneg'] in _CONFIG_TRUE:
config.update({'autoneg': 'on'})
elif opts['autoneg'] in _CONFIG_FALSE:
config.update({'autoneg': 'off'})
else:
_raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE)
if 'duplex' in opts:
valid = ['full', 'half']
if opts['duplex'] in valid:
config.update({'duplex': opts['duplex']})
else:
_raise_error_iface(iface, 'duplex', valid)
if 'speed' in opts:
valid = ['10', '100', '1000', '10000']
if six.text_type(opts['speed']) in valid:
config.update({'speed': opts['speed']})
else:
_raise_error_iface(iface, opts['speed'], valid)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'on'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'off'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_ethtool_pppoe_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
for opt in _DEB_CONFIG_PPPOE_OPTS:
if opt in opts:
config[opt] = opts[opt]
if 'provider' in opts and not opts['provider']:
_raise_error_iface(iface, 'provider', _CONFIG_TRUE + _CONFIG_FALSE)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('noipdefault', 'usepeerdns', 'defaultroute', 'hide-password', 'noauth', 'persist', 'noaccomp'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'True'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'False'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_settings_bond(opts, iface):
'''
Filters given options and outputs valid settings for requested
operation. If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond_def = {
# 803.ad aggregation selection logic
# 0 for stable (default)
# 1 for bandwidth
# 2 for count
'ad_select': '0',
# Max number of transmit queues (default = 16)
'tx_queues': '16',
# Link monitoring in milliseconds. Most NICs support this
'miimon': '100',
# ARP interval in milliseconds
'arp_interval': '250',
# Delay before considering link down in milliseconds (miimon * 2)
'downdelay': '200',
# lacp_rate 0: Slow - every 30 seconds
# lacp_rate 1: Fast - every 1 second
'lacp_rate': '0',
# Max bonds for this driver
'max_bonds': '1',
# Specifies the time, in milliseconds, to wait before
# enabling a slave after a link recovery has been
# detected. Only used with miimon.
'updelay': '0',
# Used with miimon.
# On: driver sends mii
# Off: ethtool sends mii
'use_carrier': 'on',
# Default. Don't change unless you know what you are doing.
'xmit_hash_policy': 'layer2',
}
if opts['mode'] in ['balance-rr', '0']:
log.info('Device: %s Bonding Mode: load balancing (round-robin)', iface)
return _parse_settings_bond_0(opts, iface, bond_def)
elif opts['mode'] in ['active-backup', '1']:
log.info('Device: %s Bonding Mode: fault-tolerance (active-backup)', iface)
return _parse_settings_bond_1(opts, iface, bond_def)
elif opts['mode'] in ['balance-xor', '2']:
log.info('Device: %s Bonding Mode: load balancing (xor)', iface)
return _parse_settings_bond_2(opts, iface, bond_def)
elif opts['mode'] in ['broadcast', '3']:
log.info('Device: %s Bonding Mode: fault-tolerance (broadcast)', iface)
return _parse_settings_bond_3(opts, iface, bond_def)
elif opts['mode'] in ['802.3ad', '4']:
log.info('Device: %s Bonding Mode: IEEE 802.3ad Dynamic link '
'aggregation', iface)
return _parse_settings_bond_4(opts, iface, bond_def)
elif opts['mode'] in ['balance-tlb', '5']:
log.info('Device: %s Bonding Mode: transmit load balancing', iface)
return _parse_settings_bond_5(opts, iface, bond_def)
elif opts['mode'] in ['balance-alb', '6']:
log.info('Device: %s Bonding Mode: adaptive load balancing', iface)
return _parse_settings_bond_6(opts, iface, bond_def)
else:
valid = [
'0', '1', '2', '3', '4', '5', '6',
'balance-rr', 'active-backup', 'balance-xor',
'broadcast', '802.3ad', 'balance-tlb', 'balance-alb'
]
_raise_error_iface(iface, 'mode', valid)
def _parse_settings_bond_0(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond0.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '0'}
# ARP targets in n.n.n.n form
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
return bond
def _parse_settings_bond_1(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '1'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
if not (__grains__['os'] == "Ubuntu" and __grains__['osrelease_info'][0] >= 16):
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_2(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond2.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '2'}
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_3(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond3.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '3'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_4(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond4.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '4'}
for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']:
if binding in opts:
if binding == 'lacp_rate':
if opts[binding] == 'fast':
opts.update({binding: '1'})
if opts[binding] == 'slow':
opts.update({binding: '0'})
valid = ['fast', '1', 'slow', '0']
else:
valid = ['integer']
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, valid)
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_5(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond5.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '5'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_settings_bond_6(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond6.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '6'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_bridge_opts(opts, iface):
'''
Filters given options and outputs valid settings for BRIDGING_OPTS
If an option has a value that is not expected, this
function will log the Interface, Setting and what was expected.
'''
config = {}
if 'ports' in opts:
if isinstance(opts['ports'], list):
opts['ports'] = ' '.join(opts['ports'])
config.update({'ports': opts['ports']})
for opt in ['ageing', 'fd', 'gcint', 'hello', 'maxage']:
if opt in opts:
try:
float(opts[opt])
config.update({opt: opts[opt]})
except ValueError:
_raise_error_iface(iface, opt, ['float'])
for opt in ['bridgeprio', 'maxwait']:
if opt in opts:
if isinstance(opts[opt], int):
config.update({opt: opts[opt]})
else:
_raise_error_iface(iface, opt, ['integer'])
if 'hw' in opts:
# match 12 hex digits with either : or - as separators between pairs
if re.match('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$',
opts['hw'].lower()):
config.update({'hw': opts['hw']})
else:
_raise_error_iface(iface, 'hw', ['valid MAC address'])
for opt in ['pathcost', 'portprio']:
if opt in opts:
try:
port, cost_or_prio = opts[opt].split()
int(cost_or_prio)
config.update({opt: '{0} {1}'.format(port, cost_or_prio)})
except ValueError:
_raise_error_iface(iface, opt, ['interface integer'])
if 'stp' in opts:
if opts['stp'] in _CONFIG_TRUE:
config.update({'stp': 'on'})
elif opts['stp'] in _CONFIG_FALSE:
config.update({'stp': 'off'})
else:
_raise_error_iface(iface, 'stp', _CONFIG_TRUE + _CONFIG_FALSE)
if 'waitport' in opts:
if isinstance(opts['waitport'], int):
config.update({'waitport': opts['waitport']})
else:
values = opts['waitport'].split()
waitport_time = values.pop(0)
if waitport_time.isdigit() and values:
config.update({
'waitport': '{0} {1}'.format(
waitport_time, ' '.join(values)
)
})
else:
_raise_error_iface(iface, opt, ['integer [interfaces]'])
return config
def _parse_settings_eth(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['inet'] = salt.utils.odict.OrderedDict()
iface_data['inet6'] = salt.utils.odict.OrderedDict()
if enabled:
adapters[iface]['enabled'] = True
if opts.get('hotplug', False):
adapters[iface]['hotplug'] = True
if opts.get('enable_ipv6', None) and opts.get('iface_type', '') == 'vlan':
iface_data['inet6']['vlan_raw_device'] = (
re.sub(r'\.\d*', '', iface))
for addrfam in ['inet', 'inet6']:
if iface_type not in ['bridge']:
tmp_ethtool = _parse_ethtool_opts(opts, iface)
if tmp_ethtool:
ethtool = {}
for item in tmp_ethtool:
ethtool[_ETHTOOL_CONFIG_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['ethtool'] = ethtool
# return a list of sorted keys to ensure consistent order
iface_data[addrfam]['ethtool_keys'] = sorted(ethtool)
if iface_type == 'bridge':
bridging = _parse_bridge_opts(opts, iface)
if bridging:
iface_data[addrfam]['bridging'] = bridging
iface_data[addrfam]['bridging_keys'] = sorted(bridging)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'bond':
bonding = _parse_settings_bond(opts, iface)
if bonding:
iface_data[addrfam]['bonding'] = bonding
iface_data[addrfam]['bonding']['slaves'] = opts['slaves']
iface_data[addrfam]['bonding_keys'] = sorted(bonding)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'slave':
adapters[iface]['master'] = opts['master']
opts['proto'] = 'manual'
iface_data[addrfam]['master'] = adapters[iface]['master']
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'vlan':
iface_data[addrfam]['vlan_raw_device'] = re.sub(r'\.\d*', '', iface)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'pppoe':
tmp_ethtool = _parse_ethtool_pppoe_opts(opts, iface)
if tmp_ethtool:
for item in tmp_ethtool:
adapters[iface]['data'][addrfam][_DEB_CONFIG_PPPOE_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['addrfam'] = addrfam
opts.pop('mode', None)
for opt, val in opts.items():
inet = None
if opt.startswith('ipv4'):
opt = opt[4:]
inet = 'inet'
iface_data['inet']['addrfam'] = 'inet'
elif opt.startswith('ipv6'):
iface_data['inet6']['addrfam'] = 'inet6'
opt = opt[4:]
inet = 'inet6'
elif opt in ['ipaddr', 'address', 'ipaddresses', 'addresses', 'gateway', 'proto']:
iface_data['inet']['addrfam'] = 'inet'
inet = 'inet'
_opt = SALT_ATTR_TO_DEBIAN_ATTR_MAP.get(opt, opt)
_debopt = _opt.replace('-', '_')
for addrfam in ['inet', 'inet6']:
(valid, value, errmsg) = _validate_interface_option(_opt, val, addrfam=addrfam)
if not valid:
continue
if inet is None and _debopt not in iface_data[addrfam]:
iface_data[addrfam][_debopt] = value
elif inet == addrfam:
iface_data[addrfam][_debopt] = value
for opt in ['up_cmds', 'pre_up_cmds', 'post_up_cmds',
'down_cmds', 'pre_down_cmds', 'post_down_cmds']:
if opt in opts:
iface_data['inet'][opt] = opts[opt]
iface_data['inet6'][opt] = opts[opt]
# Remove incomplete/disabled inet blocks
for (addrfam, opt) in [('inet', 'enable_ipv4'), ('inet6', 'enable_ipv6')]:
if opts.get(opt, None) is False:
iface_data.pop(addrfam)
elif iface_data[addrfam].get('addrfam', '') != addrfam:
iface_data.pop(addrfam)
return adapters
def _parse_settings_source(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['sources'] = [opts['source']]
return adapters
def _parse_network_settings(opts, current):
'''
Filters given options and outputs valid settings for
the global network settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
current = dict((k.lower(), v) for (k, v) in six.iteritems(current))
result = {}
valid = _CONFIG_TRUE + _CONFIG_FALSE
if 'enabled' not in opts:
try:
opts['networking'] = current['networking']
_log_default_network('networking', current['networking'])
except ValueError:
_raise_error_network('networking', valid)
else:
opts['networking'] = opts['enabled']
if opts['networking'] in valid:
if opts['networking'] in _CONFIG_TRUE:
result['networking'] = 'yes'
elif opts['networking'] in _CONFIG_FALSE:
result['networking'] = 'no'
else:
_raise_error_network('networking', valid)
if 'hostname' not in opts:
try:
opts['hostname'] = current['hostname']
_log_default_network('hostname', current['hostname'])
except ValueError:
_raise_error_network('hostname', ['server1.example.com'])
if opts['hostname']:
result['hostname'] = opts['hostname']
else:
_raise_error_network('hostname', ['server1.example.com'])
if 'search' in opts:
result['search'] = opts['search']
return result
def _parse_routes(iface, opts):
'''
Filters given options and outputs valid settings for
the route settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
result = {}
if 'routes' not in opts:
_raise_error_routes(iface, 'routes', 'List of routes')
for opt in opts:
result[opt] = opts[opt]
return result
def _write_file(iface, data, folder, pattern):
'''
Writes a file to disk
'''
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
return filename
def _write_file_routes(iface, data, folder, pattern):
'''
Writes a file to disk
'''
# ifup / ifdown is executing given folder via run-parts.
# according to run-parts man-page, only filenames with this pattern are
# executed: (^[a-zA-Z0-9_-]+$)
# In order to make the routes file work for vlan interfaces
# (default would have been in example /etc/network/if-up.d/route-bond0.12)
# these dots in the iface name need to be replaced by underscores, so it
# can be executed by run-parts
iface = iface.replace('.', '_')
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
__salt__['file.set_mode'](filename, '0755')
return filename
def _write_file_network(data, filename, create=False):
'''
Writes a file to disk
If file does not exist, only create if create
argument is True
'''
if not os.path.exists(filename) and not create:
msg = '{0} cannot be written. {0} does not exist\
and create is set to False'
msg = msg.format(filename)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
def _read_temp(data):
'''
Return what would be written to disk
'''
tout = StringIO()
tout.write(data)
tout.seek(0)
output = tout.readlines()
tout.close()
return output
def _read_temp_ifaces(iface, data):
'''
Return what would be written to disk for interfaces
'''
try:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': data})
# Return as an array so the difflib works
return [item + '\n' for item in ifcfg.split('\n')]
def _write_file_ifaces(iface, data, **settings):
'''
Writes a file to disk
'''
try:
eth_template = JINJA.get_template('debian_eth.jinja')
source_template = JINJA.get_template('debian_source.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
# Read /etc/network/interfaces into a dict
adapters = _parse_interfaces()
# Apply supplied settings over on-disk settings
adapters[iface] = data
ifcfg = ''
for adapter in adapters:
if 'type' in adapters[adapter] and adapters[adapter]['type'] == 'source':
tmp = source_template.render({'name': adapter, 'data': adapters[adapter]})
else:
tmp = eth_template.render({'name': adapter, 'data': adapters[adapter]})
ifcfg = ifcfg + tmp
if adapter == iface:
saved_ifcfg = tmp
_SEPARATE_FILE = False
if 'filename' in settings:
if not settings['filename'].startswith('/'):
filename = '{0}/{1}'.format(_DEB_NETWORK_DIR, settings['filename'])
else:
filename = settings['filename']
_SEPARATE_FILE = True
else:
if 'filename' in adapters[adapter]['data']:
filename = adapters[adapter]['data']
else:
filename = _DEB_NETWORK_FILE
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
if _SEPARATE_FILE:
fout.write(salt.utils.stringutils.to_str(saved_ifcfg))
else:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return saved_ifcfg.split('\n')
def _write_file_ppp_ifaces(iface, data):
'''
Writes a file to disk
'''
try:
template = JINJA.get_template('debian_ppp_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_ppp_eth.jinja')
return ''
adapters = _parse_interfaces()
adapters[iface] = data
ifcfg = ''
tmp = template.render({'data': adapters[iface]})
ifcfg = tmp + ifcfg
filename = _DEB_PPP_DIR + '/' + adapters[iface]['data']['inet']['provider']
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.fopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return filename
def build_bond(iface, **settings):
'''
Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb
'''
deb_major = __grains__['osrelease'][:1]
opts = _parse_settings_bond(settings, iface)
try:
template = JINJA.get_template('conf.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template conf.jinja')
return ''
data = template.render({'name': iface, 'bonding': opts})
if 'test' in settings and settings['test']:
return _read_temp(data)
_write_file(iface, data, _DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
if deb_major == '5':
for line_type in ('alias', 'options'):
cmd = ['sed', '-i', '-e', r'/^{0}\s{1}.*/d'.format(line_type, iface),
'/etc/modprobe.conf']
__salt__['cmd.run'](cmd, python_shell=False)
__salt__['file.append']('/etc/modprobe.conf', path)
# Load kernel module
__salt__['kmod.load']('bonding')
# install ifenslave-2.6
__salt__['pkg.install']('ifenslave-2.6')
return _read_file(path)
def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'vlan':
settings['vlan'] = 'yes'
__salt__['pkg.install']('vlan')
elif iface_type == 'pppoe':
settings['pppoe'] = 'yes'
if not __salt__['pkg.version']('ppp'):
inst = __salt__['pkg.install']('ppp')
elif iface_type == 'bond':
if 'slaves' not in settings:
msg = 'slaves is a required setting for bond interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'bridge':
if 'ports' not in settings:
msg = (
'ports is a required setting for bridge interfaces on Debian '
'or Ubuntu based systems'
)
log.error(msg)
raise AttributeError(msg)
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'pppoe']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
if iface_type in ['source']:
opts = _parse_settings_source(settings, iface_type, enabled, iface)
if 'test' in settings and settings['test']:
return _read_temp_ifaces(iface, opts[iface])
ifcfg = _write_file_ifaces(iface, opts[iface], **settings)
if iface_type == 'pppoe':
_write_file_ppp_ifaces(iface, opts[iface])
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg]
def build_routes(iface, **settings):
'''
Add route scripts for a network interface using up commands.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
'''
opts = _parse_routes(iface, settings)
try:
template = JINJA.get_template('route_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template route_eth.jinja')
return ''
add_routecfg = template.render(route_type='add',
routes=opts['routes'],
iface=iface)
del_routecfg = template.render(route_type='del',
routes=opts['routes'],
iface=iface)
if 'test' in settings and settings['test']:
return _read_temp(add_routecfg + del_routecfg)
filename = _write_file_routes(iface,
add_routecfg,
_DEB_NETWORK_UP_DIR,
'route-{0}')
results = _read_file(filename)
filename = _write_file_routes(iface,
del_routecfg,
_DEB_NETWORK_DOWN_DIR,
'route-{0}')
results += _read_file(filename)
return results
def down(iface, iface_type):
'''
Shutdown a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.down eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought down.
if iface_type not in ['slave', 'source']:
return __salt__['cmd.run'](['ifdown', iface])
return None
def get_bond(iface):
'''
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
'''
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
return _read_file(path)
def get_interface(iface):
'''
Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
adapters = _parse_interfaces()
if iface in adapters:
try:
if iface == 'source':
template = JINJA.get_template('debian_source.jinja')
else:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': adapters[iface]})
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg.split('\n')]
else:
return []
def up(iface, iface_type): # pylint: disable=C0103
'''
Start up a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.up eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought up.
if iface_type not in ('slave', 'source'):
return __salt__['cmd.run'](['ifup', iface])
return None
def get_network_settings():
'''
Return the contents of the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_network_settings
'''
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
settings = {}
if __salt__['service.available']('networking'):
if __salt__['service.status']('networking'):
settings['networking'] = "yes"
else:
settings['networking'] = "no"
else:
settings['networking'] = "no"
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
settings['hostname'] = hostname
settings['domainname'] = domainname
settings['searchdomain'] = searchdomain
else:
settings = _parse_current_network_settings()
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(settings)
return _read_temp(network)
def get_routes(iface):
'''
Return the routes for the interface
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0
'''
filename = os.path.join(_DEB_NETWORK_UP_DIR, 'route-{0}'.format(iface))
results = _read_file(filename)
filename = os.path.join(_DEB_NETWORK_DOWN_DIR, 'route-{0}'.format(iface))
results += _read_file(filename)
return results
def apply_network_settings(**settings):
'''
Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings
'''
if 'require_reboot' not in settings:
settings['require_reboot'] = False
if 'apply_hostname' not in settings:
settings['apply_hostname'] = False
hostname_res = True
if settings['apply_hostname'] in _CONFIG_TRUE:
if 'hostname' in settings:
hostname_res = __salt__['network.mod_hostname'](settings['hostname'])
else:
log.warning(
'The network state sls is trying to apply hostname '
'changes but no hostname is defined.'
)
hostname_res = False
res = True
if settings['require_reboot'] in _CONFIG_TRUE:
log.warning(
'The network state sls is requiring a reboot of the system to '
'properly apply network configuration.'
)
res = True
else:
stop = __salt__['service.stop']('networking')
time.sleep(2)
res = stop and __salt__['service.start']('networking')
return hostname_res and res
def build_network_settings(**settings):
'''
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
'''
changes = []
# Read current configuration and store default values
current_network_settings = _parse_current_network_settings()
# Build settings
opts = _parse_network_settings(settings, current_network_settings)
# Ubuntu has moved away from /etc/default/networking
# beginning with the 12.04 release so we disable or enable
# the networking related services on boot
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
if opts['networking'] == 'yes':
service_cmd = 'service.enable'
else:
service_cmd = 'service.disable'
if __salt__['service.available']('NetworkManager'):
__salt__[service_cmd]('NetworkManager')
if __salt__['service.available']('networking'):
__salt__[service_cmd]('networking')
else:
try:
template = JINJA.get_template('network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template network.jinja')
return ''
network = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(network)
# Write settings
_write_file_network(network, _DEB_NETWORKING_FILE, True)
# Get hostname and domain from opts
sline = opts['hostname'].split('.', 1)
opts['hostname'] = sline[0]
current_domainname = current_network_settings['domainname']
current_searchdomain = current_network_settings['searchdomain']
new_domain = False
if len(sline) > 1:
new_domainname = sline[1]
if new_domainname != current_domainname:
domainname = new_domainname
opts['domainname'] = new_domainname
new_domain = True
else:
domainname = current_domainname
opts['domainname'] = domainname
else:
domainname = current_domainname
opts['domainname'] = domainname
new_search = False
if 'search' in opts:
new_searchdomain = opts['search']
if new_searchdomain != current_searchdomain:
searchdomain = new_searchdomain
opts['searchdomain'] = new_searchdomain
new_search = True
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
# If the domain changes, then we should write the resolv.conf file.
if new_domain or new_search:
# Look for existing domain line and update if necessary
resolve = _parse_resolve()
domain_prog = re.compile(r'domain\s+')
search_prog = re.compile(r'search\s+')
new_contents = []
for item in _read_file(_DEB_RESOLV_FILE):
if domain_prog.match(item):
item = 'domain {0}'.format(domainname)
elif search_prog.match(item):
item = 'search {0}'.format(searchdomain)
new_contents.append(item)
# A domain line didn't exist so we'll add one in
# with the new domainname
if 'domain' not in resolve:
new_contents.insert(0, 'domain {0}' . format(domainname))
# A search line didn't exist so we'll add one in
# with the new search domain
if 'search' not in resolve:
new_contents.insert('domain' in resolve, 'search {0}'.format(searchdomain))
new_resolv = '\n'.join(new_contents)
# Write /etc/resolv.conf
if not ('test' in settings and settings['test']):
_write_file_network(new_resolv, _DEB_RESOLV_FILE)
# used for returning the results back
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(opts)
changes.extend(_read_temp(network))
return changes
|
saltstack/salt
|
salt/modules/debian_ip.py
|
_error_msg_network
|
python
|
def _error_msg_network(option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]'
return msg.format(option, '|'.join(str(e) for e in expected))
|
Build an appropriate error message from a given option and
a list of expected values.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_ip.py#L180-L186
| null |
# -*- coding: utf-8 -*-
'''
The networking module for Debian-based distros
References:
* http://www.debian.org/doc/manuals/debian-reference/ch05.en.html
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import functools
import logging
import os.path
import os
import re
import time
# Import third party libs
import jinja2
import jinja2.exceptions
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error,no-name-in-module
# Import salt libs
import salt.utils.dns
import salt.utils.files
import salt.utils.odict
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.validate.net
# Set up logging
log = logging.getLogger(__name__)
# Set up template environment
JINJA = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'debian_ip')
)
)
# Define the module's virtual name
__virtualname__ = 'ip'
def __virtual__():
'''
Confine this module to Debian-based distros
'''
if __grains__['os_family'] == 'Debian':
return __virtualname__
return (False, 'The debian_ip module could not be loaded: '
'unsupported OS family')
_ETHTOOL_CONFIG_OPTS = {
'speed': 'link-speed',
'duplex': 'link-duplex',
'autoneg': 'ethernet-autoneg',
'ethernet-port': 'ethernet-port',
'wol': 'ethernet-wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'rx': 'offload-rx',
'tx': 'offload-tx',
'sg': 'offload-sg',
'tso': 'offload-tso',
'ufo': 'offload-ufo',
'gso': 'offload-gso',
'gro': 'offload-gro',
'lro': 'offload-lro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_REV_ETHTOOL_CONFIG_OPTS = {
'link-speed': 'speed',
'link-duplex': 'duplex',
'ethernet-autoneg': 'autoneg',
'ethernet-port': 'ethernet-port',
'ethernet-wol': 'wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'offload-rx': 'rx',
'offload-tx': 'tx',
'offload-sg': 'sg',
'offload-tso': 'tso',
'offload-ufo': 'ufo',
'offload-gso': 'gso',
'offload-lro': 'lro',
'offload-gro': 'gro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_DEB_CONFIG_PPPOE_OPTS = {
'user': 'user',
'password': 'password',
'provider': 'provider',
'pppoe_iface': 'pppoe_iface',
'noipdefault': 'noipdefault',
'usepeerdns': 'usepeerdns',
'defaultroute': 'defaultroute',
'holdoff': 'holdoff',
'maxfail': 'maxfail',
'hide-password': 'hide-password',
'lcp-echo-interval': 'lcp-echo-interval',
'lcp-echo-failure': 'lcp-echo-failure',
'connect': 'connect',
'noauth': 'noauth',
'persist': 'persist',
'mtu': 'mtu',
'noaccomp': 'noaccomp',
'linkname': 'linkname',
}
_DEB_ROUTES_FILE = '/etc/network/routes'
_DEB_NETWORK_FILE = '/etc/network/interfaces'
_DEB_NETWORK_DIR = '/etc/network/interfaces.d/'
_DEB_NETWORK_UP_DIR = '/etc/network/if-up.d/'
_DEB_NETWORK_DOWN_DIR = '/etc/network/if-down.d/'
_DEB_NETWORK_CONF_FILES = '/etc/modprobe.d/'
_DEB_NETWORKING_FILE = '/etc/default/networking'
_DEB_HOSTNAME_FILE = '/etc/hostname'
_DEB_RESOLV_FILE = '/etc/resolv.conf'
_DEB_PPP_DIR = '/etc/ppp/peers/'
_CONFIG_TRUE = ['yes', 'on', 'true', '1', True]
_CONFIG_FALSE = ['no', 'off', 'false', '0', False]
_IFACE_TYPES = [
'eth', 'bond', 'alias', 'clone',
'ipsec', 'dialup', 'bridge', 'slave',
'vlan', 'pppoe', 'source',
]
def _error_msg_iface(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, '|'.join(str(e) for e in expected))
def _error_msg_routes(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, expected)
def _log_default_iface(iface, opt, value):
log.info(
'Using default option -- Interface: %s Option: %s Value: %s',
iface, opt, value
)
def _log_default_network(opt, value):
log.info('Using existing setting -- Setting: %s Value: %s', opt, value)
def _raise_error_iface(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_iface(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_network(option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_network(option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_routes(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_routes(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _read_file(path):
'''
Reads and returns the contents of a text file
'''
try:
with salt.utils.files.flopen(path, 'rb') as contents:
return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]
except (OSError, IOError):
return ''
def _parse_resolve():
'''
Parse /etc/resolv.conf
'''
return salt.utils.dns.parse_resolv(_DEB_RESOLV_FILE)
def _parse_domainname():
'''
Parse /etc/resolv.conf and return domainname
'''
return _parse_resolve().get('domain', '')
def _parse_searchdomain():
'''
Parse /etc/resolv.conf and return searchdomain
'''
return _parse_resolve().get('search', '')
def _parse_hostname():
'''
Parse /etc/hostname and return hostname
'''
contents = _read_file(_DEB_HOSTNAME_FILE)
if contents:
return contents[0].split('\n')[0]
else:
return ''
def _parse_current_network_settings():
'''
Parse /etc/default/networking and return current configuration
'''
opts = salt.utils.odict.OrderedDict()
opts['networking'] = ''
if os.path.isfile(_DEB_NETWORKING_FILE):
with salt.utils.files.fopen(_DEB_NETWORKING_FILE) as contents:
for line in contents:
salt.utils.stringutils.to_unicode(line)
if line.startswith('#'):
continue
elif line.startswith('CONFIGURE_INTERFACES'):
opts['networking'] = line.split('=', 1)[1].strip()
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
opts['hostname'] = hostname
opts['domainname'] = domainname
opts['searchdomain'] = searchdomain
return opts
# def __validator_func(value):
# return (valid: True/False, (transformed) value, error message)
def __ipv4_quad(value):
'''validate an IPv4 address'''
return (salt.utils.validate.net.ipv4_addr(value), value,
'dotted IPv4 address')
def __ipv6(value):
'''validate an IPv6 address'''
return (salt.utils.validate.net.ipv6_addr(value), value,
'IPv6 address')
def __mac(value):
'''validate a mac address'''
return (salt.utils.validate.net.mac(value), value,
'MAC address')
def __anything(value):
return (True, value, None)
def __int(value):
'''validate an integer'''
valid, _value = False, value
try:
_value = int(value)
valid = True
except ValueError:
pass
return (valid, _value, 'integer')
def __float(value):
'''validate a float'''
valid, _value = False, value
try:
_value = float(value)
valid = True
except ValueError:
pass
return (valid, _value, 'float')
def __ipv4_netmask(value):
'''validate an IPv4 dotted quad or integer CIDR netmask'''
valid, errmsg = False, 'dotted quad or integer CIDR (0->32)'
valid, value, _ = __int(value)
if not (valid and 0 <= value <= 32):
valid = salt.utils.validate.net.netmask(value)
return (valid, value, errmsg)
def __ipv6_netmask(value):
'''validate an IPv6 integer netmask'''
valid, errmsg = False, 'IPv6 netmask (0->128)'
valid, value, _ = __int(value)
valid = (valid and 0 <= value <= 128)
return (valid, value, errmsg)
def __within2(value, within=None, errmsg=None, dtype=None):
'''validate that a value is in ``within`` and optionally a ``dtype``'''
valid, _value = False, value
if dtype:
try:
_value = dtype(value) # TODO: this is a bit loose when dtype is a class
valid = _value in within
except ValueError:
pass
else:
valid = _value in within
if errmsg is None:
if dtype:
typename = getattr(dtype, '__name__',
hasattr(dtype, '__class__')
and getattr(dtype.__class__, 'name', dtype))
errmsg = '{0} within \'{1}\''.format(typename, within)
else:
errmsg = 'within \'{0}\''.format(within)
return (valid, _value, errmsg)
def __within(within=None, errmsg=None, dtype=None):
return functools.partial(__within2, within=within,
errmsg=errmsg, dtype=dtype)
def __space_delimited_list(value):
'''validate that a value contains one or more space-delimited values'''
if isinstance(value, six.string_types):
value = value.strip().split()
if hasattr(value, '__iter__') and value != []:
return (True, value, 'space-delimited string')
else:
return (False, value, '{0} is not a valid space-delimited value.\n'.format(value))
SALT_ATTR_TO_DEBIAN_ATTR_MAP = {
'dns': 'dns-nameservers',
'search': 'dns-search',
'hwaddr': 'hwaddress', # TODO: this limits bootp functionality
'ipaddr': 'address',
'ipaddrs': 'addresses',
}
DEBIAN_ATTR_TO_SALT_ATTR_MAP = dict(
(v, k) for (k, v) in six.iteritems(SALT_ATTR_TO_DEBIAN_ATTR_MAP))
# TODO
DEBIAN_ATTR_TO_SALT_ATTR_MAP['address'] = 'address'
DEBIAN_ATTR_TO_SALT_ATTR_MAP['hwaddress'] = 'hwaddress'
IPV4_VALID_PROTO = ['bootp', 'dhcp', 'static', 'manual', 'loopback', 'ppp']
IPV4_ATTR_MAP = {
'proto': __within(IPV4_VALID_PROTO, dtype=six.text_type),
# ipv4 static & manual
'address': __ipv4_quad,
'addresses': __anything,
'netmask': __ipv4_netmask,
'broadcast': __ipv4_quad,
'metric': __int,
'gateway': __ipv4_quad, # supports a colon-delimited list
'pointopoint': __ipv4_quad,
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'link', 'host'], dtype=six.text_type),
# dhcp
'hostname': __anything,
'leasehours': __int,
'leasetime': __int,
'vendor': __anything,
'client': __anything,
# bootp
'bootfile': __anything,
'server': __ipv4_quad,
'hwaddr': __mac,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'dstaddr': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# bond
'slaves': __anything,
# ppp
'provider': __anything,
'unit': __int,
'options': __anything,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
#
'network': __anything, # i don't know what this is
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
IPV6_VALID_PROTO = ['auto', 'loopback', 'static', 'manual',
'dhcp', 'v4tunnel', '6to4']
IPV6_ATTR_MAP = {
'proto': __within(IPV6_VALID_PROTO),
# ipv6 static & manual
'address': __ipv6,
'addresses': __anything,
'netmask': __ipv6_netmask,
'broadcast': __ipv6,
'gateway': __ipv6, # supports a colon-delimited list
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'site', 'link', 'host'], dtype=six.text_type),
# inet6 auto
'privext': __within([0, 1, 2], dtype=int),
'dhcp': __within([0, 1], dtype=int),
# inet6 static & manual & dhcp
'media': __anything,
'accept_ra': __within([0, 1], dtype=int),
'autoconf': __within([0, 1], dtype=int),
'preferred-lifetime': __int,
'dad-attempts': __int, # 0 to disable
'dad-interval': __float,
# bond
'slaves': __anything,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
WIRELESS_ATTR_MAP = {
'wireless-essid': __anything,
'wireless-mode': __anything, # TODO
'wpa-ap-scan': __within([0, 1, 2], dtype=int), # TODO
'wpa-conf': __anything,
'wpa-driver': __anything,
'wpa-group': __anything,
'wpa-key-mgmt': __anything,
'wpa-pairwise': __anything,
'wpa-psk': __anything,
'wpa-proto': __anything, # partial(__within,
'wpa-roam': __anything,
'wpa-ssid': __anything, # TODO
}
ATTRMAPS = {
'inet': [IPV4_ATTR_MAP, WIRELESS_ATTR_MAP],
'inet6': [IPV6_ATTR_MAP, WIRELESS_ATTR_MAP]
}
def _validate_interface_option(attr, value, addrfam='inet'):
'''lookup the validation function for a [addrfam][attr] and
return the results
:param attr: attribute name
:param value: raw setting value
:param addrfam: address family (inet, inet6,
'''
valid, _value, errmsg = False, value, 'Unknown validator'
attrmaps = ATTRMAPS.get(addrfam, [])
for attrmap in attrmaps:
if attr in attrmap:
validate_func = attrmap[attr]
(valid, _value, errmsg) = validate_func(value)
break
return (valid, _value, errmsg)
def _attrmaps_contain_attr(attr):
return (
attr in WIRELESS_ATTR_MAP or
attr in IPV4_ATTR_MAP or
attr in IPV6_ATTR_MAP)
def _parse_interfaces(interface_files=None):
'''
Parse /etc/network/interfaces and return current configured interfaces
'''
if interface_files is None:
interface_files = []
# Add this later.
if os.path.exists(_DEB_NETWORK_DIR):
interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]
if os.path.isfile(_DEB_NETWORK_FILE):
interface_files.insert(0, _DEB_NETWORK_FILE)
adapters = salt.utils.odict.OrderedDict()
method = -1
for interface_file in interface_files:
with salt.utils.files.fopen(interface_file) as interfaces:
# This ensures iface_dict exists, but does not ensure we're not reading a new interface.
iface_dict = {}
for line in interfaces:
line = salt.utils.stringutils.to_unicode(line)
# Identify the clauses by the first word of each line.
# Go to the next line if the current line is a comment
# or all spaces.
if line.lstrip().startswith('#') or line.isspace():
continue
# Parse the iface clause
if line.startswith('iface'):
sline = line.split()
if len(sline) != 4:
msg = 'Interface file malformed: {0}.'
msg = msg.format(sline)
log.error(msg)
raise AttributeError(msg)
iface_name = sline[1]
addrfam = sline[2]
method = sline[3]
# Create item in dict, if not already there
if iface_name not in adapters:
adapters[iface_name] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters[iface_name]:
adapters[iface_name]['data'] = salt.utils.odict.OrderedDict()
if addrfam not in adapters[iface_name]['data']:
adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict()
iface_dict = adapters[iface_name]['data'][addrfam]
iface_dict['addrfam'] = addrfam
iface_dict['proto'] = method
iface_dict['filename'] = interface_file
# Parse the detail clauses.
elif line[0].isspace():
sline = line.split()
# conf file attr: dns-nameservers
# salt states.network attr: dns
attr, valuestr = line.rstrip().split(None, 1)
if _attrmaps_contain_attr(attr):
if '-' in attr:
attrname = attr.replace('-', '_')
else:
attrname = attr
(valid, value, errmsg) = _validate_interface_option(
attr, valuestr, addrfam)
if attrname == 'address' and 'address' in iface_dict:
if 'addresses' not in iface_dict:
iface_dict['addresses'] = []
iface_dict['addresses'].append(value)
else:
iface_dict[attrname] = value
elif attr in _REV_ETHTOOL_CONFIG_OPTS:
if 'ethtool' not in iface_dict:
iface_dict['ethtool'] = salt.utils.odict.OrderedDict()
iface_dict['ethtool'][attr] = valuestr
elif attr.startswith('bond'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bonding' not in iface_dict:
iface_dict['bonding'] = salt.utils.odict.OrderedDict()
iface_dict['bonding'][opt] = valuestr
elif attr.startswith('bridge'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bridging' not in iface_dict:
iface_dict['bridging'] = salt.utils.odict.OrderedDict()
iface_dict['bridging'][opt] = valuestr
elif attr in ['up', 'pre-up', 'post-up',
'down', 'pre-down', 'post-down']:
cmd = valuestr
cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr))
if cmd_key not in iface_dict:
iface_dict[cmd_key] = []
iface_dict[cmd_key].append(cmd)
elif line.startswith('auto'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['enabled'] = True
elif line.startswith('allow-hotplug'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['hotplug'] = True
elif line.startswith('source'):
if 'source' not in adapters:
adapters['source'] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters['source']:
adapters['source']['data'] = salt.utils.odict.OrderedDict()
adapters['source']['data']['sources'] = []
adapters['source']['data']['sources'].append(line.split()[1])
# Return a sorted list of the keys for bond, bridge and ethtool options to
# ensure a consistent order
for iface_name in adapters:
if iface_name == 'source':
continue
if 'data' not in adapters[iface_name]:
msg = 'Interface file malformed for interface: {0}.'.format(iface_name)
log.error(msg)
adapters.pop(iface_name)
continue
for opt in ['ethtool', 'bonding', 'bridging']:
for inet in ['inet', 'inet6']:
if inet in adapters[iface_name]['data']:
if opt in adapters[iface_name]['data'][inet]:
opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys())
adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys
return adapters
def _parse_ethtool_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
if 'autoneg' in opts:
if opts['autoneg'] in _CONFIG_TRUE:
config.update({'autoneg': 'on'})
elif opts['autoneg'] in _CONFIG_FALSE:
config.update({'autoneg': 'off'})
else:
_raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE)
if 'duplex' in opts:
valid = ['full', 'half']
if opts['duplex'] in valid:
config.update({'duplex': opts['duplex']})
else:
_raise_error_iface(iface, 'duplex', valid)
if 'speed' in opts:
valid = ['10', '100', '1000', '10000']
if six.text_type(opts['speed']) in valid:
config.update({'speed': opts['speed']})
else:
_raise_error_iface(iface, opts['speed'], valid)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'on'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'off'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_ethtool_pppoe_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
for opt in _DEB_CONFIG_PPPOE_OPTS:
if opt in opts:
config[opt] = opts[opt]
if 'provider' in opts and not opts['provider']:
_raise_error_iface(iface, 'provider', _CONFIG_TRUE + _CONFIG_FALSE)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('noipdefault', 'usepeerdns', 'defaultroute', 'hide-password', 'noauth', 'persist', 'noaccomp'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'True'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'False'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_settings_bond(opts, iface):
'''
Filters given options and outputs valid settings for requested
operation. If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond_def = {
# 803.ad aggregation selection logic
# 0 for stable (default)
# 1 for bandwidth
# 2 for count
'ad_select': '0',
# Max number of transmit queues (default = 16)
'tx_queues': '16',
# Link monitoring in milliseconds. Most NICs support this
'miimon': '100',
# ARP interval in milliseconds
'arp_interval': '250',
# Delay before considering link down in milliseconds (miimon * 2)
'downdelay': '200',
# lacp_rate 0: Slow - every 30 seconds
# lacp_rate 1: Fast - every 1 second
'lacp_rate': '0',
# Max bonds for this driver
'max_bonds': '1',
# Specifies the time, in milliseconds, to wait before
# enabling a slave after a link recovery has been
# detected. Only used with miimon.
'updelay': '0',
# Used with miimon.
# On: driver sends mii
# Off: ethtool sends mii
'use_carrier': 'on',
# Default. Don't change unless you know what you are doing.
'xmit_hash_policy': 'layer2',
}
if opts['mode'] in ['balance-rr', '0']:
log.info('Device: %s Bonding Mode: load balancing (round-robin)', iface)
return _parse_settings_bond_0(opts, iface, bond_def)
elif opts['mode'] in ['active-backup', '1']:
log.info('Device: %s Bonding Mode: fault-tolerance (active-backup)', iface)
return _parse_settings_bond_1(opts, iface, bond_def)
elif opts['mode'] in ['balance-xor', '2']:
log.info('Device: %s Bonding Mode: load balancing (xor)', iface)
return _parse_settings_bond_2(opts, iface, bond_def)
elif opts['mode'] in ['broadcast', '3']:
log.info('Device: %s Bonding Mode: fault-tolerance (broadcast)', iface)
return _parse_settings_bond_3(opts, iface, bond_def)
elif opts['mode'] in ['802.3ad', '4']:
log.info('Device: %s Bonding Mode: IEEE 802.3ad Dynamic link '
'aggregation', iface)
return _parse_settings_bond_4(opts, iface, bond_def)
elif opts['mode'] in ['balance-tlb', '5']:
log.info('Device: %s Bonding Mode: transmit load balancing', iface)
return _parse_settings_bond_5(opts, iface, bond_def)
elif opts['mode'] in ['balance-alb', '6']:
log.info('Device: %s Bonding Mode: adaptive load balancing', iface)
return _parse_settings_bond_6(opts, iface, bond_def)
else:
valid = [
'0', '1', '2', '3', '4', '5', '6',
'balance-rr', 'active-backup', 'balance-xor',
'broadcast', '802.3ad', 'balance-tlb', 'balance-alb'
]
_raise_error_iface(iface, 'mode', valid)
def _parse_settings_bond_0(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond0.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '0'}
# ARP targets in n.n.n.n form
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
return bond
def _parse_settings_bond_1(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '1'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
if not (__grains__['os'] == "Ubuntu" and __grains__['osrelease_info'][0] >= 16):
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_2(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond2.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '2'}
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_3(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond3.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '3'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_4(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond4.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '4'}
for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']:
if binding in opts:
if binding == 'lacp_rate':
if opts[binding] == 'fast':
opts.update({binding: '1'})
if opts[binding] == 'slow':
opts.update({binding: '0'})
valid = ['fast', '1', 'slow', '0']
else:
valid = ['integer']
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, valid)
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_5(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond5.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '5'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_settings_bond_6(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond6.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '6'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_bridge_opts(opts, iface):
'''
Filters given options and outputs valid settings for BRIDGING_OPTS
If an option has a value that is not expected, this
function will log the Interface, Setting and what was expected.
'''
config = {}
if 'ports' in opts:
if isinstance(opts['ports'], list):
opts['ports'] = ' '.join(opts['ports'])
config.update({'ports': opts['ports']})
for opt in ['ageing', 'fd', 'gcint', 'hello', 'maxage']:
if opt in opts:
try:
float(opts[opt])
config.update({opt: opts[opt]})
except ValueError:
_raise_error_iface(iface, opt, ['float'])
for opt in ['bridgeprio', 'maxwait']:
if opt in opts:
if isinstance(opts[opt], int):
config.update({opt: opts[opt]})
else:
_raise_error_iface(iface, opt, ['integer'])
if 'hw' in opts:
# match 12 hex digits with either : or - as separators between pairs
if re.match('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$',
opts['hw'].lower()):
config.update({'hw': opts['hw']})
else:
_raise_error_iface(iface, 'hw', ['valid MAC address'])
for opt in ['pathcost', 'portprio']:
if opt in opts:
try:
port, cost_or_prio = opts[opt].split()
int(cost_or_prio)
config.update({opt: '{0} {1}'.format(port, cost_or_prio)})
except ValueError:
_raise_error_iface(iface, opt, ['interface integer'])
if 'stp' in opts:
if opts['stp'] in _CONFIG_TRUE:
config.update({'stp': 'on'})
elif opts['stp'] in _CONFIG_FALSE:
config.update({'stp': 'off'})
else:
_raise_error_iface(iface, 'stp', _CONFIG_TRUE + _CONFIG_FALSE)
if 'waitport' in opts:
if isinstance(opts['waitport'], int):
config.update({'waitport': opts['waitport']})
else:
values = opts['waitport'].split()
waitport_time = values.pop(0)
if waitport_time.isdigit() and values:
config.update({
'waitport': '{0} {1}'.format(
waitport_time, ' '.join(values)
)
})
else:
_raise_error_iface(iface, opt, ['integer [interfaces]'])
return config
def _parse_settings_eth(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['inet'] = salt.utils.odict.OrderedDict()
iface_data['inet6'] = salt.utils.odict.OrderedDict()
if enabled:
adapters[iface]['enabled'] = True
if opts.get('hotplug', False):
adapters[iface]['hotplug'] = True
if opts.get('enable_ipv6', None) and opts.get('iface_type', '') == 'vlan':
iface_data['inet6']['vlan_raw_device'] = (
re.sub(r'\.\d*', '', iface))
for addrfam in ['inet', 'inet6']:
if iface_type not in ['bridge']:
tmp_ethtool = _parse_ethtool_opts(opts, iface)
if tmp_ethtool:
ethtool = {}
for item in tmp_ethtool:
ethtool[_ETHTOOL_CONFIG_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['ethtool'] = ethtool
# return a list of sorted keys to ensure consistent order
iface_data[addrfam]['ethtool_keys'] = sorted(ethtool)
if iface_type == 'bridge':
bridging = _parse_bridge_opts(opts, iface)
if bridging:
iface_data[addrfam]['bridging'] = bridging
iface_data[addrfam]['bridging_keys'] = sorted(bridging)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'bond':
bonding = _parse_settings_bond(opts, iface)
if bonding:
iface_data[addrfam]['bonding'] = bonding
iface_data[addrfam]['bonding']['slaves'] = opts['slaves']
iface_data[addrfam]['bonding_keys'] = sorted(bonding)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'slave':
adapters[iface]['master'] = opts['master']
opts['proto'] = 'manual'
iface_data[addrfam]['master'] = adapters[iface]['master']
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'vlan':
iface_data[addrfam]['vlan_raw_device'] = re.sub(r'\.\d*', '', iface)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'pppoe':
tmp_ethtool = _parse_ethtool_pppoe_opts(opts, iface)
if tmp_ethtool:
for item in tmp_ethtool:
adapters[iface]['data'][addrfam][_DEB_CONFIG_PPPOE_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['addrfam'] = addrfam
opts.pop('mode', None)
for opt, val in opts.items():
inet = None
if opt.startswith('ipv4'):
opt = opt[4:]
inet = 'inet'
iface_data['inet']['addrfam'] = 'inet'
elif opt.startswith('ipv6'):
iface_data['inet6']['addrfam'] = 'inet6'
opt = opt[4:]
inet = 'inet6'
elif opt in ['ipaddr', 'address', 'ipaddresses', 'addresses', 'gateway', 'proto']:
iface_data['inet']['addrfam'] = 'inet'
inet = 'inet'
_opt = SALT_ATTR_TO_DEBIAN_ATTR_MAP.get(opt, opt)
_debopt = _opt.replace('-', '_')
for addrfam in ['inet', 'inet6']:
(valid, value, errmsg) = _validate_interface_option(_opt, val, addrfam=addrfam)
if not valid:
continue
if inet is None and _debopt not in iface_data[addrfam]:
iface_data[addrfam][_debopt] = value
elif inet == addrfam:
iface_data[addrfam][_debopt] = value
for opt in ['up_cmds', 'pre_up_cmds', 'post_up_cmds',
'down_cmds', 'pre_down_cmds', 'post_down_cmds']:
if opt in opts:
iface_data['inet'][opt] = opts[opt]
iface_data['inet6'][opt] = opts[opt]
# Remove incomplete/disabled inet blocks
for (addrfam, opt) in [('inet', 'enable_ipv4'), ('inet6', 'enable_ipv6')]:
if opts.get(opt, None) is False:
iface_data.pop(addrfam)
elif iface_data[addrfam].get('addrfam', '') != addrfam:
iface_data.pop(addrfam)
return adapters
def _parse_settings_source(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['sources'] = [opts['source']]
return adapters
def _parse_network_settings(opts, current):
'''
Filters given options and outputs valid settings for
the global network settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
current = dict((k.lower(), v) for (k, v) in six.iteritems(current))
result = {}
valid = _CONFIG_TRUE + _CONFIG_FALSE
if 'enabled' not in opts:
try:
opts['networking'] = current['networking']
_log_default_network('networking', current['networking'])
except ValueError:
_raise_error_network('networking', valid)
else:
opts['networking'] = opts['enabled']
if opts['networking'] in valid:
if opts['networking'] in _CONFIG_TRUE:
result['networking'] = 'yes'
elif opts['networking'] in _CONFIG_FALSE:
result['networking'] = 'no'
else:
_raise_error_network('networking', valid)
if 'hostname' not in opts:
try:
opts['hostname'] = current['hostname']
_log_default_network('hostname', current['hostname'])
except ValueError:
_raise_error_network('hostname', ['server1.example.com'])
if opts['hostname']:
result['hostname'] = opts['hostname']
else:
_raise_error_network('hostname', ['server1.example.com'])
if 'search' in opts:
result['search'] = opts['search']
return result
def _parse_routes(iface, opts):
'''
Filters given options and outputs valid settings for
the route settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
result = {}
if 'routes' not in opts:
_raise_error_routes(iface, 'routes', 'List of routes')
for opt in opts:
result[opt] = opts[opt]
return result
def _write_file(iface, data, folder, pattern):
'''
Writes a file to disk
'''
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
return filename
def _write_file_routes(iface, data, folder, pattern):
'''
Writes a file to disk
'''
# ifup / ifdown is executing given folder via run-parts.
# according to run-parts man-page, only filenames with this pattern are
# executed: (^[a-zA-Z0-9_-]+$)
# In order to make the routes file work for vlan interfaces
# (default would have been in example /etc/network/if-up.d/route-bond0.12)
# these dots in the iface name need to be replaced by underscores, so it
# can be executed by run-parts
iface = iface.replace('.', '_')
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
__salt__['file.set_mode'](filename, '0755')
return filename
def _write_file_network(data, filename, create=False):
'''
Writes a file to disk
If file does not exist, only create if create
argument is True
'''
if not os.path.exists(filename) and not create:
msg = '{0} cannot be written. {0} does not exist\
and create is set to False'
msg = msg.format(filename)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
def _read_temp(data):
'''
Return what would be written to disk
'''
tout = StringIO()
tout.write(data)
tout.seek(0)
output = tout.readlines()
tout.close()
return output
def _read_temp_ifaces(iface, data):
'''
Return what would be written to disk for interfaces
'''
try:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': data})
# Return as an array so the difflib works
return [item + '\n' for item in ifcfg.split('\n')]
def _write_file_ifaces(iface, data, **settings):
'''
Writes a file to disk
'''
try:
eth_template = JINJA.get_template('debian_eth.jinja')
source_template = JINJA.get_template('debian_source.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
# Read /etc/network/interfaces into a dict
adapters = _parse_interfaces()
# Apply supplied settings over on-disk settings
adapters[iface] = data
ifcfg = ''
for adapter in adapters:
if 'type' in adapters[adapter] and adapters[adapter]['type'] == 'source':
tmp = source_template.render({'name': adapter, 'data': adapters[adapter]})
else:
tmp = eth_template.render({'name': adapter, 'data': adapters[adapter]})
ifcfg = ifcfg + tmp
if adapter == iface:
saved_ifcfg = tmp
_SEPARATE_FILE = False
if 'filename' in settings:
if not settings['filename'].startswith('/'):
filename = '{0}/{1}'.format(_DEB_NETWORK_DIR, settings['filename'])
else:
filename = settings['filename']
_SEPARATE_FILE = True
else:
if 'filename' in adapters[adapter]['data']:
filename = adapters[adapter]['data']
else:
filename = _DEB_NETWORK_FILE
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
if _SEPARATE_FILE:
fout.write(salt.utils.stringutils.to_str(saved_ifcfg))
else:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return saved_ifcfg.split('\n')
def _write_file_ppp_ifaces(iface, data):
'''
Writes a file to disk
'''
try:
template = JINJA.get_template('debian_ppp_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_ppp_eth.jinja')
return ''
adapters = _parse_interfaces()
adapters[iface] = data
ifcfg = ''
tmp = template.render({'data': adapters[iface]})
ifcfg = tmp + ifcfg
filename = _DEB_PPP_DIR + '/' + adapters[iface]['data']['inet']['provider']
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.fopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return filename
def build_bond(iface, **settings):
'''
Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb
'''
deb_major = __grains__['osrelease'][:1]
opts = _parse_settings_bond(settings, iface)
try:
template = JINJA.get_template('conf.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template conf.jinja')
return ''
data = template.render({'name': iface, 'bonding': opts})
if 'test' in settings and settings['test']:
return _read_temp(data)
_write_file(iface, data, _DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
if deb_major == '5':
for line_type in ('alias', 'options'):
cmd = ['sed', '-i', '-e', r'/^{0}\s{1}.*/d'.format(line_type, iface),
'/etc/modprobe.conf']
__salt__['cmd.run'](cmd, python_shell=False)
__salt__['file.append']('/etc/modprobe.conf', path)
# Load kernel module
__salt__['kmod.load']('bonding')
# install ifenslave-2.6
__salt__['pkg.install']('ifenslave-2.6')
return _read_file(path)
def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'vlan':
settings['vlan'] = 'yes'
__salt__['pkg.install']('vlan')
elif iface_type == 'pppoe':
settings['pppoe'] = 'yes'
if not __salt__['pkg.version']('ppp'):
inst = __salt__['pkg.install']('ppp')
elif iface_type == 'bond':
if 'slaves' not in settings:
msg = 'slaves is a required setting for bond interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'bridge':
if 'ports' not in settings:
msg = (
'ports is a required setting for bridge interfaces on Debian '
'or Ubuntu based systems'
)
log.error(msg)
raise AttributeError(msg)
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'pppoe']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
if iface_type in ['source']:
opts = _parse_settings_source(settings, iface_type, enabled, iface)
if 'test' in settings and settings['test']:
return _read_temp_ifaces(iface, opts[iface])
ifcfg = _write_file_ifaces(iface, opts[iface], **settings)
if iface_type == 'pppoe':
_write_file_ppp_ifaces(iface, opts[iface])
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg]
def build_routes(iface, **settings):
'''
Add route scripts for a network interface using up commands.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
'''
opts = _parse_routes(iface, settings)
try:
template = JINJA.get_template('route_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template route_eth.jinja')
return ''
add_routecfg = template.render(route_type='add',
routes=opts['routes'],
iface=iface)
del_routecfg = template.render(route_type='del',
routes=opts['routes'],
iface=iface)
if 'test' in settings and settings['test']:
return _read_temp(add_routecfg + del_routecfg)
filename = _write_file_routes(iface,
add_routecfg,
_DEB_NETWORK_UP_DIR,
'route-{0}')
results = _read_file(filename)
filename = _write_file_routes(iface,
del_routecfg,
_DEB_NETWORK_DOWN_DIR,
'route-{0}')
results += _read_file(filename)
return results
def down(iface, iface_type):
'''
Shutdown a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.down eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought down.
if iface_type not in ['slave', 'source']:
return __salt__['cmd.run'](['ifdown', iface])
return None
def get_bond(iface):
'''
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
'''
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
return _read_file(path)
def get_interface(iface):
'''
Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
adapters = _parse_interfaces()
if iface in adapters:
try:
if iface == 'source':
template = JINJA.get_template('debian_source.jinja')
else:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': adapters[iface]})
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg.split('\n')]
else:
return []
def up(iface, iface_type): # pylint: disable=C0103
'''
Start up a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.up eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought up.
if iface_type not in ('slave', 'source'):
return __salt__['cmd.run'](['ifup', iface])
return None
def get_network_settings():
'''
Return the contents of the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_network_settings
'''
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
settings = {}
if __salt__['service.available']('networking'):
if __salt__['service.status']('networking'):
settings['networking'] = "yes"
else:
settings['networking'] = "no"
else:
settings['networking'] = "no"
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
settings['hostname'] = hostname
settings['domainname'] = domainname
settings['searchdomain'] = searchdomain
else:
settings = _parse_current_network_settings()
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(settings)
return _read_temp(network)
def get_routes(iface):
'''
Return the routes for the interface
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0
'''
filename = os.path.join(_DEB_NETWORK_UP_DIR, 'route-{0}'.format(iface))
results = _read_file(filename)
filename = os.path.join(_DEB_NETWORK_DOWN_DIR, 'route-{0}'.format(iface))
results += _read_file(filename)
return results
def apply_network_settings(**settings):
'''
Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings
'''
if 'require_reboot' not in settings:
settings['require_reboot'] = False
if 'apply_hostname' not in settings:
settings['apply_hostname'] = False
hostname_res = True
if settings['apply_hostname'] in _CONFIG_TRUE:
if 'hostname' in settings:
hostname_res = __salt__['network.mod_hostname'](settings['hostname'])
else:
log.warning(
'The network state sls is trying to apply hostname '
'changes but no hostname is defined.'
)
hostname_res = False
res = True
if settings['require_reboot'] in _CONFIG_TRUE:
log.warning(
'The network state sls is requiring a reboot of the system to '
'properly apply network configuration.'
)
res = True
else:
stop = __salt__['service.stop']('networking')
time.sleep(2)
res = stop and __salt__['service.start']('networking')
return hostname_res and res
def build_network_settings(**settings):
'''
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
'''
changes = []
# Read current configuration and store default values
current_network_settings = _parse_current_network_settings()
# Build settings
opts = _parse_network_settings(settings, current_network_settings)
# Ubuntu has moved away from /etc/default/networking
# beginning with the 12.04 release so we disable or enable
# the networking related services on boot
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
if opts['networking'] == 'yes':
service_cmd = 'service.enable'
else:
service_cmd = 'service.disable'
if __salt__['service.available']('NetworkManager'):
__salt__[service_cmd]('NetworkManager')
if __salt__['service.available']('networking'):
__salt__[service_cmd]('networking')
else:
try:
template = JINJA.get_template('network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template network.jinja')
return ''
network = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(network)
# Write settings
_write_file_network(network, _DEB_NETWORKING_FILE, True)
# Get hostname and domain from opts
sline = opts['hostname'].split('.', 1)
opts['hostname'] = sline[0]
current_domainname = current_network_settings['domainname']
current_searchdomain = current_network_settings['searchdomain']
new_domain = False
if len(sline) > 1:
new_domainname = sline[1]
if new_domainname != current_domainname:
domainname = new_domainname
opts['domainname'] = new_domainname
new_domain = True
else:
domainname = current_domainname
opts['domainname'] = domainname
else:
domainname = current_domainname
opts['domainname'] = domainname
new_search = False
if 'search' in opts:
new_searchdomain = opts['search']
if new_searchdomain != current_searchdomain:
searchdomain = new_searchdomain
opts['searchdomain'] = new_searchdomain
new_search = True
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
# If the domain changes, then we should write the resolv.conf file.
if new_domain or new_search:
# Look for existing domain line and update if necessary
resolve = _parse_resolve()
domain_prog = re.compile(r'domain\s+')
search_prog = re.compile(r'search\s+')
new_contents = []
for item in _read_file(_DEB_RESOLV_FILE):
if domain_prog.match(item):
item = 'domain {0}'.format(domainname)
elif search_prog.match(item):
item = 'search {0}'.format(searchdomain)
new_contents.append(item)
# A domain line didn't exist so we'll add one in
# with the new domainname
if 'domain' not in resolve:
new_contents.insert(0, 'domain {0}' . format(domainname))
# A search line didn't exist so we'll add one in
# with the new search domain
if 'search' not in resolve:
new_contents.insert('domain' in resolve, 'search {0}'.format(searchdomain))
new_resolv = '\n'.join(new_contents)
# Write /etc/resolv.conf
if not ('test' in settings and settings['test']):
_write_file_network(new_resolv, _DEB_RESOLV_FILE)
# used for returning the results back
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(opts)
changes.extend(_read_temp(network))
return changes
|
saltstack/salt
|
salt/modules/debian_ip.py
|
_raise_error_iface
|
python
|
def _raise_error_iface(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_iface(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
|
Log and raise an error with a logical formatted message.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_ip.py#L193-L199
|
[
"def _error_msg_iface(iface, option, expected):\n '''\n Build an appropriate error message from a given option and\n a list of expected values.\n '''\n msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]'\n return msg.format(iface, option, '|'.join(str(e) for e in expected))\n"
] |
# -*- coding: utf-8 -*-
'''
The networking module for Debian-based distros
References:
* http://www.debian.org/doc/manuals/debian-reference/ch05.en.html
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import functools
import logging
import os.path
import os
import re
import time
# Import third party libs
import jinja2
import jinja2.exceptions
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error,no-name-in-module
# Import salt libs
import salt.utils.dns
import salt.utils.files
import salt.utils.odict
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.validate.net
# Set up logging
log = logging.getLogger(__name__)
# Set up template environment
JINJA = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'debian_ip')
)
)
# Define the module's virtual name
__virtualname__ = 'ip'
def __virtual__():
'''
Confine this module to Debian-based distros
'''
if __grains__['os_family'] == 'Debian':
return __virtualname__
return (False, 'The debian_ip module could not be loaded: '
'unsupported OS family')
_ETHTOOL_CONFIG_OPTS = {
'speed': 'link-speed',
'duplex': 'link-duplex',
'autoneg': 'ethernet-autoneg',
'ethernet-port': 'ethernet-port',
'wol': 'ethernet-wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'rx': 'offload-rx',
'tx': 'offload-tx',
'sg': 'offload-sg',
'tso': 'offload-tso',
'ufo': 'offload-ufo',
'gso': 'offload-gso',
'gro': 'offload-gro',
'lro': 'offload-lro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_REV_ETHTOOL_CONFIG_OPTS = {
'link-speed': 'speed',
'link-duplex': 'duplex',
'ethernet-autoneg': 'autoneg',
'ethernet-port': 'ethernet-port',
'ethernet-wol': 'wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'offload-rx': 'rx',
'offload-tx': 'tx',
'offload-sg': 'sg',
'offload-tso': 'tso',
'offload-ufo': 'ufo',
'offload-gso': 'gso',
'offload-lro': 'lro',
'offload-gro': 'gro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_DEB_CONFIG_PPPOE_OPTS = {
'user': 'user',
'password': 'password',
'provider': 'provider',
'pppoe_iface': 'pppoe_iface',
'noipdefault': 'noipdefault',
'usepeerdns': 'usepeerdns',
'defaultroute': 'defaultroute',
'holdoff': 'holdoff',
'maxfail': 'maxfail',
'hide-password': 'hide-password',
'lcp-echo-interval': 'lcp-echo-interval',
'lcp-echo-failure': 'lcp-echo-failure',
'connect': 'connect',
'noauth': 'noauth',
'persist': 'persist',
'mtu': 'mtu',
'noaccomp': 'noaccomp',
'linkname': 'linkname',
}
_DEB_ROUTES_FILE = '/etc/network/routes'
_DEB_NETWORK_FILE = '/etc/network/interfaces'
_DEB_NETWORK_DIR = '/etc/network/interfaces.d/'
_DEB_NETWORK_UP_DIR = '/etc/network/if-up.d/'
_DEB_NETWORK_DOWN_DIR = '/etc/network/if-down.d/'
_DEB_NETWORK_CONF_FILES = '/etc/modprobe.d/'
_DEB_NETWORKING_FILE = '/etc/default/networking'
_DEB_HOSTNAME_FILE = '/etc/hostname'
_DEB_RESOLV_FILE = '/etc/resolv.conf'
_DEB_PPP_DIR = '/etc/ppp/peers/'
_CONFIG_TRUE = ['yes', 'on', 'true', '1', True]
_CONFIG_FALSE = ['no', 'off', 'false', '0', False]
_IFACE_TYPES = [
'eth', 'bond', 'alias', 'clone',
'ipsec', 'dialup', 'bridge', 'slave',
'vlan', 'pppoe', 'source',
]
def _error_msg_iface(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, '|'.join(str(e) for e in expected))
def _error_msg_routes(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, expected)
def _log_default_iface(iface, opt, value):
log.info(
'Using default option -- Interface: %s Option: %s Value: %s',
iface, opt, value
)
def _error_msg_network(option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]'
return msg.format(option, '|'.join(str(e) for e in expected))
def _log_default_network(opt, value):
log.info('Using existing setting -- Setting: %s Value: %s', opt, value)
def _raise_error_network(option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_network(option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_routes(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_routes(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _read_file(path):
'''
Reads and returns the contents of a text file
'''
try:
with salt.utils.files.flopen(path, 'rb') as contents:
return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]
except (OSError, IOError):
return ''
def _parse_resolve():
'''
Parse /etc/resolv.conf
'''
return salt.utils.dns.parse_resolv(_DEB_RESOLV_FILE)
def _parse_domainname():
'''
Parse /etc/resolv.conf and return domainname
'''
return _parse_resolve().get('domain', '')
def _parse_searchdomain():
'''
Parse /etc/resolv.conf and return searchdomain
'''
return _parse_resolve().get('search', '')
def _parse_hostname():
'''
Parse /etc/hostname and return hostname
'''
contents = _read_file(_DEB_HOSTNAME_FILE)
if contents:
return contents[0].split('\n')[0]
else:
return ''
def _parse_current_network_settings():
'''
Parse /etc/default/networking and return current configuration
'''
opts = salt.utils.odict.OrderedDict()
opts['networking'] = ''
if os.path.isfile(_DEB_NETWORKING_FILE):
with salt.utils.files.fopen(_DEB_NETWORKING_FILE) as contents:
for line in contents:
salt.utils.stringutils.to_unicode(line)
if line.startswith('#'):
continue
elif line.startswith('CONFIGURE_INTERFACES'):
opts['networking'] = line.split('=', 1)[1].strip()
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
opts['hostname'] = hostname
opts['domainname'] = domainname
opts['searchdomain'] = searchdomain
return opts
# def __validator_func(value):
# return (valid: True/False, (transformed) value, error message)
def __ipv4_quad(value):
'''validate an IPv4 address'''
return (salt.utils.validate.net.ipv4_addr(value), value,
'dotted IPv4 address')
def __ipv6(value):
'''validate an IPv6 address'''
return (salt.utils.validate.net.ipv6_addr(value), value,
'IPv6 address')
def __mac(value):
'''validate a mac address'''
return (salt.utils.validate.net.mac(value), value,
'MAC address')
def __anything(value):
return (True, value, None)
def __int(value):
'''validate an integer'''
valid, _value = False, value
try:
_value = int(value)
valid = True
except ValueError:
pass
return (valid, _value, 'integer')
def __float(value):
'''validate a float'''
valid, _value = False, value
try:
_value = float(value)
valid = True
except ValueError:
pass
return (valid, _value, 'float')
def __ipv4_netmask(value):
'''validate an IPv4 dotted quad or integer CIDR netmask'''
valid, errmsg = False, 'dotted quad or integer CIDR (0->32)'
valid, value, _ = __int(value)
if not (valid and 0 <= value <= 32):
valid = salt.utils.validate.net.netmask(value)
return (valid, value, errmsg)
def __ipv6_netmask(value):
'''validate an IPv6 integer netmask'''
valid, errmsg = False, 'IPv6 netmask (0->128)'
valid, value, _ = __int(value)
valid = (valid and 0 <= value <= 128)
return (valid, value, errmsg)
def __within2(value, within=None, errmsg=None, dtype=None):
'''validate that a value is in ``within`` and optionally a ``dtype``'''
valid, _value = False, value
if dtype:
try:
_value = dtype(value) # TODO: this is a bit loose when dtype is a class
valid = _value in within
except ValueError:
pass
else:
valid = _value in within
if errmsg is None:
if dtype:
typename = getattr(dtype, '__name__',
hasattr(dtype, '__class__')
and getattr(dtype.__class__, 'name', dtype))
errmsg = '{0} within \'{1}\''.format(typename, within)
else:
errmsg = 'within \'{0}\''.format(within)
return (valid, _value, errmsg)
def __within(within=None, errmsg=None, dtype=None):
return functools.partial(__within2, within=within,
errmsg=errmsg, dtype=dtype)
def __space_delimited_list(value):
'''validate that a value contains one or more space-delimited values'''
if isinstance(value, six.string_types):
value = value.strip().split()
if hasattr(value, '__iter__') and value != []:
return (True, value, 'space-delimited string')
else:
return (False, value, '{0} is not a valid space-delimited value.\n'.format(value))
SALT_ATTR_TO_DEBIAN_ATTR_MAP = {
'dns': 'dns-nameservers',
'search': 'dns-search',
'hwaddr': 'hwaddress', # TODO: this limits bootp functionality
'ipaddr': 'address',
'ipaddrs': 'addresses',
}
DEBIAN_ATTR_TO_SALT_ATTR_MAP = dict(
(v, k) for (k, v) in six.iteritems(SALT_ATTR_TO_DEBIAN_ATTR_MAP))
# TODO
DEBIAN_ATTR_TO_SALT_ATTR_MAP['address'] = 'address'
DEBIAN_ATTR_TO_SALT_ATTR_MAP['hwaddress'] = 'hwaddress'
IPV4_VALID_PROTO = ['bootp', 'dhcp', 'static', 'manual', 'loopback', 'ppp']
IPV4_ATTR_MAP = {
'proto': __within(IPV4_VALID_PROTO, dtype=six.text_type),
# ipv4 static & manual
'address': __ipv4_quad,
'addresses': __anything,
'netmask': __ipv4_netmask,
'broadcast': __ipv4_quad,
'metric': __int,
'gateway': __ipv4_quad, # supports a colon-delimited list
'pointopoint': __ipv4_quad,
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'link', 'host'], dtype=six.text_type),
# dhcp
'hostname': __anything,
'leasehours': __int,
'leasetime': __int,
'vendor': __anything,
'client': __anything,
# bootp
'bootfile': __anything,
'server': __ipv4_quad,
'hwaddr': __mac,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'dstaddr': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# bond
'slaves': __anything,
# ppp
'provider': __anything,
'unit': __int,
'options': __anything,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
#
'network': __anything, # i don't know what this is
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
IPV6_VALID_PROTO = ['auto', 'loopback', 'static', 'manual',
'dhcp', 'v4tunnel', '6to4']
IPV6_ATTR_MAP = {
'proto': __within(IPV6_VALID_PROTO),
# ipv6 static & manual
'address': __ipv6,
'addresses': __anything,
'netmask': __ipv6_netmask,
'broadcast': __ipv6,
'gateway': __ipv6, # supports a colon-delimited list
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'site', 'link', 'host'], dtype=six.text_type),
# inet6 auto
'privext': __within([0, 1, 2], dtype=int),
'dhcp': __within([0, 1], dtype=int),
# inet6 static & manual & dhcp
'media': __anything,
'accept_ra': __within([0, 1], dtype=int),
'autoconf': __within([0, 1], dtype=int),
'preferred-lifetime': __int,
'dad-attempts': __int, # 0 to disable
'dad-interval': __float,
# bond
'slaves': __anything,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
WIRELESS_ATTR_MAP = {
'wireless-essid': __anything,
'wireless-mode': __anything, # TODO
'wpa-ap-scan': __within([0, 1, 2], dtype=int), # TODO
'wpa-conf': __anything,
'wpa-driver': __anything,
'wpa-group': __anything,
'wpa-key-mgmt': __anything,
'wpa-pairwise': __anything,
'wpa-psk': __anything,
'wpa-proto': __anything, # partial(__within,
'wpa-roam': __anything,
'wpa-ssid': __anything, # TODO
}
ATTRMAPS = {
'inet': [IPV4_ATTR_MAP, WIRELESS_ATTR_MAP],
'inet6': [IPV6_ATTR_MAP, WIRELESS_ATTR_MAP]
}
def _validate_interface_option(attr, value, addrfam='inet'):
'''lookup the validation function for a [addrfam][attr] and
return the results
:param attr: attribute name
:param value: raw setting value
:param addrfam: address family (inet, inet6,
'''
valid, _value, errmsg = False, value, 'Unknown validator'
attrmaps = ATTRMAPS.get(addrfam, [])
for attrmap in attrmaps:
if attr in attrmap:
validate_func = attrmap[attr]
(valid, _value, errmsg) = validate_func(value)
break
return (valid, _value, errmsg)
def _attrmaps_contain_attr(attr):
return (
attr in WIRELESS_ATTR_MAP or
attr in IPV4_ATTR_MAP or
attr in IPV6_ATTR_MAP)
def _parse_interfaces(interface_files=None):
'''
Parse /etc/network/interfaces and return current configured interfaces
'''
if interface_files is None:
interface_files = []
# Add this later.
if os.path.exists(_DEB_NETWORK_DIR):
interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]
if os.path.isfile(_DEB_NETWORK_FILE):
interface_files.insert(0, _DEB_NETWORK_FILE)
adapters = salt.utils.odict.OrderedDict()
method = -1
for interface_file in interface_files:
with salt.utils.files.fopen(interface_file) as interfaces:
# This ensures iface_dict exists, but does not ensure we're not reading a new interface.
iface_dict = {}
for line in interfaces:
line = salt.utils.stringutils.to_unicode(line)
# Identify the clauses by the first word of each line.
# Go to the next line if the current line is a comment
# or all spaces.
if line.lstrip().startswith('#') or line.isspace():
continue
# Parse the iface clause
if line.startswith('iface'):
sline = line.split()
if len(sline) != 4:
msg = 'Interface file malformed: {0}.'
msg = msg.format(sline)
log.error(msg)
raise AttributeError(msg)
iface_name = sline[1]
addrfam = sline[2]
method = sline[3]
# Create item in dict, if not already there
if iface_name not in adapters:
adapters[iface_name] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters[iface_name]:
adapters[iface_name]['data'] = salt.utils.odict.OrderedDict()
if addrfam not in adapters[iface_name]['data']:
adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict()
iface_dict = adapters[iface_name]['data'][addrfam]
iface_dict['addrfam'] = addrfam
iface_dict['proto'] = method
iface_dict['filename'] = interface_file
# Parse the detail clauses.
elif line[0].isspace():
sline = line.split()
# conf file attr: dns-nameservers
# salt states.network attr: dns
attr, valuestr = line.rstrip().split(None, 1)
if _attrmaps_contain_attr(attr):
if '-' in attr:
attrname = attr.replace('-', '_')
else:
attrname = attr
(valid, value, errmsg) = _validate_interface_option(
attr, valuestr, addrfam)
if attrname == 'address' and 'address' in iface_dict:
if 'addresses' not in iface_dict:
iface_dict['addresses'] = []
iface_dict['addresses'].append(value)
else:
iface_dict[attrname] = value
elif attr in _REV_ETHTOOL_CONFIG_OPTS:
if 'ethtool' not in iface_dict:
iface_dict['ethtool'] = salt.utils.odict.OrderedDict()
iface_dict['ethtool'][attr] = valuestr
elif attr.startswith('bond'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bonding' not in iface_dict:
iface_dict['bonding'] = salt.utils.odict.OrderedDict()
iface_dict['bonding'][opt] = valuestr
elif attr.startswith('bridge'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bridging' not in iface_dict:
iface_dict['bridging'] = salt.utils.odict.OrderedDict()
iface_dict['bridging'][opt] = valuestr
elif attr in ['up', 'pre-up', 'post-up',
'down', 'pre-down', 'post-down']:
cmd = valuestr
cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr))
if cmd_key not in iface_dict:
iface_dict[cmd_key] = []
iface_dict[cmd_key].append(cmd)
elif line.startswith('auto'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['enabled'] = True
elif line.startswith('allow-hotplug'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['hotplug'] = True
elif line.startswith('source'):
if 'source' not in adapters:
adapters['source'] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters['source']:
adapters['source']['data'] = salt.utils.odict.OrderedDict()
adapters['source']['data']['sources'] = []
adapters['source']['data']['sources'].append(line.split()[1])
# Return a sorted list of the keys for bond, bridge and ethtool options to
# ensure a consistent order
for iface_name in adapters:
if iface_name == 'source':
continue
if 'data' not in adapters[iface_name]:
msg = 'Interface file malformed for interface: {0}.'.format(iface_name)
log.error(msg)
adapters.pop(iface_name)
continue
for opt in ['ethtool', 'bonding', 'bridging']:
for inet in ['inet', 'inet6']:
if inet in adapters[iface_name]['data']:
if opt in adapters[iface_name]['data'][inet]:
opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys())
adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys
return adapters
def _parse_ethtool_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
if 'autoneg' in opts:
if opts['autoneg'] in _CONFIG_TRUE:
config.update({'autoneg': 'on'})
elif opts['autoneg'] in _CONFIG_FALSE:
config.update({'autoneg': 'off'})
else:
_raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE)
if 'duplex' in opts:
valid = ['full', 'half']
if opts['duplex'] in valid:
config.update({'duplex': opts['duplex']})
else:
_raise_error_iface(iface, 'duplex', valid)
if 'speed' in opts:
valid = ['10', '100', '1000', '10000']
if six.text_type(opts['speed']) in valid:
config.update({'speed': opts['speed']})
else:
_raise_error_iface(iface, opts['speed'], valid)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'on'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'off'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_ethtool_pppoe_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
for opt in _DEB_CONFIG_PPPOE_OPTS:
if opt in opts:
config[opt] = opts[opt]
if 'provider' in opts and not opts['provider']:
_raise_error_iface(iface, 'provider', _CONFIG_TRUE + _CONFIG_FALSE)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('noipdefault', 'usepeerdns', 'defaultroute', 'hide-password', 'noauth', 'persist', 'noaccomp'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'True'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'False'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_settings_bond(opts, iface):
'''
Filters given options and outputs valid settings for requested
operation. If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond_def = {
# 803.ad aggregation selection logic
# 0 for stable (default)
# 1 for bandwidth
# 2 for count
'ad_select': '0',
# Max number of transmit queues (default = 16)
'tx_queues': '16',
# Link monitoring in milliseconds. Most NICs support this
'miimon': '100',
# ARP interval in milliseconds
'arp_interval': '250',
# Delay before considering link down in milliseconds (miimon * 2)
'downdelay': '200',
# lacp_rate 0: Slow - every 30 seconds
# lacp_rate 1: Fast - every 1 second
'lacp_rate': '0',
# Max bonds for this driver
'max_bonds': '1',
# Specifies the time, in milliseconds, to wait before
# enabling a slave after a link recovery has been
# detected. Only used with miimon.
'updelay': '0',
# Used with miimon.
# On: driver sends mii
# Off: ethtool sends mii
'use_carrier': 'on',
# Default. Don't change unless you know what you are doing.
'xmit_hash_policy': 'layer2',
}
if opts['mode'] in ['balance-rr', '0']:
log.info('Device: %s Bonding Mode: load balancing (round-robin)', iface)
return _parse_settings_bond_0(opts, iface, bond_def)
elif opts['mode'] in ['active-backup', '1']:
log.info('Device: %s Bonding Mode: fault-tolerance (active-backup)', iface)
return _parse_settings_bond_1(opts, iface, bond_def)
elif opts['mode'] in ['balance-xor', '2']:
log.info('Device: %s Bonding Mode: load balancing (xor)', iface)
return _parse_settings_bond_2(opts, iface, bond_def)
elif opts['mode'] in ['broadcast', '3']:
log.info('Device: %s Bonding Mode: fault-tolerance (broadcast)', iface)
return _parse_settings_bond_3(opts, iface, bond_def)
elif opts['mode'] in ['802.3ad', '4']:
log.info('Device: %s Bonding Mode: IEEE 802.3ad Dynamic link '
'aggregation', iface)
return _parse_settings_bond_4(opts, iface, bond_def)
elif opts['mode'] in ['balance-tlb', '5']:
log.info('Device: %s Bonding Mode: transmit load balancing', iface)
return _parse_settings_bond_5(opts, iface, bond_def)
elif opts['mode'] in ['balance-alb', '6']:
log.info('Device: %s Bonding Mode: adaptive load balancing', iface)
return _parse_settings_bond_6(opts, iface, bond_def)
else:
valid = [
'0', '1', '2', '3', '4', '5', '6',
'balance-rr', 'active-backup', 'balance-xor',
'broadcast', '802.3ad', 'balance-tlb', 'balance-alb'
]
_raise_error_iface(iface, 'mode', valid)
def _parse_settings_bond_0(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond0.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '0'}
# ARP targets in n.n.n.n form
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
return bond
def _parse_settings_bond_1(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '1'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
if not (__grains__['os'] == "Ubuntu" and __grains__['osrelease_info'][0] >= 16):
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_2(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond2.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '2'}
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_3(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond3.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '3'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_4(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond4.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '4'}
for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']:
if binding in opts:
if binding == 'lacp_rate':
if opts[binding] == 'fast':
opts.update({binding: '1'})
if opts[binding] == 'slow':
opts.update({binding: '0'})
valid = ['fast', '1', 'slow', '0']
else:
valid = ['integer']
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, valid)
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_5(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond5.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '5'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_settings_bond_6(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond6.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '6'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_bridge_opts(opts, iface):
'''
Filters given options and outputs valid settings for BRIDGING_OPTS
If an option has a value that is not expected, this
function will log the Interface, Setting and what was expected.
'''
config = {}
if 'ports' in opts:
if isinstance(opts['ports'], list):
opts['ports'] = ' '.join(opts['ports'])
config.update({'ports': opts['ports']})
for opt in ['ageing', 'fd', 'gcint', 'hello', 'maxage']:
if opt in opts:
try:
float(opts[opt])
config.update({opt: opts[opt]})
except ValueError:
_raise_error_iface(iface, opt, ['float'])
for opt in ['bridgeprio', 'maxwait']:
if opt in opts:
if isinstance(opts[opt], int):
config.update({opt: opts[opt]})
else:
_raise_error_iface(iface, opt, ['integer'])
if 'hw' in opts:
# match 12 hex digits with either : or - as separators between pairs
if re.match('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$',
opts['hw'].lower()):
config.update({'hw': opts['hw']})
else:
_raise_error_iface(iface, 'hw', ['valid MAC address'])
for opt in ['pathcost', 'portprio']:
if opt in opts:
try:
port, cost_or_prio = opts[opt].split()
int(cost_or_prio)
config.update({opt: '{0} {1}'.format(port, cost_or_prio)})
except ValueError:
_raise_error_iface(iface, opt, ['interface integer'])
if 'stp' in opts:
if opts['stp'] in _CONFIG_TRUE:
config.update({'stp': 'on'})
elif opts['stp'] in _CONFIG_FALSE:
config.update({'stp': 'off'})
else:
_raise_error_iface(iface, 'stp', _CONFIG_TRUE + _CONFIG_FALSE)
if 'waitport' in opts:
if isinstance(opts['waitport'], int):
config.update({'waitport': opts['waitport']})
else:
values = opts['waitport'].split()
waitport_time = values.pop(0)
if waitport_time.isdigit() and values:
config.update({
'waitport': '{0} {1}'.format(
waitport_time, ' '.join(values)
)
})
else:
_raise_error_iface(iface, opt, ['integer [interfaces]'])
return config
def _parse_settings_eth(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['inet'] = salt.utils.odict.OrderedDict()
iface_data['inet6'] = salt.utils.odict.OrderedDict()
if enabled:
adapters[iface]['enabled'] = True
if opts.get('hotplug', False):
adapters[iface]['hotplug'] = True
if opts.get('enable_ipv6', None) and opts.get('iface_type', '') == 'vlan':
iface_data['inet6']['vlan_raw_device'] = (
re.sub(r'\.\d*', '', iface))
for addrfam in ['inet', 'inet6']:
if iface_type not in ['bridge']:
tmp_ethtool = _parse_ethtool_opts(opts, iface)
if tmp_ethtool:
ethtool = {}
for item in tmp_ethtool:
ethtool[_ETHTOOL_CONFIG_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['ethtool'] = ethtool
# return a list of sorted keys to ensure consistent order
iface_data[addrfam]['ethtool_keys'] = sorted(ethtool)
if iface_type == 'bridge':
bridging = _parse_bridge_opts(opts, iface)
if bridging:
iface_data[addrfam]['bridging'] = bridging
iface_data[addrfam]['bridging_keys'] = sorted(bridging)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'bond':
bonding = _parse_settings_bond(opts, iface)
if bonding:
iface_data[addrfam]['bonding'] = bonding
iface_data[addrfam]['bonding']['slaves'] = opts['slaves']
iface_data[addrfam]['bonding_keys'] = sorted(bonding)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'slave':
adapters[iface]['master'] = opts['master']
opts['proto'] = 'manual'
iface_data[addrfam]['master'] = adapters[iface]['master']
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'vlan':
iface_data[addrfam]['vlan_raw_device'] = re.sub(r'\.\d*', '', iface)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'pppoe':
tmp_ethtool = _parse_ethtool_pppoe_opts(opts, iface)
if tmp_ethtool:
for item in tmp_ethtool:
adapters[iface]['data'][addrfam][_DEB_CONFIG_PPPOE_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['addrfam'] = addrfam
opts.pop('mode', None)
for opt, val in opts.items():
inet = None
if opt.startswith('ipv4'):
opt = opt[4:]
inet = 'inet'
iface_data['inet']['addrfam'] = 'inet'
elif opt.startswith('ipv6'):
iface_data['inet6']['addrfam'] = 'inet6'
opt = opt[4:]
inet = 'inet6'
elif opt in ['ipaddr', 'address', 'ipaddresses', 'addresses', 'gateway', 'proto']:
iface_data['inet']['addrfam'] = 'inet'
inet = 'inet'
_opt = SALT_ATTR_TO_DEBIAN_ATTR_MAP.get(opt, opt)
_debopt = _opt.replace('-', '_')
for addrfam in ['inet', 'inet6']:
(valid, value, errmsg) = _validate_interface_option(_opt, val, addrfam=addrfam)
if not valid:
continue
if inet is None and _debopt not in iface_data[addrfam]:
iface_data[addrfam][_debopt] = value
elif inet == addrfam:
iface_data[addrfam][_debopt] = value
for opt in ['up_cmds', 'pre_up_cmds', 'post_up_cmds',
'down_cmds', 'pre_down_cmds', 'post_down_cmds']:
if opt in opts:
iface_data['inet'][opt] = opts[opt]
iface_data['inet6'][opt] = opts[opt]
# Remove incomplete/disabled inet blocks
for (addrfam, opt) in [('inet', 'enable_ipv4'), ('inet6', 'enable_ipv6')]:
if opts.get(opt, None) is False:
iface_data.pop(addrfam)
elif iface_data[addrfam].get('addrfam', '') != addrfam:
iface_data.pop(addrfam)
return adapters
def _parse_settings_source(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['sources'] = [opts['source']]
return adapters
def _parse_network_settings(opts, current):
'''
Filters given options and outputs valid settings for
the global network settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
current = dict((k.lower(), v) for (k, v) in six.iteritems(current))
result = {}
valid = _CONFIG_TRUE + _CONFIG_FALSE
if 'enabled' not in opts:
try:
opts['networking'] = current['networking']
_log_default_network('networking', current['networking'])
except ValueError:
_raise_error_network('networking', valid)
else:
opts['networking'] = opts['enabled']
if opts['networking'] in valid:
if opts['networking'] in _CONFIG_TRUE:
result['networking'] = 'yes'
elif opts['networking'] in _CONFIG_FALSE:
result['networking'] = 'no'
else:
_raise_error_network('networking', valid)
if 'hostname' not in opts:
try:
opts['hostname'] = current['hostname']
_log_default_network('hostname', current['hostname'])
except ValueError:
_raise_error_network('hostname', ['server1.example.com'])
if opts['hostname']:
result['hostname'] = opts['hostname']
else:
_raise_error_network('hostname', ['server1.example.com'])
if 'search' in opts:
result['search'] = opts['search']
return result
def _parse_routes(iface, opts):
'''
Filters given options and outputs valid settings for
the route settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
result = {}
if 'routes' not in opts:
_raise_error_routes(iface, 'routes', 'List of routes')
for opt in opts:
result[opt] = opts[opt]
return result
def _write_file(iface, data, folder, pattern):
'''
Writes a file to disk
'''
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
return filename
def _write_file_routes(iface, data, folder, pattern):
'''
Writes a file to disk
'''
# ifup / ifdown is executing given folder via run-parts.
# according to run-parts man-page, only filenames with this pattern are
# executed: (^[a-zA-Z0-9_-]+$)
# In order to make the routes file work for vlan interfaces
# (default would have been in example /etc/network/if-up.d/route-bond0.12)
# these dots in the iface name need to be replaced by underscores, so it
# can be executed by run-parts
iface = iface.replace('.', '_')
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
__salt__['file.set_mode'](filename, '0755')
return filename
def _write_file_network(data, filename, create=False):
'''
Writes a file to disk
If file does not exist, only create if create
argument is True
'''
if not os.path.exists(filename) and not create:
msg = '{0} cannot be written. {0} does not exist\
and create is set to False'
msg = msg.format(filename)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
def _read_temp(data):
'''
Return what would be written to disk
'''
tout = StringIO()
tout.write(data)
tout.seek(0)
output = tout.readlines()
tout.close()
return output
def _read_temp_ifaces(iface, data):
'''
Return what would be written to disk for interfaces
'''
try:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': data})
# Return as an array so the difflib works
return [item + '\n' for item in ifcfg.split('\n')]
def _write_file_ifaces(iface, data, **settings):
'''
Writes a file to disk
'''
try:
eth_template = JINJA.get_template('debian_eth.jinja')
source_template = JINJA.get_template('debian_source.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
# Read /etc/network/interfaces into a dict
adapters = _parse_interfaces()
# Apply supplied settings over on-disk settings
adapters[iface] = data
ifcfg = ''
for adapter in adapters:
if 'type' in adapters[adapter] and adapters[adapter]['type'] == 'source':
tmp = source_template.render({'name': adapter, 'data': adapters[adapter]})
else:
tmp = eth_template.render({'name': adapter, 'data': adapters[adapter]})
ifcfg = ifcfg + tmp
if adapter == iface:
saved_ifcfg = tmp
_SEPARATE_FILE = False
if 'filename' in settings:
if not settings['filename'].startswith('/'):
filename = '{0}/{1}'.format(_DEB_NETWORK_DIR, settings['filename'])
else:
filename = settings['filename']
_SEPARATE_FILE = True
else:
if 'filename' in adapters[adapter]['data']:
filename = adapters[adapter]['data']
else:
filename = _DEB_NETWORK_FILE
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
if _SEPARATE_FILE:
fout.write(salt.utils.stringutils.to_str(saved_ifcfg))
else:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return saved_ifcfg.split('\n')
def _write_file_ppp_ifaces(iface, data):
'''
Writes a file to disk
'''
try:
template = JINJA.get_template('debian_ppp_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_ppp_eth.jinja')
return ''
adapters = _parse_interfaces()
adapters[iface] = data
ifcfg = ''
tmp = template.render({'data': adapters[iface]})
ifcfg = tmp + ifcfg
filename = _DEB_PPP_DIR + '/' + adapters[iface]['data']['inet']['provider']
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.fopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return filename
def build_bond(iface, **settings):
'''
Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb
'''
deb_major = __grains__['osrelease'][:1]
opts = _parse_settings_bond(settings, iface)
try:
template = JINJA.get_template('conf.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template conf.jinja')
return ''
data = template.render({'name': iface, 'bonding': opts})
if 'test' in settings and settings['test']:
return _read_temp(data)
_write_file(iface, data, _DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
if deb_major == '5':
for line_type in ('alias', 'options'):
cmd = ['sed', '-i', '-e', r'/^{0}\s{1}.*/d'.format(line_type, iface),
'/etc/modprobe.conf']
__salt__['cmd.run'](cmd, python_shell=False)
__salt__['file.append']('/etc/modprobe.conf', path)
# Load kernel module
__salt__['kmod.load']('bonding')
# install ifenslave-2.6
__salt__['pkg.install']('ifenslave-2.6')
return _read_file(path)
def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'vlan':
settings['vlan'] = 'yes'
__salt__['pkg.install']('vlan')
elif iface_type == 'pppoe':
settings['pppoe'] = 'yes'
if not __salt__['pkg.version']('ppp'):
inst = __salt__['pkg.install']('ppp')
elif iface_type == 'bond':
if 'slaves' not in settings:
msg = 'slaves is a required setting for bond interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'bridge':
if 'ports' not in settings:
msg = (
'ports is a required setting for bridge interfaces on Debian '
'or Ubuntu based systems'
)
log.error(msg)
raise AttributeError(msg)
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'pppoe']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
if iface_type in ['source']:
opts = _parse_settings_source(settings, iface_type, enabled, iface)
if 'test' in settings and settings['test']:
return _read_temp_ifaces(iface, opts[iface])
ifcfg = _write_file_ifaces(iface, opts[iface], **settings)
if iface_type == 'pppoe':
_write_file_ppp_ifaces(iface, opts[iface])
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg]
def build_routes(iface, **settings):
'''
Add route scripts for a network interface using up commands.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
'''
opts = _parse_routes(iface, settings)
try:
template = JINJA.get_template('route_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template route_eth.jinja')
return ''
add_routecfg = template.render(route_type='add',
routes=opts['routes'],
iface=iface)
del_routecfg = template.render(route_type='del',
routes=opts['routes'],
iface=iface)
if 'test' in settings and settings['test']:
return _read_temp(add_routecfg + del_routecfg)
filename = _write_file_routes(iface,
add_routecfg,
_DEB_NETWORK_UP_DIR,
'route-{0}')
results = _read_file(filename)
filename = _write_file_routes(iface,
del_routecfg,
_DEB_NETWORK_DOWN_DIR,
'route-{0}')
results += _read_file(filename)
return results
def down(iface, iface_type):
'''
Shutdown a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.down eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought down.
if iface_type not in ['slave', 'source']:
return __salt__['cmd.run'](['ifdown', iface])
return None
def get_bond(iface):
'''
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
'''
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
return _read_file(path)
def get_interface(iface):
'''
Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
adapters = _parse_interfaces()
if iface in adapters:
try:
if iface == 'source':
template = JINJA.get_template('debian_source.jinja')
else:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': adapters[iface]})
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg.split('\n')]
else:
return []
def up(iface, iface_type): # pylint: disable=C0103
'''
Start up a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.up eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought up.
if iface_type not in ('slave', 'source'):
return __salt__['cmd.run'](['ifup', iface])
return None
def get_network_settings():
'''
Return the contents of the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_network_settings
'''
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
settings = {}
if __salt__['service.available']('networking'):
if __salt__['service.status']('networking'):
settings['networking'] = "yes"
else:
settings['networking'] = "no"
else:
settings['networking'] = "no"
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
settings['hostname'] = hostname
settings['domainname'] = domainname
settings['searchdomain'] = searchdomain
else:
settings = _parse_current_network_settings()
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(settings)
return _read_temp(network)
def get_routes(iface):
'''
Return the routes for the interface
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0
'''
filename = os.path.join(_DEB_NETWORK_UP_DIR, 'route-{0}'.format(iface))
results = _read_file(filename)
filename = os.path.join(_DEB_NETWORK_DOWN_DIR, 'route-{0}'.format(iface))
results += _read_file(filename)
return results
def apply_network_settings(**settings):
'''
Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings
'''
if 'require_reboot' not in settings:
settings['require_reboot'] = False
if 'apply_hostname' not in settings:
settings['apply_hostname'] = False
hostname_res = True
if settings['apply_hostname'] in _CONFIG_TRUE:
if 'hostname' in settings:
hostname_res = __salt__['network.mod_hostname'](settings['hostname'])
else:
log.warning(
'The network state sls is trying to apply hostname '
'changes but no hostname is defined.'
)
hostname_res = False
res = True
if settings['require_reboot'] in _CONFIG_TRUE:
log.warning(
'The network state sls is requiring a reboot of the system to '
'properly apply network configuration.'
)
res = True
else:
stop = __salt__['service.stop']('networking')
time.sleep(2)
res = stop and __salt__['service.start']('networking')
return hostname_res and res
def build_network_settings(**settings):
'''
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
'''
changes = []
# Read current configuration and store default values
current_network_settings = _parse_current_network_settings()
# Build settings
opts = _parse_network_settings(settings, current_network_settings)
# Ubuntu has moved away from /etc/default/networking
# beginning with the 12.04 release so we disable or enable
# the networking related services on boot
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
if opts['networking'] == 'yes':
service_cmd = 'service.enable'
else:
service_cmd = 'service.disable'
if __salt__['service.available']('NetworkManager'):
__salt__[service_cmd]('NetworkManager')
if __salt__['service.available']('networking'):
__salt__[service_cmd]('networking')
else:
try:
template = JINJA.get_template('network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template network.jinja')
return ''
network = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(network)
# Write settings
_write_file_network(network, _DEB_NETWORKING_FILE, True)
# Get hostname and domain from opts
sline = opts['hostname'].split('.', 1)
opts['hostname'] = sline[0]
current_domainname = current_network_settings['domainname']
current_searchdomain = current_network_settings['searchdomain']
new_domain = False
if len(sline) > 1:
new_domainname = sline[1]
if new_domainname != current_domainname:
domainname = new_domainname
opts['domainname'] = new_domainname
new_domain = True
else:
domainname = current_domainname
opts['domainname'] = domainname
else:
domainname = current_domainname
opts['domainname'] = domainname
new_search = False
if 'search' in opts:
new_searchdomain = opts['search']
if new_searchdomain != current_searchdomain:
searchdomain = new_searchdomain
opts['searchdomain'] = new_searchdomain
new_search = True
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
# If the domain changes, then we should write the resolv.conf file.
if new_domain or new_search:
# Look for existing domain line and update if necessary
resolve = _parse_resolve()
domain_prog = re.compile(r'domain\s+')
search_prog = re.compile(r'search\s+')
new_contents = []
for item in _read_file(_DEB_RESOLV_FILE):
if domain_prog.match(item):
item = 'domain {0}'.format(domainname)
elif search_prog.match(item):
item = 'search {0}'.format(searchdomain)
new_contents.append(item)
# A domain line didn't exist so we'll add one in
# with the new domainname
if 'domain' not in resolve:
new_contents.insert(0, 'domain {0}' . format(domainname))
# A search line didn't exist so we'll add one in
# with the new search domain
if 'search' not in resolve:
new_contents.insert('domain' in resolve, 'search {0}'.format(searchdomain))
new_resolv = '\n'.join(new_contents)
# Write /etc/resolv.conf
if not ('test' in settings and settings['test']):
_write_file_network(new_resolv, _DEB_RESOLV_FILE)
# used for returning the results back
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(opts)
changes.extend(_read_temp(network))
return changes
|
saltstack/salt
|
salt/modules/debian_ip.py
|
_raise_error_network
|
python
|
def _raise_error_network(option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_network(option, expected)
log.error(msg)
raise AttributeError(msg)
|
Log and raise an error with a logical formatted message.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_ip.py#L202-L208
| null |
# -*- coding: utf-8 -*-
'''
The networking module for Debian-based distros
References:
* http://www.debian.org/doc/manuals/debian-reference/ch05.en.html
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import functools
import logging
import os.path
import os
import re
import time
# Import third party libs
import jinja2
import jinja2.exceptions
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error,no-name-in-module
# Import salt libs
import salt.utils.dns
import salt.utils.files
import salt.utils.odict
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.validate.net
# Set up logging
log = logging.getLogger(__name__)
# Set up template environment
JINJA = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'debian_ip')
)
)
# Define the module's virtual name
__virtualname__ = 'ip'
def __virtual__():
'''
Confine this module to Debian-based distros
'''
if __grains__['os_family'] == 'Debian':
return __virtualname__
return (False, 'The debian_ip module could not be loaded: '
'unsupported OS family')
_ETHTOOL_CONFIG_OPTS = {
'speed': 'link-speed',
'duplex': 'link-duplex',
'autoneg': 'ethernet-autoneg',
'ethernet-port': 'ethernet-port',
'wol': 'ethernet-wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'rx': 'offload-rx',
'tx': 'offload-tx',
'sg': 'offload-sg',
'tso': 'offload-tso',
'ufo': 'offload-ufo',
'gso': 'offload-gso',
'gro': 'offload-gro',
'lro': 'offload-lro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_REV_ETHTOOL_CONFIG_OPTS = {
'link-speed': 'speed',
'link-duplex': 'duplex',
'ethernet-autoneg': 'autoneg',
'ethernet-port': 'ethernet-port',
'ethernet-wol': 'wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'offload-rx': 'rx',
'offload-tx': 'tx',
'offload-sg': 'sg',
'offload-tso': 'tso',
'offload-ufo': 'ufo',
'offload-gso': 'gso',
'offload-lro': 'lro',
'offload-gro': 'gro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_DEB_CONFIG_PPPOE_OPTS = {
'user': 'user',
'password': 'password',
'provider': 'provider',
'pppoe_iface': 'pppoe_iface',
'noipdefault': 'noipdefault',
'usepeerdns': 'usepeerdns',
'defaultroute': 'defaultroute',
'holdoff': 'holdoff',
'maxfail': 'maxfail',
'hide-password': 'hide-password',
'lcp-echo-interval': 'lcp-echo-interval',
'lcp-echo-failure': 'lcp-echo-failure',
'connect': 'connect',
'noauth': 'noauth',
'persist': 'persist',
'mtu': 'mtu',
'noaccomp': 'noaccomp',
'linkname': 'linkname',
}
_DEB_ROUTES_FILE = '/etc/network/routes'
_DEB_NETWORK_FILE = '/etc/network/interfaces'
_DEB_NETWORK_DIR = '/etc/network/interfaces.d/'
_DEB_NETWORK_UP_DIR = '/etc/network/if-up.d/'
_DEB_NETWORK_DOWN_DIR = '/etc/network/if-down.d/'
_DEB_NETWORK_CONF_FILES = '/etc/modprobe.d/'
_DEB_NETWORKING_FILE = '/etc/default/networking'
_DEB_HOSTNAME_FILE = '/etc/hostname'
_DEB_RESOLV_FILE = '/etc/resolv.conf'
_DEB_PPP_DIR = '/etc/ppp/peers/'
_CONFIG_TRUE = ['yes', 'on', 'true', '1', True]
_CONFIG_FALSE = ['no', 'off', 'false', '0', False]
_IFACE_TYPES = [
'eth', 'bond', 'alias', 'clone',
'ipsec', 'dialup', 'bridge', 'slave',
'vlan', 'pppoe', 'source',
]
def _error_msg_iface(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, '|'.join(str(e) for e in expected))
def _error_msg_routes(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, expected)
def _log_default_iface(iface, opt, value):
log.info(
'Using default option -- Interface: %s Option: %s Value: %s',
iface, opt, value
)
def _error_msg_network(option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]'
return msg.format(option, '|'.join(str(e) for e in expected))
def _log_default_network(opt, value):
log.info('Using existing setting -- Setting: %s Value: %s', opt, value)
def _raise_error_iface(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_iface(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_routes(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_routes(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _read_file(path):
'''
Reads and returns the contents of a text file
'''
try:
with salt.utils.files.flopen(path, 'rb') as contents:
return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]
except (OSError, IOError):
return ''
def _parse_resolve():
'''
Parse /etc/resolv.conf
'''
return salt.utils.dns.parse_resolv(_DEB_RESOLV_FILE)
def _parse_domainname():
'''
Parse /etc/resolv.conf and return domainname
'''
return _parse_resolve().get('domain', '')
def _parse_searchdomain():
'''
Parse /etc/resolv.conf and return searchdomain
'''
return _parse_resolve().get('search', '')
def _parse_hostname():
'''
Parse /etc/hostname and return hostname
'''
contents = _read_file(_DEB_HOSTNAME_FILE)
if contents:
return contents[0].split('\n')[0]
else:
return ''
def _parse_current_network_settings():
'''
Parse /etc/default/networking and return current configuration
'''
opts = salt.utils.odict.OrderedDict()
opts['networking'] = ''
if os.path.isfile(_DEB_NETWORKING_FILE):
with salt.utils.files.fopen(_DEB_NETWORKING_FILE) as contents:
for line in contents:
salt.utils.stringutils.to_unicode(line)
if line.startswith('#'):
continue
elif line.startswith('CONFIGURE_INTERFACES'):
opts['networking'] = line.split('=', 1)[1].strip()
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
opts['hostname'] = hostname
opts['domainname'] = domainname
opts['searchdomain'] = searchdomain
return opts
# def __validator_func(value):
# return (valid: True/False, (transformed) value, error message)
def __ipv4_quad(value):
'''validate an IPv4 address'''
return (salt.utils.validate.net.ipv4_addr(value), value,
'dotted IPv4 address')
def __ipv6(value):
'''validate an IPv6 address'''
return (salt.utils.validate.net.ipv6_addr(value), value,
'IPv6 address')
def __mac(value):
'''validate a mac address'''
return (salt.utils.validate.net.mac(value), value,
'MAC address')
def __anything(value):
return (True, value, None)
def __int(value):
'''validate an integer'''
valid, _value = False, value
try:
_value = int(value)
valid = True
except ValueError:
pass
return (valid, _value, 'integer')
def __float(value):
'''validate a float'''
valid, _value = False, value
try:
_value = float(value)
valid = True
except ValueError:
pass
return (valid, _value, 'float')
def __ipv4_netmask(value):
'''validate an IPv4 dotted quad or integer CIDR netmask'''
valid, errmsg = False, 'dotted quad or integer CIDR (0->32)'
valid, value, _ = __int(value)
if not (valid and 0 <= value <= 32):
valid = salt.utils.validate.net.netmask(value)
return (valid, value, errmsg)
def __ipv6_netmask(value):
'''validate an IPv6 integer netmask'''
valid, errmsg = False, 'IPv6 netmask (0->128)'
valid, value, _ = __int(value)
valid = (valid and 0 <= value <= 128)
return (valid, value, errmsg)
def __within2(value, within=None, errmsg=None, dtype=None):
'''validate that a value is in ``within`` and optionally a ``dtype``'''
valid, _value = False, value
if dtype:
try:
_value = dtype(value) # TODO: this is a bit loose when dtype is a class
valid = _value in within
except ValueError:
pass
else:
valid = _value in within
if errmsg is None:
if dtype:
typename = getattr(dtype, '__name__',
hasattr(dtype, '__class__')
and getattr(dtype.__class__, 'name', dtype))
errmsg = '{0} within \'{1}\''.format(typename, within)
else:
errmsg = 'within \'{0}\''.format(within)
return (valid, _value, errmsg)
def __within(within=None, errmsg=None, dtype=None):
return functools.partial(__within2, within=within,
errmsg=errmsg, dtype=dtype)
def __space_delimited_list(value):
'''validate that a value contains one or more space-delimited values'''
if isinstance(value, six.string_types):
value = value.strip().split()
if hasattr(value, '__iter__') and value != []:
return (True, value, 'space-delimited string')
else:
return (False, value, '{0} is not a valid space-delimited value.\n'.format(value))
SALT_ATTR_TO_DEBIAN_ATTR_MAP = {
'dns': 'dns-nameservers',
'search': 'dns-search',
'hwaddr': 'hwaddress', # TODO: this limits bootp functionality
'ipaddr': 'address',
'ipaddrs': 'addresses',
}
DEBIAN_ATTR_TO_SALT_ATTR_MAP = dict(
(v, k) for (k, v) in six.iteritems(SALT_ATTR_TO_DEBIAN_ATTR_MAP))
# TODO
DEBIAN_ATTR_TO_SALT_ATTR_MAP['address'] = 'address'
DEBIAN_ATTR_TO_SALT_ATTR_MAP['hwaddress'] = 'hwaddress'
IPV4_VALID_PROTO = ['bootp', 'dhcp', 'static', 'manual', 'loopback', 'ppp']
IPV4_ATTR_MAP = {
'proto': __within(IPV4_VALID_PROTO, dtype=six.text_type),
# ipv4 static & manual
'address': __ipv4_quad,
'addresses': __anything,
'netmask': __ipv4_netmask,
'broadcast': __ipv4_quad,
'metric': __int,
'gateway': __ipv4_quad, # supports a colon-delimited list
'pointopoint': __ipv4_quad,
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'link', 'host'], dtype=six.text_type),
# dhcp
'hostname': __anything,
'leasehours': __int,
'leasetime': __int,
'vendor': __anything,
'client': __anything,
# bootp
'bootfile': __anything,
'server': __ipv4_quad,
'hwaddr': __mac,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'dstaddr': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# bond
'slaves': __anything,
# ppp
'provider': __anything,
'unit': __int,
'options': __anything,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
#
'network': __anything, # i don't know what this is
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
IPV6_VALID_PROTO = ['auto', 'loopback', 'static', 'manual',
'dhcp', 'v4tunnel', '6to4']
IPV6_ATTR_MAP = {
'proto': __within(IPV6_VALID_PROTO),
# ipv6 static & manual
'address': __ipv6,
'addresses': __anything,
'netmask': __ipv6_netmask,
'broadcast': __ipv6,
'gateway': __ipv6, # supports a colon-delimited list
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'site', 'link', 'host'], dtype=six.text_type),
# inet6 auto
'privext': __within([0, 1, 2], dtype=int),
'dhcp': __within([0, 1], dtype=int),
# inet6 static & manual & dhcp
'media': __anything,
'accept_ra': __within([0, 1], dtype=int),
'autoconf': __within([0, 1], dtype=int),
'preferred-lifetime': __int,
'dad-attempts': __int, # 0 to disable
'dad-interval': __float,
# bond
'slaves': __anything,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
WIRELESS_ATTR_MAP = {
'wireless-essid': __anything,
'wireless-mode': __anything, # TODO
'wpa-ap-scan': __within([0, 1, 2], dtype=int), # TODO
'wpa-conf': __anything,
'wpa-driver': __anything,
'wpa-group': __anything,
'wpa-key-mgmt': __anything,
'wpa-pairwise': __anything,
'wpa-psk': __anything,
'wpa-proto': __anything, # partial(__within,
'wpa-roam': __anything,
'wpa-ssid': __anything, # TODO
}
ATTRMAPS = {
'inet': [IPV4_ATTR_MAP, WIRELESS_ATTR_MAP],
'inet6': [IPV6_ATTR_MAP, WIRELESS_ATTR_MAP]
}
def _validate_interface_option(attr, value, addrfam='inet'):
'''lookup the validation function for a [addrfam][attr] and
return the results
:param attr: attribute name
:param value: raw setting value
:param addrfam: address family (inet, inet6,
'''
valid, _value, errmsg = False, value, 'Unknown validator'
attrmaps = ATTRMAPS.get(addrfam, [])
for attrmap in attrmaps:
if attr in attrmap:
validate_func = attrmap[attr]
(valid, _value, errmsg) = validate_func(value)
break
return (valid, _value, errmsg)
def _attrmaps_contain_attr(attr):
return (
attr in WIRELESS_ATTR_MAP or
attr in IPV4_ATTR_MAP or
attr in IPV6_ATTR_MAP)
def _parse_interfaces(interface_files=None):
'''
Parse /etc/network/interfaces and return current configured interfaces
'''
if interface_files is None:
interface_files = []
# Add this later.
if os.path.exists(_DEB_NETWORK_DIR):
interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]
if os.path.isfile(_DEB_NETWORK_FILE):
interface_files.insert(0, _DEB_NETWORK_FILE)
adapters = salt.utils.odict.OrderedDict()
method = -1
for interface_file in interface_files:
with salt.utils.files.fopen(interface_file) as interfaces:
# This ensures iface_dict exists, but does not ensure we're not reading a new interface.
iface_dict = {}
for line in interfaces:
line = salt.utils.stringutils.to_unicode(line)
# Identify the clauses by the first word of each line.
# Go to the next line if the current line is a comment
# or all spaces.
if line.lstrip().startswith('#') or line.isspace():
continue
# Parse the iface clause
if line.startswith('iface'):
sline = line.split()
if len(sline) != 4:
msg = 'Interface file malformed: {0}.'
msg = msg.format(sline)
log.error(msg)
raise AttributeError(msg)
iface_name = sline[1]
addrfam = sline[2]
method = sline[3]
# Create item in dict, if not already there
if iface_name not in adapters:
adapters[iface_name] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters[iface_name]:
adapters[iface_name]['data'] = salt.utils.odict.OrderedDict()
if addrfam not in adapters[iface_name]['data']:
adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict()
iface_dict = adapters[iface_name]['data'][addrfam]
iface_dict['addrfam'] = addrfam
iface_dict['proto'] = method
iface_dict['filename'] = interface_file
# Parse the detail clauses.
elif line[0].isspace():
sline = line.split()
# conf file attr: dns-nameservers
# salt states.network attr: dns
attr, valuestr = line.rstrip().split(None, 1)
if _attrmaps_contain_attr(attr):
if '-' in attr:
attrname = attr.replace('-', '_')
else:
attrname = attr
(valid, value, errmsg) = _validate_interface_option(
attr, valuestr, addrfam)
if attrname == 'address' and 'address' in iface_dict:
if 'addresses' not in iface_dict:
iface_dict['addresses'] = []
iface_dict['addresses'].append(value)
else:
iface_dict[attrname] = value
elif attr in _REV_ETHTOOL_CONFIG_OPTS:
if 'ethtool' not in iface_dict:
iface_dict['ethtool'] = salt.utils.odict.OrderedDict()
iface_dict['ethtool'][attr] = valuestr
elif attr.startswith('bond'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bonding' not in iface_dict:
iface_dict['bonding'] = salt.utils.odict.OrderedDict()
iface_dict['bonding'][opt] = valuestr
elif attr.startswith('bridge'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bridging' not in iface_dict:
iface_dict['bridging'] = salt.utils.odict.OrderedDict()
iface_dict['bridging'][opt] = valuestr
elif attr in ['up', 'pre-up', 'post-up',
'down', 'pre-down', 'post-down']:
cmd = valuestr
cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr))
if cmd_key not in iface_dict:
iface_dict[cmd_key] = []
iface_dict[cmd_key].append(cmd)
elif line.startswith('auto'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['enabled'] = True
elif line.startswith('allow-hotplug'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['hotplug'] = True
elif line.startswith('source'):
if 'source' not in adapters:
adapters['source'] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters['source']:
adapters['source']['data'] = salt.utils.odict.OrderedDict()
adapters['source']['data']['sources'] = []
adapters['source']['data']['sources'].append(line.split()[1])
# Return a sorted list of the keys for bond, bridge and ethtool options to
# ensure a consistent order
for iface_name in adapters:
if iface_name == 'source':
continue
if 'data' not in adapters[iface_name]:
msg = 'Interface file malformed for interface: {0}.'.format(iface_name)
log.error(msg)
adapters.pop(iface_name)
continue
for opt in ['ethtool', 'bonding', 'bridging']:
for inet in ['inet', 'inet6']:
if inet in adapters[iface_name]['data']:
if opt in adapters[iface_name]['data'][inet]:
opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys())
adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys
return adapters
def _parse_ethtool_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
if 'autoneg' in opts:
if opts['autoneg'] in _CONFIG_TRUE:
config.update({'autoneg': 'on'})
elif opts['autoneg'] in _CONFIG_FALSE:
config.update({'autoneg': 'off'})
else:
_raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE)
if 'duplex' in opts:
valid = ['full', 'half']
if opts['duplex'] in valid:
config.update({'duplex': opts['duplex']})
else:
_raise_error_iface(iface, 'duplex', valid)
if 'speed' in opts:
valid = ['10', '100', '1000', '10000']
if six.text_type(opts['speed']) in valid:
config.update({'speed': opts['speed']})
else:
_raise_error_iface(iface, opts['speed'], valid)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'on'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'off'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_ethtool_pppoe_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
for opt in _DEB_CONFIG_PPPOE_OPTS:
if opt in opts:
config[opt] = opts[opt]
if 'provider' in opts and not opts['provider']:
_raise_error_iface(iface, 'provider', _CONFIG_TRUE + _CONFIG_FALSE)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('noipdefault', 'usepeerdns', 'defaultroute', 'hide-password', 'noauth', 'persist', 'noaccomp'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'True'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'False'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_settings_bond(opts, iface):
'''
Filters given options and outputs valid settings for requested
operation. If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond_def = {
# 803.ad aggregation selection logic
# 0 for stable (default)
# 1 for bandwidth
# 2 for count
'ad_select': '0',
# Max number of transmit queues (default = 16)
'tx_queues': '16',
# Link monitoring in milliseconds. Most NICs support this
'miimon': '100',
# ARP interval in milliseconds
'arp_interval': '250',
# Delay before considering link down in milliseconds (miimon * 2)
'downdelay': '200',
# lacp_rate 0: Slow - every 30 seconds
# lacp_rate 1: Fast - every 1 second
'lacp_rate': '0',
# Max bonds for this driver
'max_bonds': '1',
# Specifies the time, in milliseconds, to wait before
# enabling a slave after a link recovery has been
# detected. Only used with miimon.
'updelay': '0',
# Used with miimon.
# On: driver sends mii
# Off: ethtool sends mii
'use_carrier': 'on',
# Default. Don't change unless you know what you are doing.
'xmit_hash_policy': 'layer2',
}
if opts['mode'] in ['balance-rr', '0']:
log.info('Device: %s Bonding Mode: load balancing (round-robin)', iface)
return _parse_settings_bond_0(opts, iface, bond_def)
elif opts['mode'] in ['active-backup', '1']:
log.info('Device: %s Bonding Mode: fault-tolerance (active-backup)', iface)
return _parse_settings_bond_1(opts, iface, bond_def)
elif opts['mode'] in ['balance-xor', '2']:
log.info('Device: %s Bonding Mode: load balancing (xor)', iface)
return _parse_settings_bond_2(opts, iface, bond_def)
elif opts['mode'] in ['broadcast', '3']:
log.info('Device: %s Bonding Mode: fault-tolerance (broadcast)', iface)
return _parse_settings_bond_3(opts, iface, bond_def)
elif opts['mode'] in ['802.3ad', '4']:
log.info('Device: %s Bonding Mode: IEEE 802.3ad Dynamic link '
'aggregation', iface)
return _parse_settings_bond_4(opts, iface, bond_def)
elif opts['mode'] in ['balance-tlb', '5']:
log.info('Device: %s Bonding Mode: transmit load balancing', iface)
return _parse_settings_bond_5(opts, iface, bond_def)
elif opts['mode'] in ['balance-alb', '6']:
log.info('Device: %s Bonding Mode: adaptive load balancing', iface)
return _parse_settings_bond_6(opts, iface, bond_def)
else:
valid = [
'0', '1', '2', '3', '4', '5', '6',
'balance-rr', 'active-backup', 'balance-xor',
'broadcast', '802.3ad', 'balance-tlb', 'balance-alb'
]
_raise_error_iface(iface, 'mode', valid)
def _parse_settings_bond_0(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond0.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '0'}
# ARP targets in n.n.n.n form
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
return bond
def _parse_settings_bond_1(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '1'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
if not (__grains__['os'] == "Ubuntu" and __grains__['osrelease_info'][0] >= 16):
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_2(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond2.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '2'}
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_3(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond3.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '3'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_4(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond4.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '4'}
for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']:
if binding in opts:
if binding == 'lacp_rate':
if opts[binding] == 'fast':
opts.update({binding: '1'})
if opts[binding] == 'slow':
opts.update({binding: '0'})
valid = ['fast', '1', 'slow', '0']
else:
valid = ['integer']
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, valid)
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_5(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond5.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '5'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_settings_bond_6(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond6.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '6'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_bridge_opts(opts, iface):
'''
Filters given options and outputs valid settings for BRIDGING_OPTS
If an option has a value that is not expected, this
function will log the Interface, Setting and what was expected.
'''
config = {}
if 'ports' in opts:
if isinstance(opts['ports'], list):
opts['ports'] = ' '.join(opts['ports'])
config.update({'ports': opts['ports']})
for opt in ['ageing', 'fd', 'gcint', 'hello', 'maxage']:
if opt in opts:
try:
float(opts[opt])
config.update({opt: opts[opt]})
except ValueError:
_raise_error_iface(iface, opt, ['float'])
for opt in ['bridgeprio', 'maxwait']:
if opt in opts:
if isinstance(opts[opt], int):
config.update({opt: opts[opt]})
else:
_raise_error_iface(iface, opt, ['integer'])
if 'hw' in opts:
# match 12 hex digits with either : or - as separators between pairs
if re.match('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$',
opts['hw'].lower()):
config.update({'hw': opts['hw']})
else:
_raise_error_iface(iface, 'hw', ['valid MAC address'])
for opt in ['pathcost', 'portprio']:
if opt in opts:
try:
port, cost_or_prio = opts[opt].split()
int(cost_or_prio)
config.update({opt: '{0} {1}'.format(port, cost_or_prio)})
except ValueError:
_raise_error_iface(iface, opt, ['interface integer'])
if 'stp' in opts:
if opts['stp'] in _CONFIG_TRUE:
config.update({'stp': 'on'})
elif opts['stp'] in _CONFIG_FALSE:
config.update({'stp': 'off'})
else:
_raise_error_iface(iface, 'stp', _CONFIG_TRUE + _CONFIG_FALSE)
if 'waitport' in opts:
if isinstance(opts['waitport'], int):
config.update({'waitport': opts['waitport']})
else:
values = opts['waitport'].split()
waitport_time = values.pop(0)
if waitport_time.isdigit() and values:
config.update({
'waitport': '{0} {1}'.format(
waitport_time, ' '.join(values)
)
})
else:
_raise_error_iface(iface, opt, ['integer [interfaces]'])
return config
def _parse_settings_eth(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['inet'] = salt.utils.odict.OrderedDict()
iface_data['inet6'] = salt.utils.odict.OrderedDict()
if enabled:
adapters[iface]['enabled'] = True
if opts.get('hotplug', False):
adapters[iface]['hotplug'] = True
if opts.get('enable_ipv6', None) and opts.get('iface_type', '') == 'vlan':
iface_data['inet6']['vlan_raw_device'] = (
re.sub(r'\.\d*', '', iface))
for addrfam in ['inet', 'inet6']:
if iface_type not in ['bridge']:
tmp_ethtool = _parse_ethtool_opts(opts, iface)
if tmp_ethtool:
ethtool = {}
for item in tmp_ethtool:
ethtool[_ETHTOOL_CONFIG_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['ethtool'] = ethtool
# return a list of sorted keys to ensure consistent order
iface_data[addrfam]['ethtool_keys'] = sorted(ethtool)
if iface_type == 'bridge':
bridging = _parse_bridge_opts(opts, iface)
if bridging:
iface_data[addrfam]['bridging'] = bridging
iface_data[addrfam]['bridging_keys'] = sorted(bridging)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'bond':
bonding = _parse_settings_bond(opts, iface)
if bonding:
iface_data[addrfam]['bonding'] = bonding
iface_data[addrfam]['bonding']['slaves'] = opts['slaves']
iface_data[addrfam]['bonding_keys'] = sorted(bonding)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'slave':
adapters[iface]['master'] = opts['master']
opts['proto'] = 'manual'
iface_data[addrfam]['master'] = adapters[iface]['master']
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'vlan':
iface_data[addrfam]['vlan_raw_device'] = re.sub(r'\.\d*', '', iface)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'pppoe':
tmp_ethtool = _parse_ethtool_pppoe_opts(opts, iface)
if tmp_ethtool:
for item in tmp_ethtool:
adapters[iface]['data'][addrfam][_DEB_CONFIG_PPPOE_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['addrfam'] = addrfam
opts.pop('mode', None)
for opt, val in opts.items():
inet = None
if opt.startswith('ipv4'):
opt = opt[4:]
inet = 'inet'
iface_data['inet']['addrfam'] = 'inet'
elif opt.startswith('ipv6'):
iface_data['inet6']['addrfam'] = 'inet6'
opt = opt[4:]
inet = 'inet6'
elif opt in ['ipaddr', 'address', 'ipaddresses', 'addresses', 'gateway', 'proto']:
iface_data['inet']['addrfam'] = 'inet'
inet = 'inet'
_opt = SALT_ATTR_TO_DEBIAN_ATTR_MAP.get(opt, opt)
_debopt = _opt.replace('-', '_')
for addrfam in ['inet', 'inet6']:
(valid, value, errmsg) = _validate_interface_option(_opt, val, addrfam=addrfam)
if not valid:
continue
if inet is None and _debopt not in iface_data[addrfam]:
iface_data[addrfam][_debopt] = value
elif inet == addrfam:
iface_data[addrfam][_debopt] = value
for opt in ['up_cmds', 'pre_up_cmds', 'post_up_cmds',
'down_cmds', 'pre_down_cmds', 'post_down_cmds']:
if opt in opts:
iface_data['inet'][opt] = opts[opt]
iface_data['inet6'][opt] = opts[opt]
# Remove incomplete/disabled inet blocks
for (addrfam, opt) in [('inet', 'enable_ipv4'), ('inet6', 'enable_ipv6')]:
if opts.get(opt, None) is False:
iface_data.pop(addrfam)
elif iface_data[addrfam].get('addrfam', '') != addrfam:
iface_data.pop(addrfam)
return adapters
def _parse_settings_source(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['sources'] = [opts['source']]
return adapters
def _parse_network_settings(opts, current):
'''
Filters given options and outputs valid settings for
the global network settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
current = dict((k.lower(), v) for (k, v) in six.iteritems(current))
result = {}
valid = _CONFIG_TRUE + _CONFIG_FALSE
if 'enabled' not in opts:
try:
opts['networking'] = current['networking']
_log_default_network('networking', current['networking'])
except ValueError:
_raise_error_network('networking', valid)
else:
opts['networking'] = opts['enabled']
if opts['networking'] in valid:
if opts['networking'] in _CONFIG_TRUE:
result['networking'] = 'yes'
elif opts['networking'] in _CONFIG_FALSE:
result['networking'] = 'no'
else:
_raise_error_network('networking', valid)
if 'hostname' not in opts:
try:
opts['hostname'] = current['hostname']
_log_default_network('hostname', current['hostname'])
except ValueError:
_raise_error_network('hostname', ['server1.example.com'])
if opts['hostname']:
result['hostname'] = opts['hostname']
else:
_raise_error_network('hostname', ['server1.example.com'])
if 'search' in opts:
result['search'] = opts['search']
return result
def _parse_routes(iface, opts):
'''
Filters given options and outputs valid settings for
the route settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
result = {}
if 'routes' not in opts:
_raise_error_routes(iface, 'routes', 'List of routes')
for opt in opts:
result[opt] = opts[opt]
return result
def _write_file(iface, data, folder, pattern):
'''
Writes a file to disk
'''
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
return filename
def _write_file_routes(iface, data, folder, pattern):
'''
Writes a file to disk
'''
# ifup / ifdown is executing given folder via run-parts.
# according to run-parts man-page, only filenames with this pattern are
# executed: (^[a-zA-Z0-9_-]+$)
# In order to make the routes file work for vlan interfaces
# (default would have been in example /etc/network/if-up.d/route-bond0.12)
# these dots in the iface name need to be replaced by underscores, so it
# can be executed by run-parts
iface = iface.replace('.', '_')
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
__salt__['file.set_mode'](filename, '0755')
return filename
def _write_file_network(data, filename, create=False):
'''
Writes a file to disk
If file does not exist, only create if create
argument is True
'''
if not os.path.exists(filename) and not create:
msg = '{0} cannot be written. {0} does not exist\
and create is set to False'
msg = msg.format(filename)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
def _read_temp(data):
'''
Return what would be written to disk
'''
tout = StringIO()
tout.write(data)
tout.seek(0)
output = tout.readlines()
tout.close()
return output
def _read_temp_ifaces(iface, data):
'''
Return what would be written to disk for interfaces
'''
try:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': data})
# Return as an array so the difflib works
return [item + '\n' for item in ifcfg.split('\n')]
def _write_file_ifaces(iface, data, **settings):
'''
Writes a file to disk
'''
try:
eth_template = JINJA.get_template('debian_eth.jinja')
source_template = JINJA.get_template('debian_source.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
# Read /etc/network/interfaces into a dict
adapters = _parse_interfaces()
# Apply supplied settings over on-disk settings
adapters[iface] = data
ifcfg = ''
for adapter in adapters:
if 'type' in adapters[adapter] and adapters[adapter]['type'] == 'source':
tmp = source_template.render({'name': adapter, 'data': adapters[adapter]})
else:
tmp = eth_template.render({'name': adapter, 'data': adapters[adapter]})
ifcfg = ifcfg + tmp
if adapter == iface:
saved_ifcfg = tmp
_SEPARATE_FILE = False
if 'filename' in settings:
if not settings['filename'].startswith('/'):
filename = '{0}/{1}'.format(_DEB_NETWORK_DIR, settings['filename'])
else:
filename = settings['filename']
_SEPARATE_FILE = True
else:
if 'filename' in adapters[adapter]['data']:
filename = adapters[adapter]['data']
else:
filename = _DEB_NETWORK_FILE
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
if _SEPARATE_FILE:
fout.write(salt.utils.stringutils.to_str(saved_ifcfg))
else:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return saved_ifcfg.split('\n')
def _write_file_ppp_ifaces(iface, data):
'''
Writes a file to disk
'''
try:
template = JINJA.get_template('debian_ppp_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_ppp_eth.jinja')
return ''
adapters = _parse_interfaces()
adapters[iface] = data
ifcfg = ''
tmp = template.render({'data': adapters[iface]})
ifcfg = tmp + ifcfg
filename = _DEB_PPP_DIR + '/' + adapters[iface]['data']['inet']['provider']
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.fopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return filename
def build_bond(iface, **settings):
'''
Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb
'''
deb_major = __grains__['osrelease'][:1]
opts = _parse_settings_bond(settings, iface)
try:
template = JINJA.get_template('conf.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template conf.jinja')
return ''
data = template.render({'name': iface, 'bonding': opts})
if 'test' in settings and settings['test']:
return _read_temp(data)
_write_file(iface, data, _DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
if deb_major == '5':
for line_type in ('alias', 'options'):
cmd = ['sed', '-i', '-e', r'/^{0}\s{1}.*/d'.format(line_type, iface),
'/etc/modprobe.conf']
__salt__['cmd.run'](cmd, python_shell=False)
__salt__['file.append']('/etc/modprobe.conf', path)
# Load kernel module
__salt__['kmod.load']('bonding')
# install ifenslave-2.6
__salt__['pkg.install']('ifenslave-2.6')
return _read_file(path)
def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'vlan':
settings['vlan'] = 'yes'
__salt__['pkg.install']('vlan')
elif iface_type == 'pppoe':
settings['pppoe'] = 'yes'
if not __salt__['pkg.version']('ppp'):
inst = __salt__['pkg.install']('ppp')
elif iface_type == 'bond':
if 'slaves' not in settings:
msg = 'slaves is a required setting for bond interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'bridge':
if 'ports' not in settings:
msg = (
'ports is a required setting for bridge interfaces on Debian '
'or Ubuntu based systems'
)
log.error(msg)
raise AttributeError(msg)
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'pppoe']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
if iface_type in ['source']:
opts = _parse_settings_source(settings, iface_type, enabled, iface)
if 'test' in settings and settings['test']:
return _read_temp_ifaces(iface, opts[iface])
ifcfg = _write_file_ifaces(iface, opts[iface], **settings)
if iface_type == 'pppoe':
_write_file_ppp_ifaces(iface, opts[iface])
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg]
def build_routes(iface, **settings):
'''
Add route scripts for a network interface using up commands.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
'''
opts = _parse_routes(iface, settings)
try:
template = JINJA.get_template('route_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template route_eth.jinja')
return ''
add_routecfg = template.render(route_type='add',
routes=opts['routes'],
iface=iface)
del_routecfg = template.render(route_type='del',
routes=opts['routes'],
iface=iface)
if 'test' in settings and settings['test']:
return _read_temp(add_routecfg + del_routecfg)
filename = _write_file_routes(iface,
add_routecfg,
_DEB_NETWORK_UP_DIR,
'route-{0}')
results = _read_file(filename)
filename = _write_file_routes(iface,
del_routecfg,
_DEB_NETWORK_DOWN_DIR,
'route-{0}')
results += _read_file(filename)
return results
def down(iface, iface_type):
'''
Shutdown a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.down eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought down.
if iface_type not in ['slave', 'source']:
return __salt__['cmd.run'](['ifdown', iface])
return None
def get_bond(iface):
'''
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
'''
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
return _read_file(path)
def get_interface(iface):
'''
Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
adapters = _parse_interfaces()
if iface in adapters:
try:
if iface == 'source':
template = JINJA.get_template('debian_source.jinja')
else:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': adapters[iface]})
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg.split('\n')]
else:
return []
def up(iface, iface_type): # pylint: disable=C0103
'''
Start up a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.up eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought up.
if iface_type not in ('slave', 'source'):
return __salt__['cmd.run'](['ifup', iface])
return None
def get_network_settings():
'''
Return the contents of the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_network_settings
'''
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
settings = {}
if __salt__['service.available']('networking'):
if __salt__['service.status']('networking'):
settings['networking'] = "yes"
else:
settings['networking'] = "no"
else:
settings['networking'] = "no"
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
settings['hostname'] = hostname
settings['domainname'] = domainname
settings['searchdomain'] = searchdomain
else:
settings = _parse_current_network_settings()
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(settings)
return _read_temp(network)
def get_routes(iface):
'''
Return the routes for the interface
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0
'''
filename = os.path.join(_DEB_NETWORK_UP_DIR, 'route-{0}'.format(iface))
results = _read_file(filename)
filename = os.path.join(_DEB_NETWORK_DOWN_DIR, 'route-{0}'.format(iface))
results += _read_file(filename)
return results
def apply_network_settings(**settings):
'''
Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings
'''
if 'require_reboot' not in settings:
settings['require_reboot'] = False
if 'apply_hostname' not in settings:
settings['apply_hostname'] = False
hostname_res = True
if settings['apply_hostname'] in _CONFIG_TRUE:
if 'hostname' in settings:
hostname_res = __salt__['network.mod_hostname'](settings['hostname'])
else:
log.warning(
'The network state sls is trying to apply hostname '
'changes but no hostname is defined.'
)
hostname_res = False
res = True
if settings['require_reboot'] in _CONFIG_TRUE:
log.warning(
'The network state sls is requiring a reboot of the system to '
'properly apply network configuration.'
)
res = True
else:
stop = __salt__['service.stop']('networking')
time.sleep(2)
res = stop and __salt__['service.start']('networking')
return hostname_res and res
def build_network_settings(**settings):
'''
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
'''
changes = []
# Read current configuration and store default values
current_network_settings = _parse_current_network_settings()
# Build settings
opts = _parse_network_settings(settings, current_network_settings)
# Ubuntu has moved away from /etc/default/networking
# beginning with the 12.04 release so we disable or enable
# the networking related services on boot
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
if opts['networking'] == 'yes':
service_cmd = 'service.enable'
else:
service_cmd = 'service.disable'
if __salt__['service.available']('NetworkManager'):
__salt__[service_cmd]('NetworkManager')
if __salt__['service.available']('networking'):
__salt__[service_cmd]('networking')
else:
try:
template = JINJA.get_template('network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template network.jinja')
return ''
network = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(network)
# Write settings
_write_file_network(network, _DEB_NETWORKING_FILE, True)
# Get hostname and domain from opts
sline = opts['hostname'].split('.', 1)
opts['hostname'] = sline[0]
current_domainname = current_network_settings['domainname']
current_searchdomain = current_network_settings['searchdomain']
new_domain = False
if len(sline) > 1:
new_domainname = sline[1]
if new_domainname != current_domainname:
domainname = new_domainname
opts['domainname'] = new_domainname
new_domain = True
else:
domainname = current_domainname
opts['domainname'] = domainname
else:
domainname = current_domainname
opts['domainname'] = domainname
new_search = False
if 'search' in opts:
new_searchdomain = opts['search']
if new_searchdomain != current_searchdomain:
searchdomain = new_searchdomain
opts['searchdomain'] = new_searchdomain
new_search = True
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
# If the domain changes, then we should write the resolv.conf file.
if new_domain or new_search:
# Look for existing domain line and update if necessary
resolve = _parse_resolve()
domain_prog = re.compile(r'domain\s+')
search_prog = re.compile(r'search\s+')
new_contents = []
for item in _read_file(_DEB_RESOLV_FILE):
if domain_prog.match(item):
item = 'domain {0}'.format(domainname)
elif search_prog.match(item):
item = 'search {0}'.format(searchdomain)
new_contents.append(item)
# A domain line didn't exist so we'll add one in
# with the new domainname
if 'domain' not in resolve:
new_contents.insert(0, 'domain {0}' . format(domainname))
# A search line didn't exist so we'll add one in
# with the new search domain
if 'search' not in resolve:
new_contents.insert('domain' in resolve, 'search {0}'.format(searchdomain))
new_resolv = '\n'.join(new_contents)
# Write /etc/resolv.conf
if not ('test' in settings and settings['test']):
_write_file_network(new_resolv, _DEB_RESOLV_FILE)
# used for returning the results back
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(opts)
changes.extend(_read_temp(network))
return changes
|
saltstack/salt
|
salt/modules/debian_ip.py
|
_raise_error_routes
|
python
|
def _raise_error_routes(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_routes(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
|
Log and raise an error with a logical formatted message.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_ip.py#L211-L217
| null |
# -*- coding: utf-8 -*-
'''
The networking module for Debian-based distros
References:
* http://www.debian.org/doc/manuals/debian-reference/ch05.en.html
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import functools
import logging
import os.path
import os
import re
import time
# Import third party libs
import jinja2
import jinja2.exceptions
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error,no-name-in-module
# Import salt libs
import salt.utils.dns
import salt.utils.files
import salt.utils.odict
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.validate.net
# Set up logging
log = logging.getLogger(__name__)
# Set up template environment
JINJA = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'debian_ip')
)
)
# Define the module's virtual name
__virtualname__ = 'ip'
def __virtual__():
'''
Confine this module to Debian-based distros
'''
if __grains__['os_family'] == 'Debian':
return __virtualname__
return (False, 'The debian_ip module could not be loaded: '
'unsupported OS family')
_ETHTOOL_CONFIG_OPTS = {
'speed': 'link-speed',
'duplex': 'link-duplex',
'autoneg': 'ethernet-autoneg',
'ethernet-port': 'ethernet-port',
'wol': 'ethernet-wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'rx': 'offload-rx',
'tx': 'offload-tx',
'sg': 'offload-sg',
'tso': 'offload-tso',
'ufo': 'offload-ufo',
'gso': 'offload-gso',
'gro': 'offload-gro',
'lro': 'offload-lro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_REV_ETHTOOL_CONFIG_OPTS = {
'link-speed': 'speed',
'link-duplex': 'duplex',
'ethernet-autoneg': 'autoneg',
'ethernet-port': 'ethernet-port',
'ethernet-wol': 'wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'offload-rx': 'rx',
'offload-tx': 'tx',
'offload-sg': 'sg',
'offload-tso': 'tso',
'offload-ufo': 'ufo',
'offload-gso': 'gso',
'offload-lro': 'lro',
'offload-gro': 'gro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_DEB_CONFIG_PPPOE_OPTS = {
'user': 'user',
'password': 'password',
'provider': 'provider',
'pppoe_iface': 'pppoe_iface',
'noipdefault': 'noipdefault',
'usepeerdns': 'usepeerdns',
'defaultroute': 'defaultroute',
'holdoff': 'holdoff',
'maxfail': 'maxfail',
'hide-password': 'hide-password',
'lcp-echo-interval': 'lcp-echo-interval',
'lcp-echo-failure': 'lcp-echo-failure',
'connect': 'connect',
'noauth': 'noauth',
'persist': 'persist',
'mtu': 'mtu',
'noaccomp': 'noaccomp',
'linkname': 'linkname',
}
_DEB_ROUTES_FILE = '/etc/network/routes'
_DEB_NETWORK_FILE = '/etc/network/interfaces'
_DEB_NETWORK_DIR = '/etc/network/interfaces.d/'
_DEB_NETWORK_UP_DIR = '/etc/network/if-up.d/'
_DEB_NETWORK_DOWN_DIR = '/etc/network/if-down.d/'
_DEB_NETWORK_CONF_FILES = '/etc/modprobe.d/'
_DEB_NETWORKING_FILE = '/etc/default/networking'
_DEB_HOSTNAME_FILE = '/etc/hostname'
_DEB_RESOLV_FILE = '/etc/resolv.conf'
_DEB_PPP_DIR = '/etc/ppp/peers/'
_CONFIG_TRUE = ['yes', 'on', 'true', '1', True]
_CONFIG_FALSE = ['no', 'off', 'false', '0', False]
_IFACE_TYPES = [
'eth', 'bond', 'alias', 'clone',
'ipsec', 'dialup', 'bridge', 'slave',
'vlan', 'pppoe', 'source',
]
def _error_msg_iface(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, '|'.join(str(e) for e in expected))
def _error_msg_routes(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, expected)
def _log_default_iface(iface, opt, value):
log.info(
'Using default option -- Interface: %s Option: %s Value: %s',
iface, opt, value
)
def _error_msg_network(option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]'
return msg.format(option, '|'.join(str(e) for e in expected))
def _log_default_network(opt, value):
log.info('Using existing setting -- Setting: %s Value: %s', opt, value)
def _raise_error_iface(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_iface(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_network(option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_network(option, expected)
log.error(msg)
raise AttributeError(msg)
def _read_file(path):
'''
Reads and returns the contents of a text file
'''
try:
with salt.utils.files.flopen(path, 'rb') as contents:
return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]
except (OSError, IOError):
return ''
def _parse_resolve():
'''
Parse /etc/resolv.conf
'''
return salt.utils.dns.parse_resolv(_DEB_RESOLV_FILE)
def _parse_domainname():
'''
Parse /etc/resolv.conf and return domainname
'''
return _parse_resolve().get('domain', '')
def _parse_searchdomain():
'''
Parse /etc/resolv.conf and return searchdomain
'''
return _parse_resolve().get('search', '')
def _parse_hostname():
'''
Parse /etc/hostname and return hostname
'''
contents = _read_file(_DEB_HOSTNAME_FILE)
if contents:
return contents[0].split('\n')[0]
else:
return ''
def _parse_current_network_settings():
'''
Parse /etc/default/networking and return current configuration
'''
opts = salt.utils.odict.OrderedDict()
opts['networking'] = ''
if os.path.isfile(_DEB_NETWORKING_FILE):
with salt.utils.files.fopen(_DEB_NETWORKING_FILE) as contents:
for line in contents:
salt.utils.stringutils.to_unicode(line)
if line.startswith('#'):
continue
elif line.startswith('CONFIGURE_INTERFACES'):
opts['networking'] = line.split('=', 1)[1].strip()
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
opts['hostname'] = hostname
opts['domainname'] = domainname
opts['searchdomain'] = searchdomain
return opts
# def __validator_func(value):
# return (valid: True/False, (transformed) value, error message)
def __ipv4_quad(value):
'''validate an IPv4 address'''
return (salt.utils.validate.net.ipv4_addr(value), value,
'dotted IPv4 address')
def __ipv6(value):
'''validate an IPv6 address'''
return (salt.utils.validate.net.ipv6_addr(value), value,
'IPv6 address')
def __mac(value):
'''validate a mac address'''
return (salt.utils.validate.net.mac(value), value,
'MAC address')
def __anything(value):
return (True, value, None)
def __int(value):
'''validate an integer'''
valid, _value = False, value
try:
_value = int(value)
valid = True
except ValueError:
pass
return (valid, _value, 'integer')
def __float(value):
'''validate a float'''
valid, _value = False, value
try:
_value = float(value)
valid = True
except ValueError:
pass
return (valid, _value, 'float')
def __ipv4_netmask(value):
'''validate an IPv4 dotted quad or integer CIDR netmask'''
valid, errmsg = False, 'dotted quad or integer CIDR (0->32)'
valid, value, _ = __int(value)
if not (valid and 0 <= value <= 32):
valid = salt.utils.validate.net.netmask(value)
return (valid, value, errmsg)
def __ipv6_netmask(value):
'''validate an IPv6 integer netmask'''
valid, errmsg = False, 'IPv6 netmask (0->128)'
valid, value, _ = __int(value)
valid = (valid and 0 <= value <= 128)
return (valid, value, errmsg)
def __within2(value, within=None, errmsg=None, dtype=None):
'''validate that a value is in ``within`` and optionally a ``dtype``'''
valid, _value = False, value
if dtype:
try:
_value = dtype(value) # TODO: this is a bit loose when dtype is a class
valid = _value in within
except ValueError:
pass
else:
valid = _value in within
if errmsg is None:
if dtype:
typename = getattr(dtype, '__name__',
hasattr(dtype, '__class__')
and getattr(dtype.__class__, 'name', dtype))
errmsg = '{0} within \'{1}\''.format(typename, within)
else:
errmsg = 'within \'{0}\''.format(within)
return (valid, _value, errmsg)
def __within(within=None, errmsg=None, dtype=None):
return functools.partial(__within2, within=within,
errmsg=errmsg, dtype=dtype)
def __space_delimited_list(value):
'''validate that a value contains one or more space-delimited values'''
if isinstance(value, six.string_types):
value = value.strip().split()
if hasattr(value, '__iter__') and value != []:
return (True, value, 'space-delimited string')
else:
return (False, value, '{0} is not a valid space-delimited value.\n'.format(value))
SALT_ATTR_TO_DEBIAN_ATTR_MAP = {
'dns': 'dns-nameservers',
'search': 'dns-search',
'hwaddr': 'hwaddress', # TODO: this limits bootp functionality
'ipaddr': 'address',
'ipaddrs': 'addresses',
}
DEBIAN_ATTR_TO_SALT_ATTR_MAP = dict(
(v, k) for (k, v) in six.iteritems(SALT_ATTR_TO_DEBIAN_ATTR_MAP))
# TODO
DEBIAN_ATTR_TO_SALT_ATTR_MAP['address'] = 'address'
DEBIAN_ATTR_TO_SALT_ATTR_MAP['hwaddress'] = 'hwaddress'
IPV4_VALID_PROTO = ['bootp', 'dhcp', 'static', 'manual', 'loopback', 'ppp']
IPV4_ATTR_MAP = {
'proto': __within(IPV4_VALID_PROTO, dtype=six.text_type),
# ipv4 static & manual
'address': __ipv4_quad,
'addresses': __anything,
'netmask': __ipv4_netmask,
'broadcast': __ipv4_quad,
'metric': __int,
'gateway': __ipv4_quad, # supports a colon-delimited list
'pointopoint': __ipv4_quad,
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'link', 'host'], dtype=six.text_type),
# dhcp
'hostname': __anything,
'leasehours': __int,
'leasetime': __int,
'vendor': __anything,
'client': __anything,
# bootp
'bootfile': __anything,
'server': __ipv4_quad,
'hwaddr': __mac,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'dstaddr': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# bond
'slaves': __anything,
# ppp
'provider': __anything,
'unit': __int,
'options': __anything,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
#
'network': __anything, # i don't know what this is
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
IPV6_VALID_PROTO = ['auto', 'loopback', 'static', 'manual',
'dhcp', 'v4tunnel', '6to4']
IPV6_ATTR_MAP = {
'proto': __within(IPV6_VALID_PROTO),
# ipv6 static & manual
'address': __ipv6,
'addresses': __anything,
'netmask': __ipv6_netmask,
'broadcast': __ipv6,
'gateway': __ipv6, # supports a colon-delimited list
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'site', 'link', 'host'], dtype=six.text_type),
# inet6 auto
'privext': __within([0, 1, 2], dtype=int),
'dhcp': __within([0, 1], dtype=int),
# inet6 static & manual & dhcp
'media': __anything,
'accept_ra': __within([0, 1], dtype=int),
'autoconf': __within([0, 1], dtype=int),
'preferred-lifetime': __int,
'dad-attempts': __int, # 0 to disable
'dad-interval': __float,
# bond
'slaves': __anything,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
WIRELESS_ATTR_MAP = {
'wireless-essid': __anything,
'wireless-mode': __anything, # TODO
'wpa-ap-scan': __within([0, 1, 2], dtype=int), # TODO
'wpa-conf': __anything,
'wpa-driver': __anything,
'wpa-group': __anything,
'wpa-key-mgmt': __anything,
'wpa-pairwise': __anything,
'wpa-psk': __anything,
'wpa-proto': __anything, # partial(__within,
'wpa-roam': __anything,
'wpa-ssid': __anything, # TODO
}
ATTRMAPS = {
'inet': [IPV4_ATTR_MAP, WIRELESS_ATTR_MAP],
'inet6': [IPV6_ATTR_MAP, WIRELESS_ATTR_MAP]
}
def _validate_interface_option(attr, value, addrfam='inet'):
'''lookup the validation function for a [addrfam][attr] and
return the results
:param attr: attribute name
:param value: raw setting value
:param addrfam: address family (inet, inet6,
'''
valid, _value, errmsg = False, value, 'Unknown validator'
attrmaps = ATTRMAPS.get(addrfam, [])
for attrmap in attrmaps:
if attr in attrmap:
validate_func = attrmap[attr]
(valid, _value, errmsg) = validate_func(value)
break
return (valid, _value, errmsg)
def _attrmaps_contain_attr(attr):
return (
attr in WIRELESS_ATTR_MAP or
attr in IPV4_ATTR_MAP or
attr in IPV6_ATTR_MAP)
def _parse_interfaces(interface_files=None):
'''
Parse /etc/network/interfaces and return current configured interfaces
'''
if interface_files is None:
interface_files = []
# Add this later.
if os.path.exists(_DEB_NETWORK_DIR):
interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]
if os.path.isfile(_DEB_NETWORK_FILE):
interface_files.insert(0, _DEB_NETWORK_FILE)
adapters = salt.utils.odict.OrderedDict()
method = -1
for interface_file in interface_files:
with salt.utils.files.fopen(interface_file) as interfaces:
# This ensures iface_dict exists, but does not ensure we're not reading a new interface.
iface_dict = {}
for line in interfaces:
line = salt.utils.stringutils.to_unicode(line)
# Identify the clauses by the first word of each line.
# Go to the next line if the current line is a comment
# or all spaces.
if line.lstrip().startswith('#') or line.isspace():
continue
# Parse the iface clause
if line.startswith('iface'):
sline = line.split()
if len(sline) != 4:
msg = 'Interface file malformed: {0}.'
msg = msg.format(sline)
log.error(msg)
raise AttributeError(msg)
iface_name = sline[1]
addrfam = sline[2]
method = sline[3]
# Create item in dict, if not already there
if iface_name not in adapters:
adapters[iface_name] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters[iface_name]:
adapters[iface_name]['data'] = salt.utils.odict.OrderedDict()
if addrfam not in adapters[iface_name]['data']:
adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict()
iface_dict = adapters[iface_name]['data'][addrfam]
iface_dict['addrfam'] = addrfam
iface_dict['proto'] = method
iface_dict['filename'] = interface_file
# Parse the detail clauses.
elif line[0].isspace():
sline = line.split()
# conf file attr: dns-nameservers
# salt states.network attr: dns
attr, valuestr = line.rstrip().split(None, 1)
if _attrmaps_contain_attr(attr):
if '-' in attr:
attrname = attr.replace('-', '_')
else:
attrname = attr
(valid, value, errmsg) = _validate_interface_option(
attr, valuestr, addrfam)
if attrname == 'address' and 'address' in iface_dict:
if 'addresses' not in iface_dict:
iface_dict['addresses'] = []
iface_dict['addresses'].append(value)
else:
iface_dict[attrname] = value
elif attr in _REV_ETHTOOL_CONFIG_OPTS:
if 'ethtool' not in iface_dict:
iface_dict['ethtool'] = salt.utils.odict.OrderedDict()
iface_dict['ethtool'][attr] = valuestr
elif attr.startswith('bond'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bonding' not in iface_dict:
iface_dict['bonding'] = salt.utils.odict.OrderedDict()
iface_dict['bonding'][opt] = valuestr
elif attr.startswith('bridge'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bridging' not in iface_dict:
iface_dict['bridging'] = salt.utils.odict.OrderedDict()
iface_dict['bridging'][opt] = valuestr
elif attr in ['up', 'pre-up', 'post-up',
'down', 'pre-down', 'post-down']:
cmd = valuestr
cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr))
if cmd_key not in iface_dict:
iface_dict[cmd_key] = []
iface_dict[cmd_key].append(cmd)
elif line.startswith('auto'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['enabled'] = True
elif line.startswith('allow-hotplug'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['hotplug'] = True
elif line.startswith('source'):
if 'source' not in adapters:
adapters['source'] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters['source']:
adapters['source']['data'] = salt.utils.odict.OrderedDict()
adapters['source']['data']['sources'] = []
adapters['source']['data']['sources'].append(line.split()[1])
# Return a sorted list of the keys for bond, bridge and ethtool options to
# ensure a consistent order
for iface_name in adapters:
if iface_name == 'source':
continue
if 'data' not in adapters[iface_name]:
msg = 'Interface file malformed for interface: {0}.'.format(iface_name)
log.error(msg)
adapters.pop(iface_name)
continue
for opt in ['ethtool', 'bonding', 'bridging']:
for inet in ['inet', 'inet6']:
if inet in adapters[iface_name]['data']:
if opt in adapters[iface_name]['data'][inet]:
opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys())
adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys
return adapters
def _parse_ethtool_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
if 'autoneg' in opts:
if opts['autoneg'] in _CONFIG_TRUE:
config.update({'autoneg': 'on'})
elif opts['autoneg'] in _CONFIG_FALSE:
config.update({'autoneg': 'off'})
else:
_raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE)
if 'duplex' in opts:
valid = ['full', 'half']
if opts['duplex'] in valid:
config.update({'duplex': opts['duplex']})
else:
_raise_error_iface(iface, 'duplex', valid)
if 'speed' in opts:
valid = ['10', '100', '1000', '10000']
if six.text_type(opts['speed']) in valid:
config.update({'speed': opts['speed']})
else:
_raise_error_iface(iface, opts['speed'], valid)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'on'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'off'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_ethtool_pppoe_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
for opt in _DEB_CONFIG_PPPOE_OPTS:
if opt in opts:
config[opt] = opts[opt]
if 'provider' in opts and not opts['provider']:
_raise_error_iface(iface, 'provider', _CONFIG_TRUE + _CONFIG_FALSE)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('noipdefault', 'usepeerdns', 'defaultroute', 'hide-password', 'noauth', 'persist', 'noaccomp'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'True'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'False'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_settings_bond(opts, iface):
'''
Filters given options and outputs valid settings for requested
operation. If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond_def = {
# 803.ad aggregation selection logic
# 0 for stable (default)
# 1 for bandwidth
# 2 for count
'ad_select': '0',
# Max number of transmit queues (default = 16)
'tx_queues': '16',
# Link monitoring in milliseconds. Most NICs support this
'miimon': '100',
# ARP interval in milliseconds
'arp_interval': '250',
# Delay before considering link down in milliseconds (miimon * 2)
'downdelay': '200',
# lacp_rate 0: Slow - every 30 seconds
# lacp_rate 1: Fast - every 1 second
'lacp_rate': '0',
# Max bonds for this driver
'max_bonds': '1',
# Specifies the time, in milliseconds, to wait before
# enabling a slave after a link recovery has been
# detected. Only used with miimon.
'updelay': '0',
# Used with miimon.
# On: driver sends mii
# Off: ethtool sends mii
'use_carrier': 'on',
# Default. Don't change unless you know what you are doing.
'xmit_hash_policy': 'layer2',
}
if opts['mode'] in ['balance-rr', '0']:
log.info('Device: %s Bonding Mode: load balancing (round-robin)', iface)
return _parse_settings_bond_0(opts, iface, bond_def)
elif opts['mode'] in ['active-backup', '1']:
log.info('Device: %s Bonding Mode: fault-tolerance (active-backup)', iface)
return _parse_settings_bond_1(opts, iface, bond_def)
elif opts['mode'] in ['balance-xor', '2']:
log.info('Device: %s Bonding Mode: load balancing (xor)', iface)
return _parse_settings_bond_2(opts, iface, bond_def)
elif opts['mode'] in ['broadcast', '3']:
log.info('Device: %s Bonding Mode: fault-tolerance (broadcast)', iface)
return _parse_settings_bond_3(opts, iface, bond_def)
elif opts['mode'] in ['802.3ad', '4']:
log.info('Device: %s Bonding Mode: IEEE 802.3ad Dynamic link '
'aggregation', iface)
return _parse_settings_bond_4(opts, iface, bond_def)
elif opts['mode'] in ['balance-tlb', '5']:
log.info('Device: %s Bonding Mode: transmit load balancing', iface)
return _parse_settings_bond_5(opts, iface, bond_def)
elif opts['mode'] in ['balance-alb', '6']:
log.info('Device: %s Bonding Mode: adaptive load balancing', iface)
return _parse_settings_bond_6(opts, iface, bond_def)
else:
valid = [
'0', '1', '2', '3', '4', '5', '6',
'balance-rr', 'active-backup', 'balance-xor',
'broadcast', '802.3ad', 'balance-tlb', 'balance-alb'
]
_raise_error_iface(iface, 'mode', valid)
def _parse_settings_bond_0(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond0.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '0'}
# ARP targets in n.n.n.n form
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
return bond
def _parse_settings_bond_1(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '1'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
if not (__grains__['os'] == "Ubuntu" and __grains__['osrelease_info'][0] >= 16):
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_2(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond2.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '2'}
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_3(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond3.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '3'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_4(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond4.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '4'}
for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']:
if binding in opts:
if binding == 'lacp_rate':
if opts[binding] == 'fast':
opts.update({binding: '1'})
if opts[binding] == 'slow':
opts.update({binding: '0'})
valid = ['fast', '1', 'slow', '0']
else:
valid = ['integer']
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, valid)
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_5(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond5.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '5'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_settings_bond_6(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond6.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '6'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_bridge_opts(opts, iface):
'''
Filters given options and outputs valid settings for BRIDGING_OPTS
If an option has a value that is not expected, this
function will log the Interface, Setting and what was expected.
'''
config = {}
if 'ports' in opts:
if isinstance(opts['ports'], list):
opts['ports'] = ' '.join(opts['ports'])
config.update({'ports': opts['ports']})
for opt in ['ageing', 'fd', 'gcint', 'hello', 'maxage']:
if opt in opts:
try:
float(opts[opt])
config.update({opt: opts[opt]})
except ValueError:
_raise_error_iface(iface, opt, ['float'])
for opt in ['bridgeprio', 'maxwait']:
if opt in opts:
if isinstance(opts[opt], int):
config.update({opt: opts[opt]})
else:
_raise_error_iface(iface, opt, ['integer'])
if 'hw' in opts:
# match 12 hex digits with either : or - as separators between pairs
if re.match('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$',
opts['hw'].lower()):
config.update({'hw': opts['hw']})
else:
_raise_error_iface(iface, 'hw', ['valid MAC address'])
for opt in ['pathcost', 'portprio']:
if opt in opts:
try:
port, cost_or_prio = opts[opt].split()
int(cost_or_prio)
config.update({opt: '{0} {1}'.format(port, cost_or_prio)})
except ValueError:
_raise_error_iface(iface, opt, ['interface integer'])
if 'stp' in opts:
if opts['stp'] in _CONFIG_TRUE:
config.update({'stp': 'on'})
elif opts['stp'] in _CONFIG_FALSE:
config.update({'stp': 'off'})
else:
_raise_error_iface(iface, 'stp', _CONFIG_TRUE + _CONFIG_FALSE)
if 'waitport' in opts:
if isinstance(opts['waitport'], int):
config.update({'waitport': opts['waitport']})
else:
values = opts['waitport'].split()
waitport_time = values.pop(0)
if waitport_time.isdigit() and values:
config.update({
'waitport': '{0} {1}'.format(
waitport_time, ' '.join(values)
)
})
else:
_raise_error_iface(iface, opt, ['integer [interfaces]'])
return config
def _parse_settings_eth(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['inet'] = salt.utils.odict.OrderedDict()
iface_data['inet6'] = salt.utils.odict.OrderedDict()
if enabled:
adapters[iface]['enabled'] = True
if opts.get('hotplug', False):
adapters[iface]['hotplug'] = True
if opts.get('enable_ipv6', None) and opts.get('iface_type', '') == 'vlan':
iface_data['inet6']['vlan_raw_device'] = (
re.sub(r'\.\d*', '', iface))
for addrfam in ['inet', 'inet6']:
if iface_type not in ['bridge']:
tmp_ethtool = _parse_ethtool_opts(opts, iface)
if tmp_ethtool:
ethtool = {}
for item in tmp_ethtool:
ethtool[_ETHTOOL_CONFIG_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['ethtool'] = ethtool
# return a list of sorted keys to ensure consistent order
iface_data[addrfam]['ethtool_keys'] = sorted(ethtool)
if iface_type == 'bridge':
bridging = _parse_bridge_opts(opts, iface)
if bridging:
iface_data[addrfam]['bridging'] = bridging
iface_data[addrfam]['bridging_keys'] = sorted(bridging)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'bond':
bonding = _parse_settings_bond(opts, iface)
if bonding:
iface_data[addrfam]['bonding'] = bonding
iface_data[addrfam]['bonding']['slaves'] = opts['slaves']
iface_data[addrfam]['bonding_keys'] = sorted(bonding)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'slave':
adapters[iface]['master'] = opts['master']
opts['proto'] = 'manual'
iface_data[addrfam]['master'] = adapters[iface]['master']
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'vlan':
iface_data[addrfam]['vlan_raw_device'] = re.sub(r'\.\d*', '', iface)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'pppoe':
tmp_ethtool = _parse_ethtool_pppoe_opts(opts, iface)
if tmp_ethtool:
for item in tmp_ethtool:
adapters[iface]['data'][addrfam][_DEB_CONFIG_PPPOE_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['addrfam'] = addrfam
opts.pop('mode', None)
for opt, val in opts.items():
inet = None
if opt.startswith('ipv4'):
opt = opt[4:]
inet = 'inet'
iface_data['inet']['addrfam'] = 'inet'
elif opt.startswith('ipv6'):
iface_data['inet6']['addrfam'] = 'inet6'
opt = opt[4:]
inet = 'inet6'
elif opt in ['ipaddr', 'address', 'ipaddresses', 'addresses', 'gateway', 'proto']:
iface_data['inet']['addrfam'] = 'inet'
inet = 'inet'
_opt = SALT_ATTR_TO_DEBIAN_ATTR_MAP.get(opt, opt)
_debopt = _opt.replace('-', '_')
for addrfam in ['inet', 'inet6']:
(valid, value, errmsg) = _validate_interface_option(_opt, val, addrfam=addrfam)
if not valid:
continue
if inet is None and _debopt not in iface_data[addrfam]:
iface_data[addrfam][_debopt] = value
elif inet == addrfam:
iface_data[addrfam][_debopt] = value
for opt in ['up_cmds', 'pre_up_cmds', 'post_up_cmds',
'down_cmds', 'pre_down_cmds', 'post_down_cmds']:
if opt in opts:
iface_data['inet'][opt] = opts[opt]
iface_data['inet6'][opt] = opts[opt]
# Remove incomplete/disabled inet blocks
for (addrfam, opt) in [('inet', 'enable_ipv4'), ('inet6', 'enable_ipv6')]:
if opts.get(opt, None) is False:
iface_data.pop(addrfam)
elif iface_data[addrfam].get('addrfam', '') != addrfam:
iface_data.pop(addrfam)
return adapters
def _parse_settings_source(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['sources'] = [opts['source']]
return adapters
def _parse_network_settings(opts, current):
'''
Filters given options and outputs valid settings for
the global network settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
current = dict((k.lower(), v) for (k, v) in six.iteritems(current))
result = {}
valid = _CONFIG_TRUE + _CONFIG_FALSE
if 'enabled' not in opts:
try:
opts['networking'] = current['networking']
_log_default_network('networking', current['networking'])
except ValueError:
_raise_error_network('networking', valid)
else:
opts['networking'] = opts['enabled']
if opts['networking'] in valid:
if opts['networking'] in _CONFIG_TRUE:
result['networking'] = 'yes'
elif opts['networking'] in _CONFIG_FALSE:
result['networking'] = 'no'
else:
_raise_error_network('networking', valid)
if 'hostname' not in opts:
try:
opts['hostname'] = current['hostname']
_log_default_network('hostname', current['hostname'])
except ValueError:
_raise_error_network('hostname', ['server1.example.com'])
if opts['hostname']:
result['hostname'] = opts['hostname']
else:
_raise_error_network('hostname', ['server1.example.com'])
if 'search' in opts:
result['search'] = opts['search']
return result
def _parse_routes(iface, opts):
'''
Filters given options and outputs valid settings for
the route settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
result = {}
if 'routes' not in opts:
_raise_error_routes(iface, 'routes', 'List of routes')
for opt in opts:
result[opt] = opts[opt]
return result
def _write_file(iface, data, folder, pattern):
'''
Writes a file to disk
'''
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
return filename
def _write_file_routes(iface, data, folder, pattern):
'''
Writes a file to disk
'''
# ifup / ifdown is executing given folder via run-parts.
# according to run-parts man-page, only filenames with this pattern are
# executed: (^[a-zA-Z0-9_-]+$)
# In order to make the routes file work for vlan interfaces
# (default would have been in example /etc/network/if-up.d/route-bond0.12)
# these dots in the iface name need to be replaced by underscores, so it
# can be executed by run-parts
iface = iface.replace('.', '_')
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
__salt__['file.set_mode'](filename, '0755')
return filename
def _write_file_network(data, filename, create=False):
'''
Writes a file to disk
If file does not exist, only create if create
argument is True
'''
if not os.path.exists(filename) and not create:
msg = '{0} cannot be written. {0} does not exist\
and create is set to False'
msg = msg.format(filename)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
def _read_temp(data):
'''
Return what would be written to disk
'''
tout = StringIO()
tout.write(data)
tout.seek(0)
output = tout.readlines()
tout.close()
return output
def _read_temp_ifaces(iface, data):
'''
Return what would be written to disk for interfaces
'''
try:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': data})
# Return as an array so the difflib works
return [item + '\n' for item in ifcfg.split('\n')]
def _write_file_ifaces(iface, data, **settings):
'''
Writes a file to disk
'''
try:
eth_template = JINJA.get_template('debian_eth.jinja')
source_template = JINJA.get_template('debian_source.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
# Read /etc/network/interfaces into a dict
adapters = _parse_interfaces()
# Apply supplied settings over on-disk settings
adapters[iface] = data
ifcfg = ''
for adapter in adapters:
if 'type' in adapters[adapter] and adapters[adapter]['type'] == 'source':
tmp = source_template.render({'name': adapter, 'data': adapters[adapter]})
else:
tmp = eth_template.render({'name': adapter, 'data': adapters[adapter]})
ifcfg = ifcfg + tmp
if adapter == iface:
saved_ifcfg = tmp
_SEPARATE_FILE = False
if 'filename' in settings:
if not settings['filename'].startswith('/'):
filename = '{0}/{1}'.format(_DEB_NETWORK_DIR, settings['filename'])
else:
filename = settings['filename']
_SEPARATE_FILE = True
else:
if 'filename' in adapters[adapter]['data']:
filename = adapters[adapter]['data']
else:
filename = _DEB_NETWORK_FILE
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
if _SEPARATE_FILE:
fout.write(salt.utils.stringutils.to_str(saved_ifcfg))
else:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return saved_ifcfg.split('\n')
def _write_file_ppp_ifaces(iface, data):
'''
Writes a file to disk
'''
try:
template = JINJA.get_template('debian_ppp_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_ppp_eth.jinja')
return ''
adapters = _parse_interfaces()
adapters[iface] = data
ifcfg = ''
tmp = template.render({'data': adapters[iface]})
ifcfg = tmp + ifcfg
filename = _DEB_PPP_DIR + '/' + adapters[iface]['data']['inet']['provider']
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.fopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return filename
def build_bond(iface, **settings):
'''
Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb
'''
deb_major = __grains__['osrelease'][:1]
opts = _parse_settings_bond(settings, iface)
try:
template = JINJA.get_template('conf.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template conf.jinja')
return ''
data = template.render({'name': iface, 'bonding': opts})
if 'test' in settings and settings['test']:
return _read_temp(data)
_write_file(iface, data, _DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
if deb_major == '5':
for line_type in ('alias', 'options'):
cmd = ['sed', '-i', '-e', r'/^{0}\s{1}.*/d'.format(line_type, iface),
'/etc/modprobe.conf']
__salt__['cmd.run'](cmd, python_shell=False)
__salt__['file.append']('/etc/modprobe.conf', path)
# Load kernel module
__salt__['kmod.load']('bonding')
# install ifenslave-2.6
__salt__['pkg.install']('ifenslave-2.6')
return _read_file(path)
def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'vlan':
settings['vlan'] = 'yes'
__salt__['pkg.install']('vlan')
elif iface_type == 'pppoe':
settings['pppoe'] = 'yes'
if not __salt__['pkg.version']('ppp'):
inst = __salt__['pkg.install']('ppp')
elif iface_type == 'bond':
if 'slaves' not in settings:
msg = 'slaves is a required setting for bond interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'bridge':
if 'ports' not in settings:
msg = (
'ports is a required setting for bridge interfaces on Debian '
'or Ubuntu based systems'
)
log.error(msg)
raise AttributeError(msg)
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'pppoe']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
if iface_type in ['source']:
opts = _parse_settings_source(settings, iface_type, enabled, iface)
if 'test' in settings and settings['test']:
return _read_temp_ifaces(iface, opts[iface])
ifcfg = _write_file_ifaces(iface, opts[iface], **settings)
if iface_type == 'pppoe':
_write_file_ppp_ifaces(iface, opts[iface])
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg]
def build_routes(iface, **settings):
'''
Add route scripts for a network interface using up commands.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
'''
opts = _parse_routes(iface, settings)
try:
template = JINJA.get_template('route_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template route_eth.jinja')
return ''
add_routecfg = template.render(route_type='add',
routes=opts['routes'],
iface=iface)
del_routecfg = template.render(route_type='del',
routes=opts['routes'],
iface=iface)
if 'test' in settings and settings['test']:
return _read_temp(add_routecfg + del_routecfg)
filename = _write_file_routes(iface,
add_routecfg,
_DEB_NETWORK_UP_DIR,
'route-{0}')
results = _read_file(filename)
filename = _write_file_routes(iface,
del_routecfg,
_DEB_NETWORK_DOWN_DIR,
'route-{0}')
results += _read_file(filename)
return results
def down(iface, iface_type):
'''
Shutdown a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.down eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought down.
if iface_type not in ['slave', 'source']:
return __salt__['cmd.run'](['ifdown', iface])
return None
def get_bond(iface):
'''
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
'''
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
return _read_file(path)
def get_interface(iface):
'''
Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
adapters = _parse_interfaces()
if iface in adapters:
try:
if iface == 'source':
template = JINJA.get_template('debian_source.jinja')
else:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': adapters[iface]})
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg.split('\n')]
else:
return []
def up(iface, iface_type): # pylint: disable=C0103
'''
Start up a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.up eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought up.
if iface_type not in ('slave', 'source'):
return __salt__['cmd.run'](['ifup', iface])
return None
def get_network_settings():
'''
Return the contents of the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_network_settings
'''
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
settings = {}
if __salt__['service.available']('networking'):
if __salt__['service.status']('networking'):
settings['networking'] = "yes"
else:
settings['networking'] = "no"
else:
settings['networking'] = "no"
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
settings['hostname'] = hostname
settings['domainname'] = domainname
settings['searchdomain'] = searchdomain
else:
settings = _parse_current_network_settings()
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(settings)
return _read_temp(network)
def get_routes(iface):
'''
Return the routes for the interface
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0
'''
filename = os.path.join(_DEB_NETWORK_UP_DIR, 'route-{0}'.format(iface))
results = _read_file(filename)
filename = os.path.join(_DEB_NETWORK_DOWN_DIR, 'route-{0}'.format(iface))
results += _read_file(filename)
return results
def apply_network_settings(**settings):
'''
Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings
'''
if 'require_reboot' not in settings:
settings['require_reboot'] = False
if 'apply_hostname' not in settings:
settings['apply_hostname'] = False
hostname_res = True
if settings['apply_hostname'] in _CONFIG_TRUE:
if 'hostname' in settings:
hostname_res = __salt__['network.mod_hostname'](settings['hostname'])
else:
log.warning(
'The network state sls is trying to apply hostname '
'changes but no hostname is defined.'
)
hostname_res = False
res = True
if settings['require_reboot'] in _CONFIG_TRUE:
log.warning(
'The network state sls is requiring a reboot of the system to '
'properly apply network configuration.'
)
res = True
else:
stop = __salt__['service.stop']('networking')
time.sleep(2)
res = stop and __salt__['service.start']('networking')
return hostname_res and res
def build_network_settings(**settings):
'''
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
'''
changes = []
# Read current configuration and store default values
current_network_settings = _parse_current_network_settings()
# Build settings
opts = _parse_network_settings(settings, current_network_settings)
# Ubuntu has moved away from /etc/default/networking
# beginning with the 12.04 release so we disable or enable
# the networking related services on boot
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
if opts['networking'] == 'yes':
service_cmd = 'service.enable'
else:
service_cmd = 'service.disable'
if __salt__['service.available']('NetworkManager'):
__salt__[service_cmd]('NetworkManager')
if __salt__['service.available']('networking'):
__salt__[service_cmd]('networking')
else:
try:
template = JINJA.get_template('network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template network.jinja')
return ''
network = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(network)
# Write settings
_write_file_network(network, _DEB_NETWORKING_FILE, True)
# Get hostname and domain from opts
sline = opts['hostname'].split('.', 1)
opts['hostname'] = sline[0]
current_domainname = current_network_settings['domainname']
current_searchdomain = current_network_settings['searchdomain']
new_domain = False
if len(sline) > 1:
new_domainname = sline[1]
if new_domainname != current_domainname:
domainname = new_domainname
opts['domainname'] = new_domainname
new_domain = True
else:
domainname = current_domainname
opts['domainname'] = domainname
else:
domainname = current_domainname
opts['domainname'] = domainname
new_search = False
if 'search' in opts:
new_searchdomain = opts['search']
if new_searchdomain != current_searchdomain:
searchdomain = new_searchdomain
opts['searchdomain'] = new_searchdomain
new_search = True
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
# If the domain changes, then we should write the resolv.conf file.
if new_domain or new_search:
# Look for existing domain line and update if necessary
resolve = _parse_resolve()
domain_prog = re.compile(r'domain\s+')
search_prog = re.compile(r'search\s+')
new_contents = []
for item in _read_file(_DEB_RESOLV_FILE):
if domain_prog.match(item):
item = 'domain {0}'.format(domainname)
elif search_prog.match(item):
item = 'search {0}'.format(searchdomain)
new_contents.append(item)
# A domain line didn't exist so we'll add one in
# with the new domainname
if 'domain' not in resolve:
new_contents.insert(0, 'domain {0}' . format(domainname))
# A search line didn't exist so we'll add one in
# with the new search domain
if 'search' not in resolve:
new_contents.insert('domain' in resolve, 'search {0}'.format(searchdomain))
new_resolv = '\n'.join(new_contents)
# Write /etc/resolv.conf
if not ('test' in settings and settings['test']):
_write_file_network(new_resolv, _DEB_RESOLV_FILE)
# used for returning the results back
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(opts)
changes.extend(_read_temp(network))
return changes
|
saltstack/salt
|
salt/modules/debian_ip.py
|
_read_file
|
python
|
def _read_file(path):
'''
Reads and returns the contents of a text file
'''
try:
with salt.utils.files.flopen(path, 'rb') as contents:
return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]
except (OSError, IOError):
return ''
|
Reads and returns the contents of a text file
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_ip.py#L220-L228
| null |
# -*- coding: utf-8 -*-
'''
The networking module for Debian-based distros
References:
* http://www.debian.org/doc/manuals/debian-reference/ch05.en.html
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import functools
import logging
import os.path
import os
import re
import time
# Import third party libs
import jinja2
import jinja2.exceptions
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error,no-name-in-module
# Import salt libs
import salt.utils.dns
import salt.utils.files
import salt.utils.odict
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.validate.net
# Set up logging
log = logging.getLogger(__name__)
# Set up template environment
JINJA = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'debian_ip')
)
)
# Define the module's virtual name
__virtualname__ = 'ip'
def __virtual__():
'''
Confine this module to Debian-based distros
'''
if __grains__['os_family'] == 'Debian':
return __virtualname__
return (False, 'The debian_ip module could not be loaded: '
'unsupported OS family')
_ETHTOOL_CONFIG_OPTS = {
'speed': 'link-speed',
'duplex': 'link-duplex',
'autoneg': 'ethernet-autoneg',
'ethernet-port': 'ethernet-port',
'wol': 'ethernet-wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'rx': 'offload-rx',
'tx': 'offload-tx',
'sg': 'offload-sg',
'tso': 'offload-tso',
'ufo': 'offload-ufo',
'gso': 'offload-gso',
'gro': 'offload-gro',
'lro': 'offload-lro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_REV_ETHTOOL_CONFIG_OPTS = {
'link-speed': 'speed',
'link-duplex': 'duplex',
'ethernet-autoneg': 'autoneg',
'ethernet-port': 'ethernet-port',
'ethernet-wol': 'wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'offload-rx': 'rx',
'offload-tx': 'tx',
'offload-sg': 'sg',
'offload-tso': 'tso',
'offload-ufo': 'ufo',
'offload-gso': 'gso',
'offload-lro': 'lro',
'offload-gro': 'gro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_DEB_CONFIG_PPPOE_OPTS = {
'user': 'user',
'password': 'password',
'provider': 'provider',
'pppoe_iface': 'pppoe_iface',
'noipdefault': 'noipdefault',
'usepeerdns': 'usepeerdns',
'defaultroute': 'defaultroute',
'holdoff': 'holdoff',
'maxfail': 'maxfail',
'hide-password': 'hide-password',
'lcp-echo-interval': 'lcp-echo-interval',
'lcp-echo-failure': 'lcp-echo-failure',
'connect': 'connect',
'noauth': 'noauth',
'persist': 'persist',
'mtu': 'mtu',
'noaccomp': 'noaccomp',
'linkname': 'linkname',
}
_DEB_ROUTES_FILE = '/etc/network/routes'
_DEB_NETWORK_FILE = '/etc/network/interfaces'
_DEB_NETWORK_DIR = '/etc/network/interfaces.d/'
_DEB_NETWORK_UP_DIR = '/etc/network/if-up.d/'
_DEB_NETWORK_DOWN_DIR = '/etc/network/if-down.d/'
_DEB_NETWORK_CONF_FILES = '/etc/modprobe.d/'
_DEB_NETWORKING_FILE = '/etc/default/networking'
_DEB_HOSTNAME_FILE = '/etc/hostname'
_DEB_RESOLV_FILE = '/etc/resolv.conf'
_DEB_PPP_DIR = '/etc/ppp/peers/'
_CONFIG_TRUE = ['yes', 'on', 'true', '1', True]
_CONFIG_FALSE = ['no', 'off', 'false', '0', False]
_IFACE_TYPES = [
'eth', 'bond', 'alias', 'clone',
'ipsec', 'dialup', 'bridge', 'slave',
'vlan', 'pppoe', 'source',
]
def _error_msg_iface(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, '|'.join(str(e) for e in expected))
def _error_msg_routes(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, expected)
def _log_default_iface(iface, opt, value):
log.info(
'Using default option -- Interface: %s Option: %s Value: %s',
iface, opt, value
)
def _error_msg_network(option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]'
return msg.format(option, '|'.join(str(e) for e in expected))
def _log_default_network(opt, value):
log.info('Using existing setting -- Setting: %s Value: %s', opt, value)
def _raise_error_iface(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_iface(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_network(option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_network(option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_routes(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_routes(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _parse_resolve():
'''
Parse /etc/resolv.conf
'''
return salt.utils.dns.parse_resolv(_DEB_RESOLV_FILE)
def _parse_domainname():
'''
Parse /etc/resolv.conf and return domainname
'''
return _parse_resolve().get('domain', '')
def _parse_searchdomain():
'''
Parse /etc/resolv.conf and return searchdomain
'''
return _parse_resolve().get('search', '')
def _parse_hostname():
'''
Parse /etc/hostname and return hostname
'''
contents = _read_file(_DEB_HOSTNAME_FILE)
if contents:
return contents[0].split('\n')[0]
else:
return ''
def _parse_current_network_settings():
'''
Parse /etc/default/networking and return current configuration
'''
opts = salt.utils.odict.OrderedDict()
opts['networking'] = ''
if os.path.isfile(_DEB_NETWORKING_FILE):
with salt.utils.files.fopen(_DEB_NETWORKING_FILE) as contents:
for line in contents:
salt.utils.stringutils.to_unicode(line)
if line.startswith('#'):
continue
elif line.startswith('CONFIGURE_INTERFACES'):
opts['networking'] = line.split('=', 1)[1].strip()
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
opts['hostname'] = hostname
opts['domainname'] = domainname
opts['searchdomain'] = searchdomain
return opts
# def __validator_func(value):
# return (valid: True/False, (transformed) value, error message)
def __ipv4_quad(value):
'''validate an IPv4 address'''
return (salt.utils.validate.net.ipv4_addr(value), value,
'dotted IPv4 address')
def __ipv6(value):
'''validate an IPv6 address'''
return (salt.utils.validate.net.ipv6_addr(value), value,
'IPv6 address')
def __mac(value):
'''validate a mac address'''
return (salt.utils.validate.net.mac(value), value,
'MAC address')
def __anything(value):
return (True, value, None)
def __int(value):
'''validate an integer'''
valid, _value = False, value
try:
_value = int(value)
valid = True
except ValueError:
pass
return (valid, _value, 'integer')
def __float(value):
'''validate a float'''
valid, _value = False, value
try:
_value = float(value)
valid = True
except ValueError:
pass
return (valid, _value, 'float')
def __ipv4_netmask(value):
'''validate an IPv4 dotted quad or integer CIDR netmask'''
valid, errmsg = False, 'dotted quad or integer CIDR (0->32)'
valid, value, _ = __int(value)
if not (valid and 0 <= value <= 32):
valid = salt.utils.validate.net.netmask(value)
return (valid, value, errmsg)
def __ipv6_netmask(value):
'''validate an IPv6 integer netmask'''
valid, errmsg = False, 'IPv6 netmask (0->128)'
valid, value, _ = __int(value)
valid = (valid and 0 <= value <= 128)
return (valid, value, errmsg)
def __within2(value, within=None, errmsg=None, dtype=None):
'''validate that a value is in ``within`` and optionally a ``dtype``'''
valid, _value = False, value
if dtype:
try:
_value = dtype(value) # TODO: this is a bit loose when dtype is a class
valid = _value in within
except ValueError:
pass
else:
valid = _value in within
if errmsg is None:
if dtype:
typename = getattr(dtype, '__name__',
hasattr(dtype, '__class__')
and getattr(dtype.__class__, 'name', dtype))
errmsg = '{0} within \'{1}\''.format(typename, within)
else:
errmsg = 'within \'{0}\''.format(within)
return (valid, _value, errmsg)
def __within(within=None, errmsg=None, dtype=None):
return functools.partial(__within2, within=within,
errmsg=errmsg, dtype=dtype)
def __space_delimited_list(value):
'''validate that a value contains one or more space-delimited values'''
if isinstance(value, six.string_types):
value = value.strip().split()
if hasattr(value, '__iter__') and value != []:
return (True, value, 'space-delimited string')
else:
return (False, value, '{0} is not a valid space-delimited value.\n'.format(value))
SALT_ATTR_TO_DEBIAN_ATTR_MAP = {
'dns': 'dns-nameservers',
'search': 'dns-search',
'hwaddr': 'hwaddress', # TODO: this limits bootp functionality
'ipaddr': 'address',
'ipaddrs': 'addresses',
}
DEBIAN_ATTR_TO_SALT_ATTR_MAP = dict(
(v, k) for (k, v) in six.iteritems(SALT_ATTR_TO_DEBIAN_ATTR_MAP))
# TODO
DEBIAN_ATTR_TO_SALT_ATTR_MAP['address'] = 'address'
DEBIAN_ATTR_TO_SALT_ATTR_MAP['hwaddress'] = 'hwaddress'
IPV4_VALID_PROTO = ['bootp', 'dhcp', 'static', 'manual', 'loopback', 'ppp']
IPV4_ATTR_MAP = {
'proto': __within(IPV4_VALID_PROTO, dtype=six.text_type),
# ipv4 static & manual
'address': __ipv4_quad,
'addresses': __anything,
'netmask': __ipv4_netmask,
'broadcast': __ipv4_quad,
'metric': __int,
'gateway': __ipv4_quad, # supports a colon-delimited list
'pointopoint': __ipv4_quad,
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'link', 'host'], dtype=six.text_type),
# dhcp
'hostname': __anything,
'leasehours': __int,
'leasetime': __int,
'vendor': __anything,
'client': __anything,
# bootp
'bootfile': __anything,
'server': __ipv4_quad,
'hwaddr': __mac,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'dstaddr': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# bond
'slaves': __anything,
# ppp
'provider': __anything,
'unit': __int,
'options': __anything,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
#
'network': __anything, # i don't know what this is
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
IPV6_VALID_PROTO = ['auto', 'loopback', 'static', 'manual',
'dhcp', 'v4tunnel', '6to4']
IPV6_ATTR_MAP = {
'proto': __within(IPV6_VALID_PROTO),
# ipv6 static & manual
'address': __ipv6,
'addresses': __anything,
'netmask': __ipv6_netmask,
'broadcast': __ipv6,
'gateway': __ipv6, # supports a colon-delimited list
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'site', 'link', 'host'], dtype=six.text_type),
# inet6 auto
'privext': __within([0, 1, 2], dtype=int),
'dhcp': __within([0, 1], dtype=int),
# inet6 static & manual & dhcp
'media': __anything,
'accept_ra': __within([0, 1], dtype=int),
'autoconf': __within([0, 1], dtype=int),
'preferred-lifetime': __int,
'dad-attempts': __int, # 0 to disable
'dad-interval': __float,
# bond
'slaves': __anything,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
WIRELESS_ATTR_MAP = {
'wireless-essid': __anything,
'wireless-mode': __anything, # TODO
'wpa-ap-scan': __within([0, 1, 2], dtype=int), # TODO
'wpa-conf': __anything,
'wpa-driver': __anything,
'wpa-group': __anything,
'wpa-key-mgmt': __anything,
'wpa-pairwise': __anything,
'wpa-psk': __anything,
'wpa-proto': __anything, # partial(__within,
'wpa-roam': __anything,
'wpa-ssid': __anything, # TODO
}
ATTRMAPS = {
'inet': [IPV4_ATTR_MAP, WIRELESS_ATTR_MAP],
'inet6': [IPV6_ATTR_MAP, WIRELESS_ATTR_MAP]
}
def _validate_interface_option(attr, value, addrfam='inet'):
'''lookup the validation function for a [addrfam][attr] and
return the results
:param attr: attribute name
:param value: raw setting value
:param addrfam: address family (inet, inet6,
'''
valid, _value, errmsg = False, value, 'Unknown validator'
attrmaps = ATTRMAPS.get(addrfam, [])
for attrmap in attrmaps:
if attr in attrmap:
validate_func = attrmap[attr]
(valid, _value, errmsg) = validate_func(value)
break
return (valid, _value, errmsg)
def _attrmaps_contain_attr(attr):
return (
attr in WIRELESS_ATTR_MAP or
attr in IPV4_ATTR_MAP or
attr in IPV6_ATTR_MAP)
def _parse_interfaces(interface_files=None):
'''
Parse /etc/network/interfaces and return current configured interfaces
'''
if interface_files is None:
interface_files = []
# Add this later.
if os.path.exists(_DEB_NETWORK_DIR):
interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]
if os.path.isfile(_DEB_NETWORK_FILE):
interface_files.insert(0, _DEB_NETWORK_FILE)
adapters = salt.utils.odict.OrderedDict()
method = -1
for interface_file in interface_files:
with salt.utils.files.fopen(interface_file) as interfaces:
# This ensures iface_dict exists, but does not ensure we're not reading a new interface.
iface_dict = {}
for line in interfaces:
line = salt.utils.stringutils.to_unicode(line)
# Identify the clauses by the first word of each line.
# Go to the next line if the current line is a comment
# or all spaces.
if line.lstrip().startswith('#') or line.isspace():
continue
# Parse the iface clause
if line.startswith('iface'):
sline = line.split()
if len(sline) != 4:
msg = 'Interface file malformed: {0}.'
msg = msg.format(sline)
log.error(msg)
raise AttributeError(msg)
iface_name = sline[1]
addrfam = sline[2]
method = sline[3]
# Create item in dict, if not already there
if iface_name not in adapters:
adapters[iface_name] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters[iface_name]:
adapters[iface_name]['data'] = salt.utils.odict.OrderedDict()
if addrfam not in adapters[iface_name]['data']:
adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict()
iface_dict = adapters[iface_name]['data'][addrfam]
iface_dict['addrfam'] = addrfam
iface_dict['proto'] = method
iface_dict['filename'] = interface_file
# Parse the detail clauses.
elif line[0].isspace():
sline = line.split()
# conf file attr: dns-nameservers
# salt states.network attr: dns
attr, valuestr = line.rstrip().split(None, 1)
if _attrmaps_contain_attr(attr):
if '-' in attr:
attrname = attr.replace('-', '_')
else:
attrname = attr
(valid, value, errmsg) = _validate_interface_option(
attr, valuestr, addrfam)
if attrname == 'address' and 'address' in iface_dict:
if 'addresses' not in iface_dict:
iface_dict['addresses'] = []
iface_dict['addresses'].append(value)
else:
iface_dict[attrname] = value
elif attr in _REV_ETHTOOL_CONFIG_OPTS:
if 'ethtool' not in iface_dict:
iface_dict['ethtool'] = salt.utils.odict.OrderedDict()
iface_dict['ethtool'][attr] = valuestr
elif attr.startswith('bond'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bonding' not in iface_dict:
iface_dict['bonding'] = salt.utils.odict.OrderedDict()
iface_dict['bonding'][opt] = valuestr
elif attr.startswith('bridge'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bridging' not in iface_dict:
iface_dict['bridging'] = salt.utils.odict.OrderedDict()
iface_dict['bridging'][opt] = valuestr
elif attr in ['up', 'pre-up', 'post-up',
'down', 'pre-down', 'post-down']:
cmd = valuestr
cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr))
if cmd_key not in iface_dict:
iface_dict[cmd_key] = []
iface_dict[cmd_key].append(cmd)
elif line.startswith('auto'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['enabled'] = True
elif line.startswith('allow-hotplug'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['hotplug'] = True
elif line.startswith('source'):
if 'source' not in adapters:
adapters['source'] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters['source']:
adapters['source']['data'] = salt.utils.odict.OrderedDict()
adapters['source']['data']['sources'] = []
adapters['source']['data']['sources'].append(line.split()[1])
# Return a sorted list of the keys for bond, bridge and ethtool options to
# ensure a consistent order
for iface_name in adapters:
if iface_name == 'source':
continue
if 'data' not in adapters[iface_name]:
msg = 'Interface file malformed for interface: {0}.'.format(iface_name)
log.error(msg)
adapters.pop(iface_name)
continue
for opt in ['ethtool', 'bonding', 'bridging']:
for inet in ['inet', 'inet6']:
if inet in adapters[iface_name]['data']:
if opt in adapters[iface_name]['data'][inet]:
opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys())
adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys
return adapters
def _parse_ethtool_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
if 'autoneg' in opts:
if opts['autoneg'] in _CONFIG_TRUE:
config.update({'autoneg': 'on'})
elif opts['autoneg'] in _CONFIG_FALSE:
config.update({'autoneg': 'off'})
else:
_raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE)
if 'duplex' in opts:
valid = ['full', 'half']
if opts['duplex'] in valid:
config.update({'duplex': opts['duplex']})
else:
_raise_error_iface(iface, 'duplex', valid)
if 'speed' in opts:
valid = ['10', '100', '1000', '10000']
if six.text_type(opts['speed']) in valid:
config.update({'speed': opts['speed']})
else:
_raise_error_iface(iface, opts['speed'], valid)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'on'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'off'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_ethtool_pppoe_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
for opt in _DEB_CONFIG_PPPOE_OPTS:
if opt in opts:
config[opt] = opts[opt]
if 'provider' in opts and not opts['provider']:
_raise_error_iface(iface, 'provider', _CONFIG_TRUE + _CONFIG_FALSE)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('noipdefault', 'usepeerdns', 'defaultroute', 'hide-password', 'noauth', 'persist', 'noaccomp'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'True'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'False'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_settings_bond(opts, iface):
'''
Filters given options and outputs valid settings for requested
operation. If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond_def = {
# 803.ad aggregation selection logic
# 0 for stable (default)
# 1 for bandwidth
# 2 for count
'ad_select': '0',
# Max number of transmit queues (default = 16)
'tx_queues': '16',
# Link monitoring in milliseconds. Most NICs support this
'miimon': '100',
# ARP interval in milliseconds
'arp_interval': '250',
# Delay before considering link down in milliseconds (miimon * 2)
'downdelay': '200',
# lacp_rate 0: Slow - every 30 seconds
# lacp_rate 1: Fast - every 1 second
'lacp_rate': '0',
# Max bonds for this driver
'max_bonds': '1',
# Specifies the time, in milliseconds, to wait before
# enabling a slave after a link recovery has been
# detected. Only used with miimon.
'updelay': '0',
# Used with miimon.
# On: driver sends mii
# Off: ethtool sends mii
'use_carrier': 'on',
# Default. Don't change unless you know what you are doing.
'xmit_hash_policy': 'layer2',
}
if opts['mode'] in ['balance-rr', '0']:
log.info('Device: %s Bonding Mode: load balancing (round-robin)', iface)
return _parse_settings_bond_0(opts, iface, bond_def)
elif opts['mode'] in ['active-backup', '1']:
log.info('Device: %s Bonding Mode: fault-tolerance (active-backup)', iface)
return _parse_settings_bond_1(opts, iface, bond_def)
elif opts['mode'] in ['balance-xor', '2']:
log.info('Device: %s Bonding Mode: load balancing (xor)', iface)
return _parse_settings_bond_2(opts, iface, bond_def)
elif opts['mode'] in ['broadcast', '3']:
log.info('Device: %s Bonding Mode: fault-tolerance (broadcast)', iface)
return _parse_settings_bond_3(opts, iface, bond_def)
elif opts['mode'] in ['802.3ad', '4']:
log.info('Device: %s Bonding Mode: IEEE 802.3ad Dynamic link '
'aggregation', iface)
return _parse_settings_bond_4(opts, iface, bond_def)
elif opts['mode'] in ['balance-tlb', '5']:
log.info('Device: %s Bonding Mode: transmit load balancing', iface)
return _parse_settings_bond_5(opts, iface, bond_def)
elif opts['mode'] in ['balance-alb', '6']:
log.info('Device: %s Bonding Mode: adaptive load balancing', iface)
return _parse_settings_bond_6(opts, iface, bond_def)
else:
valid = [
'0', '1', '2', '3', '4', '5', '6',
'balance-rr', 'active-backup', 'balance-xor',
'broadcast', '802.3ad', 'balance-tlb', 'balance-alb'
]
_raise_error_iface(iface, 'mode', valid)
def _parse_settings_bond_0(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond0.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '0'}
# ARP targets in n.n.n.n form
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
return bond
def _parse_settings_bond_1(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '1'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
if not (__grains__['os'] == "Ubuntu" and __grains__['osrelease_info'][0] >= 16):
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_2(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond2.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '2'}
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_3(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond3.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '3'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_4(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond4.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '4'}
for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']:
if binding in opts:
if binding == 'lacp_rate':
if opts[binding] == 'fast':
opts.update({binding: '1'})
if opts[binding] == 'slow':
opts.update({binding: '0'})
valid = ['fast', '1', 'slow', '0']
else:
valid = ['integer']
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, valid)
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_5(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond5.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '5'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_settings_bond_6(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond6.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '6'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_bridge_opts(opts, iface):
'''
Filters given options and outputs valid settings for BRIDGING_OPTS
If an option has a value that is not expected, this
function will log the Interface, Setting and what was expected.
'''
config = {}
if 'ports' in opts:
if isinstance(opts['ports'], list):
opts['ports'] = ' '.join(opts['ports'])
config.update({'ports': opts['ports']})
for opt in ['ageing', 'fd', 'gcint', 'hello', 'maxage']:
if opt in opts:
try:
float(opts[opt])
config.update({opt: opts[opt]})
except ValueError:
_raise_error_iface(iface, opt, ['float'])
for opt in ['bridgeprio', 'maxwait']:
if opt in opts:
if isinstance(opts[opt], int):
config.update({opt: opts[opt]})
else:
_raise_error_iface(iface, opt, ['integer'])
if 'hw' in opts:
# match 12 hex digits with either : or - as separators between pairs
if re.match('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$',
opts['hw'].lower()):
config.update({'hw': opts['hw']})
else:
_raise_error_iface(iface, 'hw', ['valid MAC address'])
for opt in ['pathcost', 'portprio']:
if opt in opts:
try:
port, cost_or_prio = opts[opt].split()
int(cost_or_prio)
config.update({opt: '{0} {1}'.format(port, cost_or_prio)})
except ValueError:
_raise_error_iface(iface, opt, ['interface integer'])
if 'stp' in opts:
if opts['stp'] in _CONFIG_TRUE:
config.update({'stp': 'on'})
elif opts['stp'] in _CONFIG_FALSE:
config.update({'stp': 'off'})
else:
_raise_error_iface(iface, 'stp', _CONFIG_TRUE + _CONFIG_FALSE)
if 'waitport' in opts:
if isinstance(opts['waitport'], int):
config.update({'waitport': opts['waitport']})
else:
values = opts['waitport'].split()
waitport_time = values.pop(0)
if waitport_time.isdigit() and values:
config.update({
'waitport': '{0} {1}'.format(
waitport_time, ' '.join(values)
)
})
else:
_raise_error_iface(iface, opt, ['integer [interfaces]'])
return config
def _parse_settings_eth(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['inet'] = salt.utils.odict.OrderedDict()
iface_data['inet6'] = salt.utils.odict.OrderedDict()
if enabled:
adapters[iface]['enabled'] = True
if opts.get('hotplug', False):
adapters[iface]['hotplug'] = True
if opts.get('enable_ipv6', None) and opts.get('iface_type', '') == 'vlan':
iface_data['inet6']['vlan_raw_device'] = (
re.sub(r'\.\d*', '', iface))
for addrfam in ['inet', 'inet6']:
if iface_type not in ['bridge']:
tmp_ethtool = _parse_ethtool_opts(opts, iface)
if tmp_ethtool:
ethtool = {}
for item in tmp_ethtool:
ethtool[_ETHTOOL_CONFIG_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['ethtool'] = ethtool
# return a list of sorted keys to ensure consistent order
iface_data[addrfam]['ethtool_keys'] = sorted(ethtool)
if iface_type == 'bridge':
bridging = _parse_bridge_opts(opts, iface)
if bridging:
iface_data[addrfam]['bridging'] = bridging
iface_data[addrfam]['bridging_keys'] = sorted(bridging)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'bond':
bonding = _parse_settings_bond(opts, iface)
if bonding:
iface_data[addrfam]['bonding'] = bonding
iface_data[addrfam]['bonding']['slaves'] = opts['slaves']
iface_data[addrfam]['bonding_keys'] = sorted(bonding)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'slave':
adapters[iface]['master'] = opts['master']
opts['proto'] = 'manual'
iface_data[addrfam]['master'] = adapters[iface]['master']
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'vlan':
iface_data[addrfam]['vlan_raw_device'] = re.sub(r'\.\d*', '', iface)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'pppoe':
tmp_ethtool = _parse_ethtool_pppoe_opts(opts, iface)
if tmp_ethtool:
for item in tmp_ethtool:
adapters[iface]['data'][addrfam][_DEB_CONFIG_PPPOE_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['addrfam'] = addrfam
opts.pop('mode', None)
for opt, val in opts.items():
inet = None
if opt.startswith('ipv4'):
opt = opt[4:]
inet = 'inet'
iface_data['inet']['addrfam'] = 'inet'
elif opt.startswith('ipv6'):
iface_data['inet6']['addrfam'] = 'inet6'
opt = opt[4:]
inet = 'inet6'
elif opt in ['ipaddr', 'address', 'ipaddresses', 'addresses', 'gateway', 'proto']:
iface_data['inet']['addrfam'] = 'inet'
inet = 'inet'
_opt = SALT_ATTR_TO_DEBIAN_ATTR_MAP.get(opt, opt)
_debopt = _opt.replace('-', '_')
for addrfam in ['inet', 'inet6']:
(valid, value, errmsg) = _validate_interface_option(_opt, val, addrfam=addrfam)
if not valid:
continue
if inet is None and _debopt not in iface_data[addrfam]:
iface_data[addrfam][_debopt] = value
elif inet == addrfam:
iface_data[addrfam][_debopt] = value
for opt in ['up_cmds', 'pre_up_cmds', 'post_up_cmds',
'down_cmds', 'pre_down_cmds', 'post_down_cmds']:
if opt in opts:
iface_data['inet'][opt] = opts[opt]
iface_data['inet6'][opt] = opts[opt]
# Remove incomplete/disabled inet blocks
for (addrfam, opt) in [('inet', 'enable_ipv4'), ('inet6', 'enable_ipv6')]:
if opts.get(opt, None) is False:
iface_data.pop(addrfam)
elif iface_data[addrfam].get('addrfam', '') != addrfam:
iface_data.pop(addrfam)
return adapters
def _parse_settings_source(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['sources'] = [opts['source']]
return adapters
def _parse_network_settings(opts, current):
'''
Filters given options and outputs valid settings for
the global network settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
current = dict((k.lower(), v) for (k, v) in six.iteritems(current))
result = {}
valid = _CONFIG_TRUE + _CONFIG_FALSE
if 'enabled' not in opts:
try:
opts['networking'] = current['networking']
_log_default_network('networking', current['networking'])
except ValueError:
_raise_error_network('networking', valid)
else:
opts['networking'] = opts['enabled']
if opts['networking'] in valid:
if opts['networking'] in _CONFIG_TRUE:
result['networking'] = 'yes'
elif opts['networking'] in _CONFIG_FALSE:
result['networking'] = 'no'
else:
_raise_error_network('networking', valid)
if 'hostname' not in opts:
try:
opts['hostname'] = current['hostname']
_log_default_network('hostname', current['hostname'])
except ValueError:
_raise_error_network('hostname', ['server1.example.com'])
if opts['hostname']:
result['hostname'] = opts['hostname']
else:
_raise_error_network('hostname', ['server1.example.com'])
if 'search' in opts:
result['search'] = opts['search']
return result
def _parse_routes(iface, opts):
'''
Filters given options and outputs valid settings for
the route settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
result = {}
if 'routes' not in opts:
_raise_error_routes(iface, 'routes', 'List of routes')
for opt in opts:
result[opt] = opts[opt]
return result
def _write_file(iface, data, folder, pattern):
'''
Writes a file to disk
'''
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
return filename
def _write_file_routes(iface, data, folder, pattern):
'''
Writes a file to disk
'''
# ifup / ifdown is executing given folder via run-parts.
# according to run-parts man-page, only filenames with this pattern are
# executed: (^[a-zA-Z0-9_-]+$)
# In order to make the routes file work for vlan interfaces
# (default would have been in example /etc/network/if-up.d/route-bond0.12)
# these dots in the iface name need to be replaced by underscores, so it
# can be executed by run-parts
iface = iface.replace('.', '_')
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
__salt__['file.set_mode'](filename, '0755')
return filename
def _write_file_network(data, filename, create=False):
'''
Writes a file to disk
If file does not exist, only create if create
argument is True
'''
if not os.path.exists(filename) and not create:
msg = '{0} cannot be written. {0} does not exist\
and create is set to False'
msg = msg.format(filename)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
def _read_temp(data):
'''
Return what would be written to disk
'''
tout = StringIO()
tout.write(data)
tout.seek(0)
output = tout.readlines()
tout.close()
return output
def _read_temp_ifaces(iface, data):
'''
Return what would be written to disk for interfaces
'''
try:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': data})
# Return as an array so the difflib works
return [item + '\n' for item in ifcfg.split('\n')]
def _write_file_ifaces(iface, data, **settings):
'''
Writes a file to disk
'''
try:
eth_template = JINJA.get_template('debian_eth.jinja')
source_template = JINJA.get_template('debian_source.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
# Read /etc/network/interfaces into a dict
adapters = _parse_interfaces()
# Apply supplied settings over on-disk settings
adapters[iface] = data
ifcfg = ''
for adapter in adapters:
if 'type' in adapters[adapter] and adapters[adapter]['type'] == 'source':
tmp = source_template.render({'name': adapter, 'data': adapters[adapter]})
else:
tmp = eth_template.render({'name': adapter, 'data': adapters[adapter]})
ifcfg = ifcfg + tmp
if adapter == iface:
saved_ifcfg = tmp
_SEPARATE_FILE = False
if 'filename' in settings:
if not settings['filename'].startswith('/'):
filename = '{0}/{1}'.format(_DEB_NETWORK_DIR, settings['filename'])
else:
filename = settings['filename']
_SEPARATE_FILE = True
else:
if 'filename' in adapters[adapter]['data']:
filename = adapters[adapter]['data']
else:
filename = _DEB_NETWORK_FILE
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
if _SEPARATE_FILE:
fout.write(salt.utils.stringutils.to_str(saved_ifcfg))
else:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return saved_ifcfg.split('\n')
def _write_file_ppp_ifaces(iface, data):
'''
Writes a file to disk
'''
try:
template = JINJA.get_template('debian_ppp_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_ppp_eth.jinja')
return ''
adapters = _parse_interfaces()
adapters[iface] = data
ifcfg = ''
tmp = template.render({'data': adapters[iface]})
ifcfg = tmp + ifcfg
filename = _DEB_PPP_DIR + '/' + adapters[iface]['data']['inet']['provider']
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.fopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return filename
def build_bond(iface, **settings):
'''
Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb
'''
deb_major = __grains__['osrelease'][:1]
opts = _parse_settings_bond(settings, iface)
try:
template = JINJA.get_template('conf.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template conf.jinja')
return ''
data = template.render({'name': iface, 'bonding': opts})
if 'test' in settings and settings['test']:
return _read_temp(data)
_write_file(iface, data, _DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
if deb_major == '5':
for line_type in ('alias', 'options'):
cmd = ['sed', '-i', '-e', r'/^{0}\s{1}.*/d'.format(line_type, iface),
'/etc/modprobe.conf']
__salt__['cmd.run'](cmd, python_shell=False)
__salt__['file.append']('/etc/modprobe.conf', path)
# Load kernel module
__salt__['kmod.load']('bonding')
# install ifenslave-2.6
__salt__['pkg.install']('ifenslave-2.6')
return _read_file(path)
def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'vlan':
settings['vlan'] = 'yes'
__salt__['pkg.install']('vlan')
elif iface_type == 'pppoe':
settings['pppoe'] = 'yes'
if not __salt__['pkg.version']('ppp'):
inst = __salt__['pkg.install']('ppp')
elif iface_type == 'bond':
if 'slaves' not in settings:
msg = 'slaves is a required setting for bond interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'bridge':
if 'ports' not in settings:
msg = (
'ports is a required setting for bridge interfaces on Debian '
'or Ubuntu based systems'
)
log.error(msg)
raise AttributeError(msg)
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'pppoe']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
if iface_type in ['source']:
opts = _parse_settings_source(settings, iface_type, enabled, iface)
if 'test' in settings and settings['test']:
return _read_temp_ifaces(iface, opts[iface])
ifcfg = _write_file_ifaces(iface, opts[iface], **settings)
if iface_type == 'pppoe':
_write_file_ppp_ifaces(iface, opts[iface])
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg]
def build_routes(iface, **settings):
'''
Add route scripts for a network interface using up commands.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
'''
opts = _parse_routes(iface, settings)
try:
template = JINJA.get_template('route_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template route_eth.jinja')
return ''
add_routecfg = template.render(route_type='add',
routes=opts['routes'],
iface=iface)
del_routecfg = template.render(route_type='del',
routes=opts['routes'],
iface=iface)
if 'test' in settings and settings['test']:
return _read_temp(add_routecfg + del_routecfg)
filename = _write_file_routes(iface,
add_routecfg,
_DEB_NETWORK_UP_DIR,
'route-{0}')
results = _read_file(filename)
filename = _write_file_routes(iface,
del_routecfg,
_DEB_NETWORK_DOWN_DIR,
'route-{0}')
results += _read_file(filename)
return results
def down(iface, iface_type):
'''
Shutdown a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.down eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought down.
if iface_type not in ['slave', 'source']:
return __salt__['cmd.run'](['ifdown', iface])
return None
def get_bond(iface):
'''
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
'''
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
return _read_file(path)
def get_interface(iface):
'''
Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
adapters = _parse_interfaces()
if iface in adapters:
try:
if iface == 'source':
template = JINJA.get_template('debian_source.jinja')
else:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': adapters[iface]})
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg.split('\n')]
else:
return []
def up(iface, iface_type): # pylint: disable=C0103
'''
Start up a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.up eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought up.
if iface_type not in ('slave', 'source'):
return __salt__['cmd.run'](['ifup', iface])
return None
def get_network_settings():
'''
Return the contents of the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_network_settings
'''
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
settings = {}
if __salt__['service.available']('networking'):
if __salt__['service.status']('networking'):
settings['networking'] = "yes"
else:
settings['networking'] = "no"
else:
settings['networking'] = "no"
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
settings['hostname'] = hostname
settings['domainname'] = domainname
settings['searchdomain'] = searchdomain
else:
settings = _parse_current_network_settings()
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(settings)
return _read_temp(network)
def get_routes(iface):
'''
Return the routes for the interface
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0
'''
filename = os.path.join(_DEB_NETWORK_UP_DIR, 'route-{0}'.format(iface))
results = _read_file(filename)
filename = os.path.join(_DEB_NETWORK_DOWN_DIR, 'route-{0}'.format(iface))
results += _read_file(filename)
return results
def apply_network_settings(**settings):
'''
Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings
'''
if 'require_reboot' not in settings:
settings['require_reboot'] = False
if 'apply_hostname' not in settings:
settings['apply_hostname'] = False
hostname_res = True
if settings['apply_hostname'] in _CONFIG_TRUE:
if 'hostname' in settings:
hostname_res = __salt__['network.mod_hostname'](settings['hostname'])
else:
log.warning(
'The network state sls is trying to apply hostname '
'changes but no hostname is defined.'
)
hostname_res = False
res = True
if settings['require_reboot'] in _CONFIG_TRUE:
log.warning(
'The network state sls is requiring a reboot of the system to '
'properly apply network configuration.'
)
res = True
else:
stop = __salt__['service.stop']('networking')
time.sleep(2)
res = stop and __salt__['service.start']('networking')
return hostname_res and res
def build_network_settings(**settings):
'''
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
'''
changes = []
# Read current configuration and store default values
current_network_settings = _parse_current_network_settings()
# Build settings
opts = _parse_network_settings(settings, current_network_settings)
# Ubuntu has moved away from /etc/default/networking
# beginning with the 12.04 release so we disable or enable
# the networking related services on boot
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
if opts['networking'] == 'yes':
service_cmd = 'service.enable'
else:
service_cmd = 'service.disable'
if __salt__['service.available']('NetworkManager'):
__salt__[service_cmd]('NetworkManager')
if __salt__['service.available']('networking'):
__salt__[service_cmd]('networking')
else:
try:
template = JINJA.get_template('network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template network.jinja')
return ''
network = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(network)
# Write settings
_write_file_network(network, _DEB_NETWORKING_FILE, True)
# Get hostname and domain from opts
sline = opts['hostname'].split('.', 1)
opts['hostname'] = sline[0]
current_domainname = current_network_settings['domainname']
current_searchdomain = current_network_settings['searchdomain']
new_domain = False
if len(sline) > 1:
new_domainname = sline[1]
if new_domainname != current_domainname:
domainname = new_domainname
opts['domainname'] = new_domainname
new_domain = True
else:
domainname = current_domainname
opts['domainname'] = domainname
else:
domainname = current_domainname
opts['domainname'] = domainname
new_search = False
if 'search' in opts:
new_searchdomain = opts['search']
if new_searchdomain != current_searchdomain:
searchdomain = new_searchdomain
opts['searchdomain'] = new_searchdomain
new_search = True
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
# If the domain changes, then we should write the resolv.conf file.
if new_domain or new_search:
# Look for existing domain line and update if necessary
resolve = _parse_resolve()
domain_prog = re.compile(r'domain\s+')
search_prog = re.compile(r'search\s+')
new_contents = []
for item in _read_file(_DEB_RESOLV_FILE):
if domain_prog.match(item):
item = 'domain {0}'.format(domainname)
elif search_prog.match(item):
item = 'search {0}'.format(searchdomain)
new_contents.append(item)
# A domain line didn't exist so we'll add one in
# with the new domainname
if 'domain' not in resolve:
new_contents.insert(0, 'domain {0}' . format(domainname))
# A search line didn't exist so we'll add one in
# with the new search domain
if 'search' not in resolve:
new_contents.insert('domain' in resolve, 'search {0}'.format(searchdomain))
new_resolv = '\n'.join(new_contents)
# Write /etc/resolv.conf
if not ('test' in settings and settings['test']):
_write_file_network(new_resolv, _DEB_RESOLV_FILE)
# used for returning the results back
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(opts)
changes.extend(_read_temp(network))
return changes
|
saltstack/salt
|
salt/modules/debian_ip.py
|
_parse_current_network_settings
|
python
|
def _parse_current_network_settings():
'''
Parse /etc/default/networking and return current configuration
'''
opts = salt.utils.odict.OrderedDict()
opts['networking'] = ''
if os.path.isfile(_DEB_NETWORKING_FILE):
with salt.utils.files.fopen(_DEB_NETWORKING_FILE) as contents:
for line in contents:
salt.utils.stringutils.to_unicode(line)
if line.startswith('#'):
continue
elif line.startswith('CONFIGURE_INTERFACES'):
opts['networking'] = line.split('=', 1)[1].strip()
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
opts['hostname'] = hostname
opts['domainname'] = domainname
opts['searchdomain'] = searchdomain
return opts
|
Parse /etc/default/networking and return current configuration
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_ip.py#L263-L286
| null |
# -*- coding: utf-8 -*-
'''
The networking module for Debian-based distros
References:
* http://www.debian.org/doc/manuals/debian-reference/ch05.en.html
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import functools
import logging
import os.path
import os
import re
import time
# Import third party libs
import jinja2
import jinja2.exceptions
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error,no-name-in-module
# Import salt libs
import salt.utils.dns
import salt.utils.files
import salt.utils.odict
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.validate.net
# Set up logging
log = logging.getLogger(__name__)
# Set up template environment
JINJA = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'debian_ip')
)
)
# Define the module's virtual name
__virtualname__ = 'ip'
def __virtual__():
'''
Confine this module to Debian-based distros
'''
if __grains__['os_family'] == 'Debian':
return __virtualname__
return (False, 'The debian_ip module could not be loaded: '
'unsupported OS family')
_ETHTOOL_CONFIG_OPTS = {
'speed': 'link-speed',
'duplex': 'link-duplex',
'autoneg': 'ethernet-autoneg',
'ethernet-port': 'ethernet-port',
'wol': 'ethernet-wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'rx': 'offload-rx',
'tx': 'offload-tx',
'sg': 'offload-sg',
'tso': 'offload-tso',
'ufo': 'offload-ufo',
'gso': 'offload-gso',
'gro': 'offload-gro',
'lro': 'offload-lro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_REV_ETHTOOL_CONFIG_OPTS = {
'link-speed': 'speed',
'link-duplex': 'duplex',
'ethernet-autoneg': 'autoneg',
'ethernet-port': 'ethernet-port',
'ethernet-wol': 'wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'offload-rx': 'rx',
'offload-tx': 'tx',
'offload-sg': 'sg',
'offload-tso': 'tso',
'offload-ufo': 'ufo',
'offload-gso': 'gso',
'offload-lro': 'lro',
'offload-gro': 'gro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_DEB_CONFIG_PPPOE_OPTS = {
'user': 'user',
'password': 'password',
'provider': 'provider',
'pppoe_iface': 'pppoe_iface',
'noipdefault': 'noipdefault',
'usepeerdns': 'usepeerdns',
'defaultroute': 'defaultroute',
'holdoff': 'holdoff',
'maxfail': 'maxfail',
'hide-password': 'hide-password',
'lcp-echo-interval': 'lcp-echo-interval',
'lcp-echo-failure': 'lcp-echo-failure',
'connect': 'connect',
'noauth': 'noauth',
'persist': 'persist',
'mtu': 'mtu',
'noaccomp': 'noaccomp',
'linkname': 'linkname',
}
_DEB_ROUTES_FILE = '/etc/network/routes'
_DEB_NETWORK_FILE = '/etc/network/interfaces'
_DEB_NETWORK_DIR = '/etc/network/interfaces.d/'
_DEB_NETWORK_UP_DIR = '/etc/network/if-up.d/'
_DEB_NETWORK_DOWN_DIR = '/etc/network/if-down.d/'
_DEB_NETWORK_CONF_FILES = '/etc/modprobe.d/'
_DEB_NETWORKING_FILE = '/etc/default/networking'
_DEB_HOSTNAME_FILE = '/etc/hostname'
_DEB_RESOLV_FILE = '/etc/resolv.conf'
_DEB_PPP_DIR = '/etc/ppp/peers/'
_CONFIG_TRUE = ['yes', 'on', 'true', '1', True]
_CONFIG_FALSE = ['no', 'off', 'false', '0', False]
_IFACE_TYPES = [
'eth', 'bond', 'alias', 'clone',
'ipsec', 'dialup', 'bridge', 'slave',
'vlan', 'pppoe', 'source',
]
def _error_msg_iface(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, '|'.join(str(e) for e in expected))
def _error_msg_routes(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, expected)
def _log_default_iface(iface, opt, value):
log.info(
'Using default option -- Interface: %s Option: %s Value: %s',
iface, opt, value
)
def _error_msg_network(option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]'
return msg.format(option, '|'.join(str(e) for e in expected))
def _log_default_network(opt, value):
log.info('Using existing setting -- Setting: %s Value: %s', opt, value)
def _raise_error_iface(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_iface(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_network(option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_network(option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_routes(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_routes(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _read_file(path):
'''
Reads and returns the contents of a text file
'''
try:
with salt.utils.files.flopen(path, 'rb') as contents:
return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]
except (OSError, IOError):
return ''
def _parse_resolve():
'''
Parse /etc/resolv.conf
'''
return salt.utils.dns.parse_resolv(_DEB_RESOLV_FILE)
def _parse_domainname():
'''
Parse /etc/resolv.conf and return domainname
'''
return _parse_resolve().get('domain', '')
def _parse_searchdomain():
'''
Parse /etc/resolv.conf and return searchdomain
'''
return _parse_resolve().get('search', '')
def _parse_hostname():
'''
Parse /etc/hostname and return hostname
'''
contents = _read_file(_DEB_HOSTNAME_FILE)
if contents:
return contents[0].split('\n')[0]
else:
return ''
# def __validator_func(value):
# return (valid: True/False, (transformed) value, error message)
def __ipv4_quad(value):
'''validate an IPv4 address'''
return (salt.utils.validate.net.ipv4_addr(value), value,
'dotted IPv4 address')
def __ipv6(value):
'''validate an IPv6 address'''
return (salt.utils.validate.net.ipv6_addr(value), value,
'IPv6 address')
def __mac(value):
'''validate a mac address'''
return (salt.utils.validate.net.mac(value), value,
'MAC address')
def __anything(value):
return (True, value, None)
def __int(value):
'''validate an integer'''
valid, _value = False, value
try:
_value = int(value)
valid = True
except ValueError:
pass
return (valid, _value, 'integer')
def __float(value):
'''validate a float'''
valid, _value = False, value
try:
_value = float(value)
valid = True
except ValueError:
pass
return (valid, _value, 'float')
def __ipv4_netmask(value):
'''validate an IPv4 dotted quad or integer CIDR netmask'''
valid, errmsg = False, 'dotted quad or integer CIDR (0->32)'
valid, value, _ = __int(value)
if not (valid and 0 <= value <= 32):
valid = salt.utils.validate.net.netmask(value)
return (valid, value, errmsg)
def __ipv6_netmask(value):
'''validate an IPv6 integer netmask'''
valid, errmsg = False, 'IPv6 netmask (0->128)'
valid, value, _ = __int(value)
valid = (valid and 0 <= value <= 128)
return (valid, value, errmsg)
def __within2(value, within=None, errmsg=None, dtype=None):
'''validate that a value is in ``within`` and optionally a ``dtype``'''
valid, _value = False, value
if dtype:
try:
_value = dtype(value) # TODO: this is a bit loose when dtype is a class
valid = _value in within
except ValueError:
pass
else:
valid = _value in within
if errmsg is None:
if dtype:
typename = getattr(dtype, '__name__',
hasattr(dtype, '__class__')
and getattr(dtype.__class__, 'name', dtype))
errmsg = '{0} within \'{1}\''.format(typename, within)
else:
errmsg = 'within \'{0}\''.format(within)
return (valid, _value, errmsg)
def __within(within=None, errmsg=None, dtype=None):
return functools.partial(__within2, within=within,
errmsg=errmsg, dtype=dtype)
def __space_delimited_list(value):
'''validate that a value contains one or more space-delimited values'''
if isinstance(value, six.string_types):
value = value.strip().split()
if hasattr(value, '__iter__') and value != []:
return (True, value, 'space-delimited string')
else:
return (False, value, '{0} is not a valid space-delimited value.\n'.format(value))
SALT_ATTR_TO_DEBIAN_ATTR_MAP = {
'dns': 'dns-nameservers',
'search': 'dns-search',
'hwaddr': 'hwaddress', # TODO: this limits bootp functionality
'ipaddr': 'address',
'ipaddrs': 'addresses',
}
DEBIAN_ATTR_TO_SALT_ATTR_MAP = dict(
(v, k) for (k, v) in six.iteritems(SALT_ATTR_TO_DEBIAN_ATTR_MAP))
# TODO
DEBIAN_ATTR_TO_SALT_ATTR_MAP['address'] = 'address'
DEBIAN_ATTR_TO_SALT_ATTR_MAP['hwaddress'] = 'hwaddress'
IPV4_VALID_PROTO = ['bootp', 'dhcp', 'static', 'manual', 'loopback', 'ppp']
IPV4_ATTR_MAP = {
'proto': __within(IPV4_VALID_PROTO, dtype=six.text_type),
# ipv4 static & manual
'address': __ipv4_quad,
'addresses': __anything,
'netmask': __ipv4_netmask,
'broadcast': __ipv4_quad,
'metric': __int,
'gateway': __ipv4_quad, # supports a colon-delimited list
'pointopoint': __ipv4_quad,
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'link', 'host'], dtype=six.text_type),
# dhcp
'hostname': __anything,
'leasehours': __int,
'leasetime': __int,
'vendor': __anything,
'client': __anything,
# bootp
'bootfile': __anything,
'server': __ipv4_quad,
'hwaddr': __mac,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'dstaddr': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# bond
'slaves': __anything,
# ppp
'provider': __anything,
'unit': __int,
'options': __anything,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
#
'network': __anything, # i don't know what this is
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
IPV6_VALID_PROTO = ['auto', 'loopback', 'static', 'manual',
'dhcp', 'v4tunnel', '6to4']
IPV6_ATTR_MAP = {
'proto': __within(IPV6_VALID_PROTO),
# ipv6 static & manual
'address': __ipv6,
'addresses': __anything,
'netmask': __ipv6_netmask,
'broadcast': __ipv6,
'gateway': __ipv6, # supports a colon-delimited list
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'site', 'link', 'host'], dtype=six.text_type),
# inet6 auto
'privext': __within([0, 1, 2], dtype=int),
'dhcp': __within([0, 1], dtype=int),
# inet6 static & manual & dhcp
'media': __anything,
'accept_ra': __within([0, 1], dtype=int),
'autoconf': __within([0, 1], dtype=int),
'preferred-lifetime': __int,
'dad-attempts': __int, # 0 to disable
'dad-interval': __float,
# bond
'slaves': __anything,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
WIRELESS_ATTR_MAP = {
'wireless-essid': __anything,
'wireless-mode': __anything, # TODO
'wpa-ap-scan': __within([0, 1, 2], dtype=int), # TODO
'wpa-conf': __anything,
'wpa-driver': __anything,
'wpa-group': __anything,
'wpa-key-mgmt': __anything,
'wpa-pairwise': __anything,
'wpa-psk': __anything,
'wpa-proto': __anything, # partial(__within,
'wpa-roam': __anything,
'wpa-ssid': __anything, # TODO
}
ATTRMAPS = {
'inet': [IPV4_ATTR_MAP, WIRELESS_ATTR_MAP],
'inet6': [IPV6_ATTR_MAP, WIRELESS_ATTR_MAP]
}
def _validate_interface_option(attr, value, addrfam='inet'):
'''lookup the validation function for a [addrfam][attr] and
return the results
:param attr: attribute name
:param value: raw setting value
:param addrfam: address family (inet, inet6,
'''
valid, _value, errmsg = False, value, 'Unknown validator'
attrmaps = ATTRMAPS.get(addrfam, [])
for attrmap in attrmaps:
if attr in attrmap:
validate_func = attrmap[attr]
(valid, _value, errmsg) = validate_func(value)
break
return (valid, _value, errmsg)
def _attrmaps_contain_attr(attr):
return (
attr in WIRELESS_ATTR_MAP or
attr in IPV4_ATTR_MAP or
attr in IPV6_ATTR_MAP)
def _parse_interfaces(interface_files=None):
'''
Parse /etc/network/interfaces and return current configured interfaces
'''
if interface_files is None:
interface_files = []
# Add this later.
if os.path.exists(_DEB_NETWORK_DIR):
interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]
if os.path.isfile(_DEB_NETWORK_FILE):
interface_files.insert(0, _DEB_NETWORK_FILE)
adapters = salt.utils.odict.OrderedDict()
method = -1
for interface_file in interface_files:
with salt.utils.files.fopen(interface_file) as interfaces:
# This ensures iface_dict exists, but does not ensure we're not reading a new interface.
iface_dict = {}
for line in interfaces:
line = salt.utils.stringutils.to_unicode(line)
# Identify the clauses by the first word of each line.
# Go to the next line if the current line is a comment
# or all spaces.
if line.lstrip().startswith('#') or line.isspace():
continue
# Parse the iface clause
if line.startswith('iface'):
sline = line.split()
if len(sline) != 4:
msg = 'Interface file malformed: {0}.'
msg = msg.format(sline)
log.error(msg)
raise AttributeError(msg)
iface_name = sline[1]
addrfam = sline[2]
method = sline[3]
# Create item in dict, if not already there
if iface_name not in adapters:
adapters[iface_name] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters[iface_name]:
adapters[iface_name]['data'] = salt.utils.odict.OrderedDict()
if addrfam not in adapters[iface_name]['data']:
adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict()
iface_dict = adapters[iface_name]['data'][addrfam]
iface_dict['addrfam'] = addrfam
iface_dict['proto'] = method
iface_dict['filename'] = interface_file
# Parse the detail clauses.
elif line[0].isspace():
sline = line.split()
# conf file attr: dns-nameservers
# salt states.network attr: dns
attr, valuestr = line.rstrip().split(None, 1)
if _attrmaps_contain_attr(attr):
if '-' in attr:
attrname = attr.replace('-', '_')
else:
attrname = attr
(valid, value, errmsg) = _validate_interface_option(
attr, valuestr, addrfam)
if attrname == 'address' and 'address' in iface_dict:
if 'addresses' not in iface_dict:
iface_dict['addresses'] = []
iface_dict['addresses'].append(value)
else:
iface_dict[attrname] = value
elif attr in _REV_ETHTOOL_CONFIG_OPTS:
if 'ethtool' not in iface_dict:
iface_dict['ethtool'] = salt.utils.odict.OrderedDict()
iface_dict['ethtool'][attr] = valuestr
elif attr.startswith('bond'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bonding' not in iface_dict:
iface_dict['bonding'] = salt.utils.odict.OrderedDict()
iface_dict['bonding'][opt] = valuestr
elif attr.startswith('bridge'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bridging' not in iface_dict:
iface_dict['bridging'] = salt.utils.odict.OrderedDict()
iface_dict['bridging'][opt] = valuestr
elif attr in ['up', 'pre-up', 'post-up',
'down', 'pre-down', 'post-down']:
cmd = valuestr
cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr))
if cmd_key not in iface_dict:
iface_dict[cmd_key] = []
iface_dict[cmd_key].append(cmd)
elif line.startswith('auto'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['enabled'] = True
elif line.startswith('allow-hotplug'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['hotplug'] = True
elif line.startswith('source'):
if 'source' not in adapters:
adapters['source'] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters['source']:
adapters['source']['data'] = salt.utils.odict.OrderedDict()
adapters['source']['data']['sources'] = []
adapters['source']['data']['sources'].append(line.split()[1])
# Return a sorted list of the keys for bond, bridge and ethtool options to
# ensure a consistent order
for iface_name in adapters:
if iface_name == 'source':
continue
if 'data' not in adapters[iface_name]:
msg = 'Interface file malformed for interface: {0}.'.format(iface_name)
log.error(msg)
adapters.pop(iface_name)
continue
for opt in ['ethtool', 'bonding', 'bridging']:
for inet in ['inet', 'inet6']:
if inet in adapters[iface_name]['data']:
if opt in adapters[iface_name]['data'][inet]:
opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys())
adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys
return adapters
def _parse_ethtool_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
if 'autoneg' in opts:
if opts['autoneg'] in _CONFIG_TRUE:
config.update({'autoneg': 'on'})
elif opts['autoneg'] in _CONFIG_FALSE:
config.update({'autoneg': 'off'})
else:
_raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE)
if 'duplex' in opts:
valid = ['full', 'half']
if opts['duplex'] in valid:
config.update({'duplex': opts['duplex']})
else:
_raise_error_iface(iface, 'duplex', valid)
if 'speed' in opts:
valid = ['10', '100', '1000', '10000']
if six.text_type(opts['speed']) in valid:
config.update({'speed': opts['speed']})
else:
_raise_error_iface(iface, opts['speed'], valid)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'on'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'off'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_ethtool_pppoe_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
for opt in _DEB_CONFIG_PPPOE_OPTS:
if opt in opts:
config[opt] = opts[opt]
if 'provider' in opts and not opts['provider']:
_raise_error_iface(iface, 'provider', _CONFIG_TRUE + _CONFIG_FALSE)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('noipdefault', 'usepeerdns', 'defaultroute', 'hide-password', 'noauth', 'persist', 'noaccomp'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'True'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'False'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_settings_bond(opts, iface):
'''
Filters given options and outputs valid settings for requested
operation. If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond_def = {
# 803.ad aggregation selection logic
# 0 for stable (default)
# 1 for bandwidth
# 2 for count
'ad_select': '0',
# Max number of transmit queues (default = 16)
'tx_queues': '16',
# Link monitoring in milliseconds. Most NICs support this
'miimon': '100',
# ARP interval in milliseconds
'arp_interval': '250',
# Delay before considering link down in milliseconds (miimon * 2)
'downdelay': '200',
# lacp_rate 0: Slow - every 30 seconds
# lacp_rate 1: Fast - every 1 second
'lacp_rate': '0',
# Max bonds for this driver
'max_bonds': '1',
# Specifies the time, in milliseconds, to wait before
# enabling a slave after a link recovery has been
# detected. Only used with miimon.
'updelay': '0',
# Used with miimon.
# On: driver sends mii
# Off: ethtool sends mii
'use_carrier': 'on',
# Default. Don't change unless you know what you are doing.
'xmit_hash_policy': 'layer2',
}
if opts['mode'] in ['balance-rr', '0']:
log.info('Device: %s Bonding Mode: load balancing (round-robin)', iface)
return _parse_settings_bond_0(opts, iface, bond_def)
elif opts['mode'] in ['active-backup', '1']:
log.info('Device: %s Bonding Mode: fault-tolerance (active-backup)', iface)
return _parse_settings_bond_1(opts, iface, bond_def)
elif opts['mode'] in ['balance-xor', '2']:
log.info('Device: %s Bonding Mode: load balancing (xor)', iface)
return _parse_settings_bond_2(opts, iface, bond_def)
elif opts['mode'] in ['broadcast', '3']:
log.info('Device: %s Bonding Mode: fault-tolerance (broadcast)', iface)
return _parse_settings_bond_3(opts, iface, bond_def)
elif opts['mode'] in ['802.3ad', '4']:
log.info('Device: %s Bonding Mode: IEEE 802.3ad Dynamic link '
'aggregation', iface)
return _parse_settings_bond_4(opts, iface, bond_def)
elif opts['mode'] in ['balance-tlb', '5']:
log.info('Device: %s Bonding Mode: transmit load balancing', iface)
return _parse_settings_bond_5(opts, iface, bond_def)
elif opts['mode'] in ['balance-alb', '6']:
log.info('Device: %s Bonding Mode: adaptive load balancing', iface)
return _parse_settings_bond_6(opts, iface, bond_def)
else:
valid = [
'0', '1', '2', '3', '4', '5', '6',
'balance-rr', 'active-backup', 'balance-xor',
'broadcast', '802.3ad', 'balance-tlb', 'balance-alb'
]
_raise_error_iface(iface, 'mode', valid)
def _parse_settings_bond_0(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond0.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '0'}
# ARP targets in n.n.n.n form
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
return bond
def _parse_settings_bond_1(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '1'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
if not (__grains__['os'] == "Ubuntu" and __grains__['osrelease_info'][0] >= 16):
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_2(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond2.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '2'}
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_3(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond3.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '3'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_4(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond4.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '4'}
for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']:
if binding in opts:
if binding == 'lacp_rate':
if opts[binding] == 'fast':
opts.update({binding: '1'})
if opts[binding] == 'slow':
opts.update({binding: '0'})
valid = ['fast', '1', 'slow', '0']
else:
valid = ['integer']
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, valid)
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_5(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond5.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '5'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_settings_bond_6(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond6.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '6'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_bridge_opts(opts, iface):
'''
Filters given options and outputs valid settings for BRIDGING_OPTS
If an option has a value that is not expected, this
function will log the Interface, Setting and what was expected.
'''
config = {}
if 'ports' in opts:
if isinstance(opts['ports'], list):
opts['ports'] = ' '.join(opts['ports'])
config.update({'ports': opts['ports']})
for opt in ['ageing', 'fd', 'gcint', 'hello', 'maxage']:
if opt in opts:
try:
float(opts[opt])
config.update({opt: opts[opt]})
except ValueError:
_raise_error_iface(iface, opt, ['float'])
for opt in ['bridgeprio', 'maxwait']:
if opt in opts:
if isinstance(opts[opt], int):
config.update({opt: opts[opt]})
else:
_raise_error_iface(iface, opt, ['integer'])
if 'hw' in opts:
# match 12 hex digits with either : or - as separators between pairs
if re.match('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$',
opts['hw'].lower()):
config.update({'hw': opts['hw']})
else:
_raise_error_iface(iface, 'hw', ['valid MAC address'])
for opt in ['pathcost', 'portprio']:
if opt in opts:
try:
port, cost_or_prio = opts[opt].split()
int(cost_or_prio)
config.update({opt: '{0} {1}'.format(port, cost_or_prio)})
except ValueError:
_raise_error_iface(iface, opt, ['interface integer'])
if 'stp' in opts:
if opts['stp'] in _CONFIG_TRUE:
config.update({'stp': 'on'})
elif opts['stp'] in _CONFIG_FALSE:
config.update({'stp': 'off'})
else:
_raise_error_iface(iface, 'stp', _CONFIG_TRUE + _CONFIG_FALSE)
if 'waitport' in opts:
if isinstance(opts['waitport'], int):
config.update({'waitport': opts['waitport']})
else:
values = opts['waitport'].split()
waitport_time = values.pop(0)
if waitport_time.isdigit() and values:
config.update({
'waitport': '{0} {1}'.format(
waitport_time, ' '.join(values)
)
})
else:
_raise_error_iface(iface, opt, ['integer [interfaces]'])
return config
def _parse_settings_eth(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['inet'] = salt.utils.odict.OrderedDict()
iface_data['inet6'] = salt.utils.odict.OrderedDict()
if enabled:
adapters[iface]['enabled'] = True
if opts.get('hotplug', False):
adapters[iface]['hotplug'] = True
if opts.get('enable_ipv6', None) and opts.get('iface_type', '') == 'vlan':
iface_data['inet6']['vlan_raw_device'] = (
re.sub(r'\.\d*', '', iface))
for addrfam in ['inet', 'inet6']:
if iface_type not in ['bridge']:
tmp_ethtool = _parse_ethtool_opts(opts, iface)
if tmp_ethtool:
ethtool = {}
for item in tmp_ethtool:
ethtool[_ETHTOOL_CONFIG_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['ethtool'] = ethtool
# return a list of sorted keys to ensure consistent order
iface_data[addrfam]['ethtool_keys'] = sorted(ethtool)
if iface_type == 'bridge':
bridging = _parse_bridge_opts(opts, iface)
if bridging:
iface_data[addrfam]['bridging'] = bridging
iface_data[addrfam]['bridging_keys'] = sorted(bridging)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'bond':
bonding = _parse_settings_bond(opts, iface)
if bonding:
iface_data[addrfam]['bonding'] = bonding
iface_data[addrfam]['bonding']['slaves'] = opts['slaves']
iface_data[addrfam]['bonding_keys'] = sorted(bonding)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'slave':
adapters[iface]['master'] = opts['master']
opts['proto'] = 'manual'
iface_data[addrfam]['master'] = adapters[iface]['master']
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'vlan':
iface_data[addrfam]['vlan_raw_device'] = re.sub(r'\.\d*', '', iface)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'pppoe':
tmp_ethtool = _parse_ethtool_pppoe_opts(opts, iface)
if tmp_ethtool:
for item in tmp_ethtool:
adapters[iface]['data'][addrfam][_DEB_CONFIG_PPPOE_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['addrfam'] = addrfam
opts.pop('mode', None)
for opt, val in opts.items():
inet = None
if opt.startswith('ipv4'):
opt = opt[4:]
inet = 'inet'
iface_data['inet']['addrfam'] = 'inet'
elif opt.startswith('ipv6'):
iface_data['inet6']['addrfam'] = 'inet6'
opt = opt[4:]
inet = 'inet6'
elif opt in ['ipaddr', 'address', 'ipaddresses', 'addresses', 'gateway', 'proto']:
iface_data['inet']['addrfam'] = 'inet'
inet = 'inet'
_opt = SALT_ATTR_TO_DEBIAN_ATTR_MAP.get(opt, opt)
_debopt = _opt.replace('-', '_')
for addrfam in ['inet', 'inet6']:
(valid, value, errmsg) = _validate_interface_option(_opt, val, addrfam=addrfam)
if not valid:
continue
if inet is None and _debopt not in iface_data[addrfam]:
iface_data[addrfam][_debopt] = value
elif inet == addrfam:
iface_data[addrfam][_debopt] = value
for opt in ['up_cmds', 'pre_up_cmds', 'post_up_cmds',
'down_cmds', 'pre_down_cmds', 'post_down_cmds']:
if opt in opts:
iface_data['inet'][opt] = opts[opt]
iface_data['inet6'][opt] = opts[opt]
# Remove incomplete/disabled inet blocks
for (addrfam, opt) in [('inet', 'enable_ipv4'), ('inet6', 'enable_ipv6')]:
if opts.get(opt, None) is False:
iface_data.pop(addrfam)
elif iface_data[addrfam].get('addrfam', '') != addrfam:
iface_data.pop(addrfam)
return adapters
def _parse_settings_source(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['sources'] = [opts['source']]
return adapters
def _parse_network_settings(opts, current):
'''
Filters given options and outputs valid settings for
the global network settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
current = dict((k.lower(), v) for (k, v) in six.iteritems(current))
result = {}
valid = _CONFIG_TRUE + _CONFIG_FALSE
if 'enabled' not in opts:
try:
opts['networking'] = current['networking']
_log_default_network('networking', current['networking'])
except ValueError:
_raise_error_network('networking', valid)
else:
opts['networking'] = opts['enabled']
if opts['networking'] in valid:
if opts['networking'] in _CONFIG_TRUE:
result['networking'] = 'yes'
elif opts['networking'] in _CONFIG_FALSE:
result['networking'] = 'no'
else:
_raise_error_network('networking', valid)
if 'hostname' not in opts:
try:
opts['hostname'] = current['hostname']
_log_default_network('hostname', current['hostname'])
except ValueError:
_raise_error_network('hostname', ['server1.example.com'])
if opts['hostname']:
result['hostname'] = opts['hostname']
else:
_raise_error_network('hostname', ['server1.example.com'])
if 'search' in opts:
result['search'] = opts['search']
return result
def _parse_routes(iface, opts):
'''
Filters given options and outputs valid settings for
the route settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
result = {}
if 'routes' not in opts:
_raise_error_routes(iface, 'routes', 'List of routes')
for opt in opts:
result[opt] = opts[opt]
return result
def _write_file(iface, data, folder, pattern):
'''
Writes a file to disk
'''
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
return filename
def _write_file_routes(iface, data, folder, pattern):
'''
Writes a file to disk
'''
# ifup / ifdown is executing given folder via run-parts.
# according to run-parts man-page, only filenames with this pattern are
# executed: (^[a-zA-Z0-9_-]+$)
# In order to make the routes file work for vlan interfaces
# (default would have been in example /etc/network/if-up.d/route-bond0.12)
# these dots in the iface name need to be replaced by underscores, so it
# can be executed by run-parts
iface = iface.replace('.', '_')
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
__salt__['file.set_mode'](filename, '0755')
return filename
def _write_file_network(data, filename, create=False):
'''
Writes a file to disk
If file does not exist, only create if create
argument is True
'''
if not os.path.exists(filename) and not create:
msg = '{0} cannot be written. {0} does not exist\
and create is set to False'
msg = msg.format(filename)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
def _read_temp(data):
'''
Return what would be written to disk
'''
tout = StringIO()
tout.write(data)
tout.seek(0)
output = tout.readlines()
tout.close()
return output
def _read_temp_ifaces(iface, data):
'''
Return what would be written to disk for interfaces
'''
try:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': data})
# Return as an array so the difflib works
return [item + '\n' for item in ifcfg.split('\n')]
def _write_file_ifaces(iface, data, **settings):
'''
Writes a file to disk
'''
try:
eth_template = JINJA.get_template('debian_eth.jinja')
source_template = JINJA.get_template('debian_source.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
# Read /etc/network/interfaces into a dict
adapters = _parse_interfaces()
# Apply supplied settings over on-disk settings
adapters[iface] = data
ifcfg = ''
for adapter in adapters:
if 'type' in adapters[adapter] and adapters[adapter]['type'] == 'source':
tmp = source_template.render({'name': adapter, 'data': adapters[adapter]})
else:
tmp = eth_template.render({'name': adapter, 'data': adapters[adapter]})
ifcfg = ifcfg + tmp
if adapter == iface:
saved_ifcfg = tmp
_SEPARATE_FILE = False
if 'filename' in settings:
if not settings['filename'].startswith('/'):
filename = '{0}/{1}'.format(_DEB_NETWORK_DIR, settings['filename'])
else:
filename = settings['filename']
_SEPARATE_FILE = True
else:
if 'filename' in adapters[adapter]['data']:
filename = adapters[adapter]['data']
else:
filename = _DEB_NETWORK_FILE
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
if _SEPARATE_FILE:
fout.write(salt.utils.stringutils.to_str(saved_ifcfg))
else:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return saved_ifcfg.split('\n')
def _write_file_ppp_ifaces(iface, data):
'''
Writes a file to disk
'''
try:
template = JINJA.get_template('debian_ppp_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_ppp_eth.jinja')
return ''
adapters = _parse_interfaces()
adapters[iface] = data
ifcfg = ''
tmp = template.render({'data': adapters[iface]})
ifcfg = tmp + ifcfg
filename = _DEB_PPP_DIR + '/' + adapters[iface]['data']['inet']['provider']
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.fopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return filename
def build_bond(iface, **settings):
'''
Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb
'''
deb_major = __grains__['osrelease'][:1]
opts = _parse_settings_bond(settings, iface)
try:
template = JINJA.get_template('conf.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template conf.jinja')
return ''
data = template.render({'name': iface, 'bonding': opts})
if 'test' in settings and settings['test']:
return _read_temp(data)
_write_file(iface, data, _DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
if deb_major == '5':
for line_type in ('alias', 'options'):
cmd = ['sed', '-i', '-e', r'/^{0}\s{1}.*/d'.format(line_type, iface),
'/etc/modprobe.conf']
__salt__['cmd.run'](cmd, python_shell=False)
__salt__['file.append']('/etc/modprobe.conf', path)
# Load kernel module
__salt__['kmod.load']('bonding')
# install ifenslave-2.6
__salt__['pkg.install']('ifenslave-2.6')
return _read_file(path)
def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'vlan':
settings['vlan'] = 'yes'
__salt__['pkg.install']('vlan')
elif iface_type == 'pppoe':
settings['pppoe'] = 'yes'
if not __salt__['pkg.version']('ppp'):
inst = __salt__['pkg.install']('ppp')
elif iface_type == 'bond':
if 'slaves' not in settings:
msg = 'slaves is a required setting for bond interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'bridge':
if 'ports' not in settings:
msg = (
'ports is a required setting for bridge interfaces on Debian '
'or Ubuntu based systems'
)
log.error(msg)
raise AttributeError(msg)
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'pppoe']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
if iface_type in ['source']:
opts = _parse_settings_source(settings, iface_type, enabled, iface)
if 'test' in settings and settings['test']:
return _read_temp_ifaces(iface, opts[iface])
ifcfg = _write_file_ifaces(iface, opts[iface], **settings)
if iface_type == 'pppoe':
_write_file_ppp_ifaces(iface, opts[iface])
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg]
def build_routes(iface, **settings):
'''
Add route scripts for a network interface using up commands.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
'''
opts = _parse_routes(iface, settings)
try:
template = JINJA.get_template('route_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template route_eth.jinja')
return ''
add_routecfg = template.render(route_type='add',
routes=opts['routes'],
iface=iface)
del_routecfg = template.render(route_type='del',
routes=opts['routes'],
iface=iface)
if 'test' in settings and settings['test']:
return _read_temp(add_routecfg + del_routecfg)
filename = _write_file_routes(iface,
add_routecfg,
_DEB_NETWORK_UP_DIR,
'route-{0}')
results = _read_file(filename)
filename = _write_file_routes(iface,
del_routecfg,
_DEB_NETWORK_DOWN_DIR,
'route-{0}')
results += _read_file(filename)
return results
def down(iface, iface_type):
'''
Shutdown a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.down eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought down.
if iface_type not in ['slave', 'source']:
return __salt__['cmd.run'](['ifdown', iface])
return None
def get_bond(iface):
'''
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
'''
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
return _read_file(path)
def get_interface(iface):
'''
Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
adapters = _parse_interfaces()
if iface in adapters:
try:
if iface == 'source':
template = JINJA.get_template('debian_source.jinja')
else:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': adapters[iface]})
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg.split('\n')]
else:
return []
def up(iface, iface_type): # pylint: disable=C0103
'''
Start up a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.up eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought up.
if iface_type not in ('slave', 'source'):
return __salt__['cmd.run'](['ifup', iface])
return None
def get_network_settings():
'''
Return the contents of the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_network_settings
'''
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
settings = {}
if __salt__['service.available']('networking'):
if __salt__['service.status']('networking'):
settings['networking'] = "yes"
else:
settings['networking'] = "no"
else:
settings['networking'] = "no"
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
settings['hostname'] = hostname
settings['domainname'] = domainname
settings['searchdomain'] = searchdomain
else:
settings = _parse_current_network_settings()
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(settings)
return _read_temp(network)
def get_routes(iface):
'''
Return the routes for the interface
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0
'''
filename = os.path.join(_DEB_NETWORK_UP_DIR, 'route-{0}'.format(iface))
results = _read_file(filename)
filename = os.path.join(_DEB_NETWORK_DOWN_DIR, 'route-{0}'.format(iface))
results += _read_file(filename)
return results
def apply_network_settings(**settings):
'''
Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings
'''
if 'require_reboot' not in settings:
settings['require_reboot'] = False
if 'apply_hostname' not in settings:
settings['apply_hostname'] = False
hostname_res = True
if settings['apply_hostname'] in _CONFIG_TRUE:
if 'hostname' in settings:
hostname_res = __salt__['network.mod_hostname'](settings['hostname'])
else:
log.warning(
'The network state sls is trying to apply hostname '
'changes but no hostname is defined.'
)
hostname_res = False
res = True
if settings['require_reboot'] in _CONFIG_TRUE:
log.warning(
'The network state sls is requiring a reboot of the system to '
'properly apply network configuration.'
)
res = True
else:
stop = __salt__['service.stop']('networking')
time.sleep(2)
res = stop and __salt__['service.start']('networking')
return hostname_res and res
def build_network_settings(**settings):
'''
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
'''
changes = []
# Read current configuration and store default values
current_network_settings = _parse_current_network_settings()
# Build settings
opts = _parse_network_settings(settings, current_network_settings)
# Ubuntu has moved away from /etc/default/networking
# beginning with the 12.04 release so we disable or enable
# the networking related services on boot
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
if opts['networking'] == 'yes':
service_cmd = 'service.enable'
else:
service_cmd = 'service.disable'
if __salt__['service.available']('NetworkManager'):
__salt__[service_cmd]('NetworkManager')
if __salt__['service.available']('networking'):
__salt__[service_cmd]('networking')
else:
try:
template = JINJA.get_template('network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template network.jinja')
return ''
network = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(network)
# Write settings
_write_file_network(network, _DEB_NETWORKING_FILE, True)
# Get hostname and domain from opts
sline = opts['hostname'].split('.', 1)
opts['hostname'] = sline[0]
current_domainname = current_network_settings['domainname']
current_searchdomain = current_network_settings['searchdomain']
new_domain = False
if len(sline) > 1:
new_domainname = sline[1]
if new_domainname != current_domainname:
domainname = new_domainname
opts['domainname'] = new_domainname
new_domain = True
else:
domainname = current_domainname
opts['domainname'] = domainname
else:
domainname = current_domainname
opts['domainname'] = domainname
new_search = False
if 'search' in opts:
new_searchdomain = opts['search']
if new_searchdomain != current_searchdomain:
searchdomain = new_searchdomain
opts['searchdomain'] = new_searchdomain
new_search = True
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
# If the domain changes, then we should write the resolv.conf file.
if new_domain or new_search:
# Look for existing domain line and update if necessary
resolve = _parse_resolve()
domain_prog = re.compile(r'domain\s+')
search_prog = re.compile(r'search\s+')
new_contents = []
for item in _read_file(_DEB_RESOLV_FILE):
if domain_prog.match(item):
item = 'domain {0}'.format(domainname)
elif search_prog.match(item):
item = 'search {0}'.format(searchdomain)
new_contents.append(item)
# A domain line didn't exist so we'll add one in
# with the new domainname
if 'domain' not in resolve:
new_contents.insert(0, 'domain {0}' . format(domainname))
# A search line didn't exist so we'll add one in
# with the new search domain
if 'search' not in resolve:
new_contents.insert('domain' in resolve, 'search {0}'.format(searchdomain))
new_resolv = '\n'.join(new_contents)
# Write /etc/resolv.conf
if not ('test' in settings and settings['test']):
_write_file_network(new_resolv, _DEB_RESOLV_FILE)
# used for returning the results back
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(opts)
changes.extend(_read_temp(network))
return changes
|
saltstack/salt
|
salt/modules/debian_ip.py
|
__int
|
python
|
def __int(value):
'''validate an integer'''
valid, _value = False, value
try:
_value = int(value)
valid = True
except ValueError:
pass
return (valid, _value, 'integer')
|
validate an integer
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_ip.py#L315-L323
| null |
# -*- coding: utf-8 -*-
'''
The networking module for Debian-based distros
References:
* http://www.debian.org/doc/manuals/debian-reference/ch05.en.html
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import functools
import logging
import os.path
import os
import re
import time
# Import third party libs
import jinja2
import jinja2.exceptions
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error,no-name-in-module
# Import salt libs
import salt.utils.dns
import salt.utils.files
import salt.utils.odict
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.validate.net
# Set up logging
log = logging.getLogger(__name__)
# Set up template environment
JINJA = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'debian_ip')
)
)
# Define the module's virtual name
__virtualname__ = 'ip'
def __virtual__():
'''
Confine this module to Debian-based distros
'''
if __grains__['os_family'] == 'Debian':
return __virtualname__
return (False, 'The debian_ip module could not be loaded: '
'unsupported OS family')
_ETHTOOL_CONFIG_OPTS = {
'speed': 'link-speed',
'duplex': 'link-duplex',
'autoneg': 'ethernet-autoneg',
'ethernet-port': 'ethernet-port',
'wol': 'ethernet-wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'rx': 'offload-rx',
'tx': 'offload-tx',
'sg': 'offload-sg',
'tso': 'offload-tso',
'ufo': 'offload-ufo',
'gso': 'offload-gso',
'gro': 'offload-gro',
'lro': 'offload-lro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_REV_ETHTOOL_CONFIG_OPTS = {
'link-speed': 'speed',
'link-duplex': 'duplex',
'ethernet-autoneg': 'autoneg',
'ethernet-port': 'ethernet-port',
'ethernet-wol': 'wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'offload-rx': 'rx',
'offload-tx': 'tx',
'offload-sg': 'sg',
'offload-tso': 'tso',
'offload-ufo': 'ufo',
'offload-gso': 'gso',
'offload-lro': 'lro',
'offload-gro': 'gro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_DEB_CONFIG_PPPOE_OPTS = {
'user': 'user',
'password': 'password',
'provider': 'provider',
'pppoe_iface': 'pppoe_iface',
'noipdefault': 'noipdefault',
'usepeerdns': 'usepeerdns',
'defaultroute': 'defaultroute',
'holdoff': 'holdoff',
'maxfail': 'maxfail',
'hide-password': 'hide-password',
'lcp-echo-interval': 'lcp-echo-interval',
'lcp-echo-failure': 'lcp-echo-failure',
'connect': 'connect',
'noauth': 'noauth',
'persist': 'persist',
'mtu': 'mtu',
'noaccomp': 'noaccomp',
'linkname': 'linkname',
}
_DEB_ROUTES_FILE = '/etc/network/routes'
_DEB_NETWORK_FILE = '/etc/network/interfaces'
_DEB_NETWORK_DIR = '/etc/network/interfaces.d/'
_DEB_NETWORK_UP_DIR = '/etc/network/if-up.d/'
_DEB_NETWORK_DOWN_DIR = '/etc/network/if-down.d/'
_DEB_NETWORK_CONF_FILES = '/etc/modprobe.d/'
_DEB_NETWORKING_FILE = '/etc/default/networking'
_DEB_HOSTNAME_FILE = '/etc/hostname'
_DEB_RESOLV_FILE = '/etc/resolv.conf'
_DEB_PPP_DIR = '/etc/ppp/peers/'
_CONFIG_TRUE = ['yes', 'on', 'true', '1', True]
_CONFIG_FALSE = ['no', 'off', 'false', '0', False]
_IFACE_TYPES = [
'eth', 'bond', 'alias', 'clone',
'ipsec', 'dialup', 'bridge', 'slave',
'vlan', 'pppoe', 'source',
]
def _error_msg_iface(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, '|'.join(str(e) for e in expected))
def _error_msg_routes(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, expected)
def _log_default_iface(iface, opt, value):
log.info(
'Using default option -- Interface: %s Option: %s Value: %s',
iface, opt, value
)
def _error_msg_network(option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]'
return msg.format(option, '|'.join(str(e) for e in expected))
def _log_default_network(opt, value):
log.info('Using existing setting -- Setting: %s Value: %s', opt, value)
def _raise_error_iface(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_iface(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_network(option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_network(option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_routes(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_routes(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _read_file(path):
'''
Reads and returns the contents of a text file
'''
try:
with salt.utils.files.flopen(path, 'rb') as contents:
return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]
except (OSError, IOError):
return ''
def _parse_resolve():
'''
Parse /etc/resolv.conf
'''
return salt.utils.dns.parse_resolv(_DEB_RESOLV_FILE)
def _parse_domainname():
'''
Parse /etc/resolv.conf and return domainname
'''
return _parse_resolve().get('domain', '')
def _parse_searchdomain():
'''
Parse /etc/resolv.conf and return searchdomain
'''
return _parse_resolve().get('search', '')
def _parse_hostname():
'''
Parse /etc/hostname and return hostname
'''
contents = _read_file(_DEB_HOSTNAME_FILE)
if contents:
return contents[0].split('\n')[0]
else:
return ''
def _parse_current_network_settings():
'''
Parse /etc/default/networking and return current configuration
'''
opts = salt.utils.odict.OrderedDict()
opts['networking'] = ''
if os.path.isfile(_DEB_NETWORKING_FILE):
with salt.utils.files.fopen(_DEB_NETWORKING_FILE) as contents:
for line in contents:
salt.utils.stringutils.to_unicode(line)
if line.startswith('#'):
continue
elif line.startswith('CONFIGURE_INTERFACES'):
opts['networking'] = line.split('=', 1)[1].strip()
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
opts['hostname'] = hostname
opts['domainname'] = domainname
opts['searchdomain'] = searchdomain
return opts
# def __validator_func(value):
# return (valid: True/False, (transformed) value, error message)
def __ipv4_quad(value):
'''validate an IPv4 address'''
return (salt.utils.validate.net.ipv4_addr(value), value,
'dotted IPv4 address')
def __ipv6(value):
'''validate an IPv6 address'''
return (salt.utils.validate.net.ipv6_addr(value), value,
'IPv6 address')
def __mac(value):
'''validate a mac address'''
return (salt.utils.validate.net.mac(value), value,
'MAC address')
def __anything(value):
return (True, value, None)
def __float(value):
'''validate a float'''
valid, _value = False, value
try:
_value = float(value)
valid = True
except ValueError:
pass
return (valid, _value, 'float')
def __ipv4_netmask(value):
'''validate an IPv4 dotted quad or integer CIDR netmask'''
valid, errmsg = False, 'dotted quad or integer CIDR (0->32)'
valid, value, _ = __int(value)
if not (valid and 0 <= value <= 32):
valid = salt.utils.validate.net.netmask(value)
return (valid, value, errmsg)
def __ipv6_netmask(value):
'''validate an IPv6 integer netmask'''
valid, errmsg = False, 'IPv6 netmask (0->128)'
valid, value, _ = __int(value)
valid = (valid and 0 <= value <= 128)
return (valid, value, errmsg)
def __within2(value, within=None, errmsg=None, dtype=None):
'''validate that a value is in ``within`` and optionally a ``dtype``'''
valid, _value = False, value
if dtype:
try:
_value = dtype(value) # TODO: this is a bit loose when dtype is a class
valid = _value in within
except ValueError:
pass
else:
valid = _value in within
if errmsg is None:
if dtype:
typename = getattr(dtype, '__name__',
hasattr(dtype, '__class__')
and getattr(dtype.__class__, 'name', dtype))
errmsg = '{0} within \'{1}\''.format(typename, within)
else:
errmsg = 'within \'{0}\''.format(within)
return (valid, _value, errmsg)
def __within(within=None, errmsg=None, dtype=None):
return functools.partial(__within2, within=within,
errmsg=errmsg, dtype=dtype)
def __space_delimited_list(value):
'''validate that a value contains one or more space-delimited values'''
if isinstance(value, six.string_types):
value = value.strip().split()
if hasattr(value, '__iter__') and value != []:
return (True, value, 'space-delimited string')
else:
return (False, value, '{0} is not a valid space-delimited value.\n'.format(value))
SALT_ATTR_TO_DEBIAN_ATTR_MAP = {
'dns': 'dns-nameservers',
'search': 'dns-search',
'hwaddr': 'hwaddress', # TODO: this limits bootp functionality
'ipaddr': 'address',
'ipaddrs': 'addresses',
}
DEBIAN_ATTR_TO_SALT_ATTR_MAP = dict(
(v, k) for (k, v) in six.iteritems(SALT_ATTR_TO_DEBIAN_ATTR_MAP))
# TODO
DEBIAN_ATTR_TO_SALT_ATTR_MAP['address'] = 'address'
DEBIAN_ATTR_TO_SALT_ATTR_MAP['hwaddress'] = 'hwaddress'
IPV4_VALID_PROTO = ['bootp', 'dhcp', 'static', 'manual', 'loopback', 'ppp']
IPV4_ATTR_MAP = {
'proto': __within(IPV4_VALID_PROTO, dtype=six.text_type),
# ipv4 static & manual
'address': __ipv4_quad,
'addresses': __anything,
'netmask': __ipv4_netmask,
'broadcast': __ipv4_quad,
'metric': __int,
'gateway': __ipv4_quad, # supports a colon-delimited list
'pointopoint': __ipv4_quad,
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'link', 'host'], dtype=six.text_type),
# dhcp
'hostname': __anything,
'leasehours': __int,
'leasetime': __int,
'vendor': __anything,
'client': __anything,
# bootp
'bootfile': __anything,
'server': __ipv4_quad,
'hwaddr': __mac,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'dstaddr': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# bond
'slaves': __anything,
# ppp
'provider': __anything,
'unit': __int,
'options': __anything,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
#
'network': __anything, # i don't know what this is
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
IPV6_VALID_PROTO = ['auto', 'loopback', 'static', 'manual',
'dhcp', 'v4tunnel', '6to4']
IPV6_ATTR_MAP = {
'proto': __within(IPV6_VALID_PROTO),
# ipv6 static & manual
'address': __ipv6,
'addresses': __anything,
'netmask': __ipv6_netmask,
'broadcast': __ipv6,
'gateway': __ipv6, # supports a colon-delimited list
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'site', 'link', 'host'], dtype=six.text_type),
# inet6 auto
'privext': __within([0, 1, 2], dtype=int),
'dhcp': __within([0, 1], dtype=int),
# inet6 static & manual & dhcp
'media': __anything,
'accept_ra': __within([0, 1], dtype=int),
'autoconf': __within([0, 1], dtype=int),
'preferred-lifetime': __int,
'dad-attempts': __int, # 0 to disable
'dad-interval': __float,
# bond
'slaves': __anything,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
WIRELESS_ATTR_MAP = {
'wireless-essid': __anything,
'wireless-mode': __anything, # TODO
'wpa-ap-scan': __within([0, 1, 2], dtype=int), # TODO
'wpa-conf': __anything,
'wpa-driver': __anything,
'wpa-group': __anything,
'wpa-key-mgmt': __anything,
'wpa-pairwise': __anything,
'wpa-psk': __anything,
'wpa-proto': __anything, # partial(__within,
'wpa-roam': __anything,
'wpa-ssid': __anything, # TODO
}
ATTRMAPS = {
'inet': [IPV4_ATTR_MAP, WIRELESS_ATTR_MAP],
'inet6': [IPV6_ATTR_MAP, WIRELESS_ATTR_MAP]
}
def _validate_interface_option(attr, value, addrfam='inet'):
'''lookup the validation function for a [addrfam][attr] and
return the results
:param attr: attribute name
:param value: raw setting value
:param addrfam: address family (inet, inet6,
'''
valid, _value, errmsg = False, value, 'Unknown validator'
attrmaps = ATTRMAPS.get(addrfam, [])
for attrmap in attrmaps:
if attr in attrmap:
validate_func = attrmap[attr]
(valid, _value, errmsg) = validate_func(value)
break
return (valid, _value, errmsg)
def _attrmaps_contain_attr(attr):
return (
attr in WIRELESS_ATTR_MAP or
attr in IPV4_ATTR_MAP or
attr in IPV6_ATTR_MAP)
def _parse_interfaces(interface_files=None):
'''
Parse /etc/network/interfaces and return current configured interfaces
'''
if interface_files is None:
interface_files = []
# Add this later.
if os.path.exists(_DEB_NETWORK_DIR):
interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]
if os.path.isfile(_DEB_NETWORK_FILE):
interface_files.insert(0, _DEB_NETWORK_FILE)
adapters = salt.utils.odict.OrderedDict()
method = -1
for interface_file in interface_files:
with salt.utils.files.fopen(interface_file) as interfaces:
# This ensures iface_dict exists, but does not ensure we're not reading a new interface.
iface_dict = {}
for line in interfaces:
line = salt.utils.stringutils.to_unicode(line)
# Identify the clauses by the first word of each line.
# Go to the next line if the current line is a comment
# or all spaces.
if line.lstrip().startswith('#') or line.isspace():
continue
# Parse the iface clause
if line.startswith('iface'):
sline = line.split()
if len(sline) != 4:
msg = 'Interface file malformed: {0}.'
msg = msg.format(sline)
log.error(msg)
raise AttributeError(msg)
iface_name = sline[1]
addrfam = sline[2]
method = sline[3]
# Create item in dict, if not already there
if iface_name not in adapters:
adapters[iface_name] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters[iface_name]:
adapters[iface_name]['data'] = salt.utils.odict.OrderedDict()
if addrfam not in adapters[iface_name]['data']:
adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict()
iface_dict = adapters[iface_name]['data'][addrfam]
iface_dict['addrfam'] = addrfam
iface_dict['proto'] = method
iface_dict['filename'] = interface_file
# Parse the detail clauses.
elif line[0].isspace():
sline = line.split()
# conf file attr: dns-nameservers
# salt states.network attr: dns
attr, valuestr = line.rstrip().split(None, 1)
if _attrmaps_contain_attr(attr):
if '-' in attr:
attrname = attr.replace('-', '_')
else:
attrname = attr
(valid, value, errmsg) = _validate_interface_option(
attr, valuestr, addrfam)
if attrname == 'address' and 'address' in iface_dict:
if 'addresses' not in iface_dict:
iface_dict['addresses'] = []
iface_dict['addresses'].append(value)
else:
iface_dict[attrname] = value
elif attr in _REV_ETHTOOL_CONFIG_OPTS:
if 'ethtool' not in iface_dict:
iface_dict['ethtool'] = salt.utils.odict.OrderedDict()
iface_dict['ethtool'][attr] = valuestr
elif attr.startswith('bond'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bonding' not in iface_dict:
iface_dict['bonding'] = salt.utils.odict.OrderedDict()
iface_dict['bonding'][opt] = valuestr
elif attr.startswith('bridge'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bridging' not in iface_dict:
iface_dict['bridging'] = salt.utils.odict.OrderedDict()
iface_dict['bridging'][opt] = valuestr
elif attr in ['up', 'pre-up', 'post-up',
'down', 'pre-down', 'post-down']:
cmd = valuestr
cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr))
if cmd_key not in iface_dict:
iface_dict[cmd_key] = []
iface_dict[cmd_key].append(cmd)
elif line.startswith('auto'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['enabled'] = True
elif line.startswith('allow-hotplug'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['hotplug'] = True
elif line.startswith('source'):
if 'source' not in adapters:
adapters['source'] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters['source']:
adapters['source']['data'] = salt.utils.odict.OrderedDict()
adapters['source']['data']['sources'] = []
adapters['source']['data']['sources'].append(line.split()[1])
# Return a sorted list of the keys for bond, bridge and ethtool options to
# ensure a consistent order
for iface_name in adapters:
if iface_name == 'source':
continue
if 'data' not in adapters[iface_name]:
msg = 'Interface file malformed for interface: {0}.'.format(iface_name)
log.error(msg)
adapters.pop(iface_name)
continue
for opt in ['ethtool', 'bonding', 'bridging']:
for inet in ['inet', 'inet6']:
if inet in adapters[iface_name]['data']:
if opt in adapters[iface_name]['data'][inet]:
opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys())
adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys
return adapters
def _parse_ethtool_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
if 'autoneg' in opts:
if opts['autoneg'] in _CONFIG_TRUE:
config.update({'autoneg': 'on'})
elif opts['autoneg'] in _CONFIG_FALSE:
config.update({'autoneg': 'off'})
else:
_raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE)
if 'duplex' in opts:
valid = ['full', 'half']
if opts['duplex'] in valid:
config.update({'duplex': opts['duplex']})
else:
_raise_error_iface(iface, 'duplex', valid)
if 'speed' in opts:
valid = ['10', '100', '1000', '10000']
if six.text_type(opts['speed']) in valid:
config.update({'speed': opts['speed']})
else:
_raise_error_iface(iface, opts['speed'], valid)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'on'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'off'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_ethtool_pppoe_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
for opt in _DEB_CONFIG_PPPOE_OPTS:
if opt in opts:
config[opt] = opts[opt]
if 'provider' in opts and not opts['provider']:
_raise_error_iface(iface, 'provider', _CONFIG_TRUE + _CONFIG_FALSE)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('noipdefault', 'usepeerdns', 'defaultroute', 'hide-password', 'noauth', 'persist', 'noaccomp'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'True'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'False'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_settings_bond(opts, iface):
'''
Filters given options and outputs valid settings for requested
operation. If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond_def = {
# 803.ad aggregation selection logic
# 0 for stable (default)
# 1 for bandwidth
# 2 for count
'ad_select': '0',
# Max number of transmit queues (default = 16)
'tx_queues': '16',
# Link monitoring in milliseconds. Most NICs support this
'miimon': '100',
# ARP interval in milliseconds
'arp_interval': '250',
# Delay before considering link down in milliseconds (miimon * 2)
'downdelay': '200',
# lacp_rate 0: Slow - every 30 seconds
# lacp_rate 1: Fast - every 1 second
'lacp_rate': '0',
# Max bonds for this driver
'max_bonds': '1',
# Specifies the time, in milliseconds, to wait before
# enabling a slave after a link recovery has been
# detected. Only used with miimon.
'updelay': '0',
# Used with miimon.
# On: driver sends mii
# Off: ethtool sends mii
'use_carrier': 'on',
# Default. Don't change unless you know what you are doing.
'xmit_hash_policy': 'layer2',
}
if opts['mode'] in ['balance-rr', '0']:
log.info('Device: %s Bonding Mode: load balancing (round-robin)', iface)
return _parse_settings_bond_0(opts, iface, bond_def)
elif opts['mode'] in ['active-backup', '1']:
log.info('Device: %s Bonding Mode: fault-tolerance (active-backup)', iface)
return _parse_settings_bond_1(opts, iface, bond_def)
elif opts['mode'] in ['balance-xor', '2']:
log.info('Device: %s Bonding Mode: load balancing (xor)', iface)
return _parse_settings_bond_2(opts, iface, bond_def)
elif opts['mode'] in ['broadcast', '3']:
log.info('Device: %s Bonding Mode: fault-tolerance (broadcast)', iface)
return _parse_settings_bond_3(opts, iface, bond_def)
elif opts['mode'] in ['802.3ad', '4']:
log.info('Device: %s Bonding Mode: IEEE 802.3ad Dynamic link '
'aggregation', iface)
return _parse_settings_bond_4(opts, iface, bond_def)
elif opts['mode'] in ['balance-tlb', '5']:
log.info('Device: %s Bonding Mode: transmit load balancing', iface)
return _parse_settings_bond_5(opts, iface, bond_def)
elif opts['mode'] in ['balance-alb', '6']:
log.info('Device: %s Bonding Mode: adaptive load balancing', iface)
return _parse_settings_bond_6(opts, iface, bond_def)
else:
valid = [
'0', '1', '2', '3', '4', '5', '6',
'balance-rr', 'active-backup', 'balance-xor',
'broadcast', '802.3ad', 'balance-tlb', 'balance-alb'
]
_raise_error_iface(iface, 'mode', valid)
def _parse_settings_bond_0(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond0.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '0'}
# ARP targets in n.n.n.n form
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
return bond
def _parse_settings_bond_1(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '1'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
if not (__grains__['os'] == "Ubuntu" and __grains__['osrelease_info'][0] >= 16):
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_2(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond2.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '2'}
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_3(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond3.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '3'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_4(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond4.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '4'}
for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']:
if binding in opts:
if binding == 'lacp_rate':
if opts[binding] == 'fast':
opts.update({binding: '1'})
if opts[binding] == 'slow':
opts.update({binding: '0'})
valid = ['fast', '1', 'slow', '0']
else:
valid = ['integer']
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, valid)
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_5(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond5.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '5'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_settings_bond_6(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond6.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '6'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_bridge_opts(opts, iface):
'''
Filters given options and outputs valid settings for BRIDGING_OPTS
If an option has a value that is not expected, this
function will log the Interface, Setting and what was expected.
'''
config = {}
if 'ports' in opts:
if isinstance(opts['ports'], list):
opts['ports'] = ' '.join(opts['ports'])
config.update({'ports': opts['ports']})
for opt in ['ageing', 'fd', 'gcint', 'hello', 'maxage']:
if opt in opts:
try:
float(opts[opt])
config.update({opt: opts[opt]})
except ValueError:
_raise_error_iface(iface, opt, ['float'])
for opt in ['bridgeprio', 'maxwait']:
if opt in opts:
if isinstance(opts[opt], int):
config.update({opt: opts[opt]})
else:
_raise_error_iface(iface, opt, ['integer'])
if 'hw' in opts:
# match 12 hex digits with either : or - as separators between pairs
if re.match('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$',
opts['hw'].lower()):
config.update({'hw': opts['hw']})
else:
_raise_error_iface(iface, 'hw', ['valid MAC address'])
for opt in ['pathcost', 'portprio']:
if opt in opts:
try:
port, cost_or_prio = opts[opt].split()
int(cost_or_prio)
config.update({opt: '{0} {1}'.format(port, cost_or_prio)})
except ValueError:
_raise_error_iface(iface, opt, ['interface integer'])
if 'stp' in opts:
if opts['stp'] in _CONFIG_TRUE:
config.update({'stp': 'on'})
elif opts['stp'] in _CONFIG_FALSE:
config.update({'stp': 'off'})
else:
_raise_error_iface(iface, 'stp', _CONFIG_TRUE + _CONFIG_FALSE)
if 'waitport' in opts:
if isinstance(opts['waitport'], int):
config.update({'waitport': opts['waitport']})
else:
values = opts['waitport'].split()
waitport_time = values.pop(0)
if waitport_time.isdigit() and values:
config.update({
'waitport': '{0} {1}'.format(
waitport_time, ' '.join(values)
)
})
else:
_raise_error_iface(iface, opt, ['integer [interfaces]'])
return config
def _parse_settings_eth(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['inet'] = salt.utils.odict.OrderedDict()
iface_data['inet6'] = salt.utils.odict.OrderedDict()
if enabled:
adapters[iface]['enabled'] = True
if opts.get('hotplug', False):
adapters[iface]['hotplug'] = True
if opts.get('enable_ipv6', None) and opts.get('iface_type', '') == 'vlan':
iface_data['inet6']['vlan_raw_device'] = (
re.sub(r'\.\d*', '', iface))
for addrfam in ['inet', 'inet6']:
if iface_type not in ['bridge']:
tmp_ethtool = _parse_ethtool_opts(opts, iface)
if tmp_ethtool:
ethtool = {}
for item in tmp_ethtool:
ethtool[_ETHTOOL_CONFIG_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['ethtool'] = ethtool
# return a list of sorted keys to ensure consistent order
iface_data[addrfam]['ethtool_keys'] = sorted(ethtool)
if iface_type == 'bridge':
bridging = _parse_bridge_opts(opts, iface)
if bridging:
iface_data[addrfam]['bridging'] = bridging
iface_data[addrfam]['bridging_keys'] = sorted(bridging)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'bond':
bonding = _parse_settings_bond(opts, iface)
if bonding:
iface_data[addrfam]['bonding'] = bonding
iface_data[addrfam]['bonding']['slaves'] = opts['slaves']
iface_data[addrfam]['bonding_keys'] = sorted(bonding)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'slave':
adapters[iface]['master'] = opts['master']
opts['proto'] = 'manual'
iface_data[addrfam]['master'] = adapters[iface]['master']
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'vlan':
iface_data[addrfam]['vlan_raw_device'] = re.sub(r'\.\d*', '', iface)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'pppoe':
tmp_ethtool = _parse_ethtool_pppoe_opts(opts, iface)
if tmp_ethtool:
for item in tmp_ethtool:
adapters[iface]['data'][addrfam][_DEB_CONFIG_PPPOE_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['addrfam'] = addrfam
opts.pop('mode', None)
for opt, val in opts.items():
inet = None
if opt.startswith('ipv4'):
opt = opt[4:]
inet = 'inet'
iface_data['inet']['addrfam'] = 'inet'
elif opt.startswith('ipv6'):
iface_data['inet6']['addrfam'] = 'inet6'
opt = opt[4:]
inet = 'inet6'
elif opt in ['ipaddr', 'address', 'ipaddresses', 'addresses', 'gateway', 'proto']:
iface_data['inet']['addrfam'] = 'inet'
inet = 'inet'
_opt = SALT_ATTR_TO_DEBIAN_ATTR_MAP.get(opt, opt)
_debopt = _opt.replace('-', '_')
for addrfam in ['inet', 'inet6']:
(valid, value, errmsg) = _validate_interface_option(_opt, val, addrfam=addrfam)
if not valid:
continue
if inet is None and _debopt not in iface_data[addrfam]:
iface_data[addrfam][_debopt] = value
elif inet == addrfam:
iface_data[addrfam][_debopt] = value
for opt in ['up_cmds', 'pre_up_cmds', 'post_up_cmds',
'down_cmds', 'pre_down_cmds', 'post_down_cmds']:
if opt in opts:
iface_data['inet'][opt] = opts[opt]
iface_data['inet6'][opt] = opts[opt]
# Remove incomplete/disabled inet blocks
for (addrfam, opt) in [('inet', 'enable_ipv4'), ('inet6', 'enable_ipv6')]:
if opts.get(opt, None) is False:
iface_data.pop(addrfam)
elif iface_data[addrfam].get('addrfam', '') != addrfam:
iface_data.pop(addrfam)
return adapters
def _parse_settings_source(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['sources'] = [opts['source']]
return adapters
def _parse_network_settings(opts, current):
'''
Filters given options and outputs valid settings for
the global network settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
current = dict((k.lower(), v) for (k, v) in six.iteritems(current))
result = {}
valid = _CONFIG_TRUE + _CONFIG_FALSE
if 'enabled' not in opts:
try:
opts['networking'] = current['networking']
_log_default_network('networking', current['networking'])
except ValueError:
_raise_error_network('networking', valid)
else:
opts['networking'] = opts['enabled']
if opts['networking'] in valid:
if opts['networking'] in _CONFIG_TRUE:
result['networking'] = 'yes'
elif opts['networking'] in _CONFIG_FALSE:
result['networking'] = 'no'
else:
_raise_error_network('networking', valid)
if 'hostname' not in opts:
try:
opts['hostname'] = current['hostname']
_log_default_network('hostname', current['hostname'])
except ValueError:
_raise_error_network('hostname', ['server1.example.com'])
if opts['hostname']:
result['hostname'] = opts['hostname']
else:
_raise_error_network('hostname', ['server1.example.com'])
if 'search' in opts:
result['search'] = opts['search']
return result
def _parse_routes(iface, opts):
'''
Filters given options and outputs valid settings for
the route settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
result = {}
if 'routes' not in opts:
_raise_error_routes(iface, 'routes', 'List of routes')
for opt in opts:
result[opt] = opts[opt]
return result
def _write_file(iface, data, folder, pattern):
'''
Writes a file to disk
'''
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
return filename
def _write_file_routes(iface, data, folder, pattern):
'''
Writes a file to disk
'''
# ifup / ifdown is executing given folder via run-parts.
# according to run-parts man-page, only filenames with this pattern are
# executed: (^[a-zA-Z0-9_-]+$)
# In order to make the routes file work for vlan interfaces
# (default would have been in example /etc/network/if-up.d/route-bond0.12)
# these dots in the iface name need to be replaced by underscores, so it
# can be executed by run-parts
iface = iface.replace('.', '_')
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
__salt__['file.set_mode'](filename, '0755')
return filename
def _write_file_network(data, filename, create=False):
'''
Writes a file to disk
If file does not exist, only create if create
argument is True
'''
if not os.path.exists(filename) and not create:
msg = '{0} cannot be written. {0} does not exist\
and create is set to False'
msg = msg.format(filename)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
def _read_temp(data):
'''
Return what would be written to disk
'''
tout = StringIO()
tout.write(data)
tout.seek(0)
output = tout.readlines()
tout.close()
return output
def _read_temp_ifaces(iface, data):
'''
Return what would be written to disk for interfaces
'''
try:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': data})
# Return as an array so the difflib works
return [item + '\n' for item in ifcfg.split('\n')]
def _write_file_ifaces(iface, data, **settings):
'''
Writes a file to disk
'''
try:
eth_template = JINJA.get_template('debian_eth.jinja')
source_template = JINJA.get_template('debian_source.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
# Read /etc/network/interfaces into a dict
adapters = _parse_interfaces()
# Apply supplied settings over on-disk settings
adapters[iface] = data
ifcfg = ''
for adapter in adapters:
if 'type' in adapters[adapter] and adapters[adapter]['type'] == 'source':
tmp = source_template.render({'name': adapter, 'data': adapters[adapter]})
else:
tmp = eth_template.render({'name': adapter, 'data': adapters[adapter]})
ifcfg = ifcfg + tmp
if adapter == iface:
saved_ifcfg = tmp
_SEPARATE_FILE = False
if 'filename' in settings:
if not settings['filename'].startswith('/'):
filename = '{0}/{1}'.format(_DEB_NETWORK_DIR, settings['filename'])
else:
filename = settings['filename']
_SEPARATE_FILE = True
else:
if 'filename' in adapters[adapter]['data']:
filename = adapters[adapter]['data']
else:
filename = _DEB_NETWORK_FILE
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
if _SEPARATE_FILE:
fout.write(salt.utils.stringutils.to_str(saved_ifcfg))
else:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return saved_ifcfg.split('\n')
def _write_file_ppp_ifaces(iface, data):
'''
Writes a file to disk
'''
try:
template = JINJA.get_template('debian_ppp_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_ppp_eth.jinja')
return ''
adapters = _parse_interfaces()
adapters[iface] = data
ifcfg = ''
tmp = template.render({'data': adapters[iface]})
ifcfg = tmp + ifcfg
filename = _DEB_PPP_DIR + '/' + adapters[iface]['data']['inet']['provider']
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.fopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return filename
def build_bond(iface, **settings):
'''
Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb
'''
deb_major = __grains__['osrelease'][:1]
opts = _parse_settings_bond(settings, iface)
try:
template = JINJA.get_template('conf.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template conf.jinja')
return ''
data = template.render({'name': iface, 'bonding': opts})
if 'test' in settings and settings['test']:
return _read_temp(data)
_write_file(iface, data, _DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
if deb_major == '5':
for line_type in ('alias', 'options'):
cmd = ['sed', '-i', '-e', r'/^{0}\s{1}.*/d'.format(line_type, iface),
'/etc/modprobe.conf']
__salt__['cmd.run'](cmd, python_shell=False)
__salt__['file.append']('/etc/modprobe.conf', path)
# Load kernel module
__salt__['kmod.load']('bonding')
# install ifenslave-2.6
__salt__['pkg.install']('ifenslave-2.6')
return _read_file(path)
def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'vlan':
settings['vlan'] = 'yes'
__salt__['pkg.install']('vlan')
elif iface_type == 'pppoe':
settings['pppoe'] = 'yes'
if not __salt__['pkg.version']('ppp'):
inst = __salt__['pkg.install']('ppp')
elif iface_type == 'bond':
if 'slaves' not in settings:
msg = 'slaves is a required setting for bond interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'bridge':
if 'ports' not in settings:
msg = (
'ports is a required setting for bridge interfaces on Debian '
'or Ubuntu based systems'
)
log.error(msg)
raise AttributeError(msg)
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'pppoe']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
if iface_type in ['source']:
opts = _parse_settings_source(settings, iface_type, enabled, iface)
if 'test' in settings and settings['test']:
return _read_temp_ifaces(iface, opts[iface])
ifcfg = _write_file_ifaces(iface, opts[iface], **settings)
if iface_type == 'pppoe':
_write_file_ppp_ifaces(iface, opts[iface])
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg]
def build_routes(iface, **settings):
'''
Add route scripts for a network interface using up commands.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
'''
opts = _parse_routes(iface, settings)
try:
template = JINJA.get_template('route_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template route_eth.jinja')
return ''
add_routecfg = template.render(route_type='add',
routes=opts['routes'],
iface=iface)
del_routecfg = template.render(route_type='del',
routes=opts['routes'],
iface=iface)
if 'test' in settings and settings['test']:
return _read_temp(add_routecfg + del_routecfg)
filename = _write_file_routes(iface,
add_routecfg,
_DEB_NETWORK_UP_DIR,
'route-{0}')
results = _read_file(filename)
filename = _write_file_routes(iface,
del_routecfg,
_DEB_NETWORK_DOWN_DIR,
'route-{0}')
results += _read_file(filename)
return results
def down(iface, iface_type):
'''
Shutdown a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.down eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought down.
if iface_type not in ['slave', 'source']:
return __salt__['cmd.run'](['ifdown', iface])
return None
def get_bond(iface):
'''
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
'''
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
return _read_file(path)
def get_interface(iface):
'''
Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
adapters = _parse_interfaces()
if iface in adapters:
try:
if iface == 'source':
template = JINJA.get_template('debian_source.jinja')
else:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': adapters[iface]})
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg.split('\n')]
else:
return []
def up(iface, iface_type): # pylint: disable=C0103
'''
Start up a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.up eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought up.
if iface_type not in ('slave', 'source'):
return __salt__['cmd.run'](['ifup', iface])
return None
def get_network_settings():
'''
Return the contents of the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_network_settings
'''
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
settings = {}
if __salt__['service.available']('networking'):
if __salt__['service.status']('networking'):
settings['networking'] = "yes"
else:
settings['networking'] = "no"
else:
settings['networking'] = "no"
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
settings['hostname'] = hostname
settings['domainname'] = domainname
settings['searchdomain'] = searchdomain
else:
settings = _parse_current_network_settings()
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(settings)
return _read_temp(network)
def get_routes(iface):
'''
Return the routes for the interface
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0
'''
filename = os.path.join(_DEB_NETWORK_UP_DIR, 'route-{0}'.format(iface))
results = _read_file(filename)
filename = os.path.join(_DEB_NETWORK_DOWN_DIR, 'route-{0}'.format(iface))
results += _read_file(filename)
return results
def apply_network_settings(**settings):
'''
Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings
'''
if 'require_reboot' not in settings:
settings['require_reboot'] = False
if 'apply_hostname' not in settings:
settings['apply_hostname'] = False
hostname_res = True
if settings['apply_hostname'] in _CONFIG_TRUE:
if 'hostname' in settings:
hostname_res = __salt__['network.mod_hostname'](settings['hostname'])
else:
log.warning(
'The network state sls is trying to apply hostname '
'changes but no hostname is defined.'
)
hostname_res = False
res = True
if settings['require_reboot'] in _CONFIG_TRUE:
log.warning(
'The network state sls is requiring a reboot of the system to '
'properly apply network configuration.'
)
res = True
else:
stop = __salt__['service.stop']('networking')
time.sleep(2)
res = stop and __salt__['service.start']('networking')
return hostname_res and res
def build_network_settings(**settings):
'''
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
'''
changes = []
# Read current configuration and store default values
current_network_settings = _parse_current_network_settings()
# Build settings
opts = _parse_network_settings(settings, current_network_settings)
# Ubuntu has moved away from /etc/default/networking
# beginning with the 12.04 release so we disable or enable
# the networking related services on boot
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
if opts['networking'] == 'yes':
service_cmd = 'service.enable'
else:
service_cmd = 'service.disable'
if __salt__['service.available']('NetworkManager'):
__salt__[service_cmd]('NetworkManager')
if __salt__['service.available']('networking'):
__salt__[service_cmd]('networking')
else:
try:
template = JINJA.get_template('network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template network.jinja')
return ''
network = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(network)
# Write settings
_write_file_network(network, _DEB_NETWORKING_FILE, True)
# Get hostname and domain from opts
sline = opts['hostname'].split('.', 1)
opts['hostname'] = sline[0]
current_domainname = current_network_settings['domainname']
current_searchdomain = current_network_settings['searchdomain']
new_domain = False
if len(sline) > 1:
new_domainname = sline[1]
if new_domainname != current_domainname:
domainname = new_domainname
opts['domainname'] = new_domainname
new_domain = True
else:
domainname = current_domainname
opts['domainname'] = domainname
else:
domainname = current_domainname
opts['domainname'] = domainname
new_search = False
if 'search' in opts:
new_searchdomain = opts['search']
if new_searchdomain != current_searchdomain:
searchdomain = new_searchdomain
opts['searchdomain'] = new_searchdomain
new_search = True
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
# If the domain changes, then we should write the resolv.conf file.
if new_domain or new_search:
# Look for existing domain line and update if necessary
resolve = _parse_resolve()
domain_prog = re.compile(r'domain\s+')
search_prog = re.compile(r'search\s+')
new_contents = []
for item in _read_file(_DEB_RESOLV_FILE):
if domain_prog.match(item):
item = 'domain {0}'.format(domainname)
elif search_prog.match(item):
item = 'search {0}'.format(searchdomain)
new_contents.append(item)
# A domain line didn't exist so we'll add one in
# with the new domainname
if 'domain' not in resolve:
new_contents.insert(0, 'domain {0}' . format(domainname))
# A search line didn't exist so we'll add one in
# with the new search domain
if 'search' not in resolve:
new_contents.insert('domain' in resolve, 'search {0}'.format(searchdomain))
new_resolv = '\n'.join(new_contents)
# Write /etc/resolv.conf
if not ('test' in settings and settings['test']):
_write_file_network(new_resolv, _DEB_RESOLV_FILE)
# used for returning the results back
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(opts)
changes.extend(_read_temp(network))
return changes
|
saltstack/salt
|
salt/modules/debian_ip.py
|
__float
|
python
|
def __float(value):
'''validate a float'''
valid, _value = False, value
try:
_value = float(value)
valid = True
except ValueError:
pass
return (valid, _value, 'float')
|
validate a float
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_ip.py#L326-L334
| null |
# -*- coding: utf-8 -*-
'''
The networking module for Debian-based distros
References:
* http://www.debian.org/doc/manuals/debian-reference/ch05.en.html
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import functools
import logging
import os.path
import os
import re
import time
# Import third party libs
import jinja2
import jinja2.exceptions
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error,no-name-in-module
# Import salt libs
import salt.utils.dns
import salt.utils.files
import salt.utils.odict
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.validate.net
# Set up logging
log = logging.getLogger(__name__)
# Set up template environment
JINJA = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'debian_ip')
)
)
# Define the module's virtual name
__virtualname__ = 'ip'
def __virtual__():
'''
Confine this module to Debian-based distros
'''
if __grains__['os_family'] == 'Debian':
return __virtualname__
return (False, 'The debian_ip module could not be loaded: '
'unsupported OS family')
_ETHTOOL_CONFIG_OPTS = {
'speed': 'link-speed',
'duplex': 'link-duplex',
'autoneg': 'ethernet-autoneg',
'ethernet-port': 'ethernet-port',
'wol': 'ethernet-wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'rx': 'offload-rx',
'tx': 'offload-tx',
'sg': 'offload-sg',
'tso': 'offload-tso',
'ufo': 'offload-ufo',
'gso': 'offload-gso',
'gro': 'offload-gro',
'lro': 'offload-lro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_REV_ETHTOOL_CONFIG_OPTS = {
'link-speed': 'speed',
'link-duplex': 'duplex',
'ethernet-autoneg': 'autoneg',
'ethernet-port': 'ethernet-port',
'ethernet-wol': 'wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'offload-rx': 'rx',
'offload-tx': 'tx',
'offload-sg': 'sg',
'offload-tso': 'tso',
'offload-ufo': 'ufo',
'offload-gso': 'gso',
'offload-lro': 'lro',
'offload-gro': 'gro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_DEB_CONFIG_PPPOE_OPTS = {
'user': 'user',
'password': 'password',
'provider': 'provider',
'pppoe_iface': 'pppoe_iface',
'noipdefault': 'noipdefault',
'usepeerdns': 'usepeerdns',
'defaultroute': 'defaultroute',
'holdoff': 'holdoff',
'maxfail': 'maxfail',
'hide-password': 'hide-password',
'lcp-echo-interval': 'lcp-echo-interval',
'lcp-echo-failure': 'lcp-echo-failure',
'connect': 'connect',
'noauth': 'noauth',
'persist': 'persist',
'mtu': 'mtu',
'noaccomp': 'noaccomp',
'linkname': 'linkname',
}
_DEB_ROUTES_FILE = '/etc/network/routes'
_DEB_NETWORK_FILE = '/etc/network/interfaces'
_DEB_NETWORK_DIR = '/etc/network/interfaces.d/'
_DEB_NETWORK_UP_DIR = '/etc/network/if-up.d/'
_DEB_NETWORK_DOWN_DIR = '/etc/network/if-down.d/'
_DEB_NETWORK_CONF_FILES = '/etc/modprobe.d/'
_DEB_NETWORKING_FILE = '/etc/default/networking'
_DEB_HOSTNAME_FILE = '/etc/hostname'
_DEB_RESOLV_FILE = '/etc/resolv.conf'
_DEB_PPP_DIR = '/etc/ppp/peers/'
_CONFIG_TRUE = ['yes', 'on', 'true', '1', True]
_CONFIG_FALSE = ['no', 'off', 'false', '0', False]
_IFACE_TYPES = [
'eth', 'bond', 'alias', 'clone',
'ipsec', 'dialup', 'bridge', 'slave',
'vlan', 'pppoe', 'source',
]
def _error_msg_iface(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, '|'.join(str(e) for e in expected))
def _error_msg_routes(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, expected)
def _log_default_iface(iface, opt, value):
log.info(
'Using default option -- Interface: %s Option: %s Value: %s',
iface, opt, value
)
def _error_msg_network(option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]'
return msg.format(option, '|'.join(str(e) for e in expected))
def _log_default_network(opt, value):
log.info('Using existing setting -- Setting: %s Value: %s', opt, value)
def _raise_error_iface(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_iface(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_network(option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_network(option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_routes(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_routes(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _read_file(path):
'''
Reads and returns the contents of a text file
'''
try:
with salt.utils.files.flopen(path, 'rb') as contents:
return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]
except (OSError, IOError):
return ''
def _parse_resolve():
'''
Parse /etc/resolv.conf
'''
return salt.utils.dns.parse_resolv(_DEB_RESOLV_FILE)
def _parse_domainname():
'''
Parse /etc/resolv.conf and return domainname
'''
return _parse_resolve().get('domain', '')
def _parse_searchdomain():
'''
Parse /etc/resolv.conf and return searchdomain
'''
return _parse_resolve().get('search', '')
def _parse_hostname():
'''
Parse /etc/hostname and return hostname
'''
contents = _read_file(_DEB_HOSTNAME_FILE)
if contents:
return contents[0].split('\n')[0]
else:
return ''
def _parse_current_network_settings():
'''
Parse /etc/default/networking and return current configuration
'''
opts = salt.utils.odict.OrderedDict()
opts['networking'] = ''
if os.path.isfile(_DEB_NETWORKING_FILE):
with salt.utils.files.fopen(_DEB_NETWORKING_FILE) as contents:
for line in contents:
salt.utils.stringutils.to_unicode(line)
if line.startswith('#'):
continue
elif line.startswith('CONFIGURE_INTERFACES'):
opts['networking'] = line.split('=', 1)[1].strip()
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
opts['hostname'] = hostname
opts['domainname'] = domainname
opts['searchdomain'] = searchdomain
return opts
# def __validator_func(value):
# return (valid: True/False, (transformed) value, error message)
def __ipv4_quad(value):
'''validate an IPv4 address'''
return (salt.utils.validate.net.ipv4_addr(value), value,
'dotted IPv4 address')
def __ipv6(value):
'''validate an IPv6 address'''
return (salt.utils.validate.net.ipv6_addr(value), value,
'IPv6 address')
def __mac(value):
'''validate a mac address'''
return (salt.utils.validate.net.mac(value), value,
'MAC address')
def __anything(value):
return (True, value, None)
def __int(value):
'''validate an integer'''
valid, _value = False, value
try:
_value = int(value)
valid = True
except ValueError:
pass
return (valid, _value, 'integer')
def __ipv4_netmask(value):
'''validate an IPv4 dotted quad or integer CIDR netmask'''
valid, errmsg = False, 'dotted quad or integer CIDR (0->32)'
valid, value, _ = __int(value)
if not (valid and 0 <= value <= 32):
valid = salt.utils.validate.net.netmask(value)
return (valid, value, errmsg)
def __ipv6_netmask(value):
'''validate an IPv6 integer netmask'''
valid, errmsg = False, 'IPv6 netmask (0->128)'
valid, value, _ = __int(value)
valid = (valid and 0 <= value <= 128)
return (valid, value, errmsg)
def __within2(value, within=None, errmsg=None, dtype=None):
'''validate that a value is in ``within`` and optionally a ``dtype``'''
valid, _value = False, value
if dtype:
try:
_value = dtype(value) # TODO: this is a bit loose when dtype is a class
valid = _value in within
except ValueError:
pass
else:
valid = _value in within
if errmsg is None:
if dtype:
typename = getattr(dtype, '__name__',
hasattr(dtype, '__class__')
and getattr(dtype.__class__, 'name', dtype))
errmsg = '{0} within \'{1}\''.format(typename, within)
else:
errmsg = 'within \'{0}\''.format(within)
return (valid, _value, errmsg)
def __within(within=None, errmsg=None, dtype=None):
return functools.partial(__within2, within=within,
errmsg=errmsg, dtype=dtype)
def __space_delimited_list(value):
'''validate that a value contains one or more space-delimited values'''
if isinstance(value, six.string_types):
value = value.strip().split()
if hasattr(value, '__iter__') and value != []:
return (True, value, 'space-delimited string')
else:
return (False, value, '{0} is not a valid space-delimited value.\n'.format(value))
SALT_ATTR_TO_DEBIAN_ATTR_MAP = {
'dns': 'dns-nameservers',
'search': 'dns-search',
'hwaddr': 'hwaddress', # TODO: this limits bootp functionality
'ipaddr': 'address',
'ipaddrs': 'addresses',
}
DEBIAN_ATTR_TO_SALT_ATTR_MAP = dict(
(v, k) for (k, v) in six.iteritems(SALT_ATTR_TO_DEBIAN_ATTR_MAP))
# TODO
DEBIAN_ATTR_TO_SALT_ATTR_MAP['address'] = 'address'
DEBIAN_ATTR_TO_SALT_ATTR_MAP['hwaddress'] = 'hwaddress'
IPV4_VALID_PROTO = ['bootp', 'dhcp', 'static', 'manual', 'loopback', 'ppp']
IPV4_ATTR_MAP = {
'proto': __within(IPV4_VALID_PROTO, dtype=six.text_type),
# ipv4 static & manual
'address': __ipv4_quad,
'addresses': __anything,
'netmask': __ipv4_netmask,
'broadcast': __ipv4_quad,
'metric': __int,
'gateway': __ipv4_quad, # supports a colon-delimited list
'pointopoint': __ipv4_quad,
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'link', 'host'], dtype=six.text_type),
# dhcp
'hostname': __anything,
'leasehours': __int,
'leasetime': __int,
'vendor': __anything,
'client': __anything,
# bootp
'bootfile': __anything,
'server': __ipv4_quad,
'hwaddr': __mac,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'dstaddr': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# bond
'slaves': __anything,
# ppp
'provider': __anything,
'unit': __int,
'options': __anything,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
#
'network': __anything, # i don't know what this is
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
IPV6_VALID_PROTO = ['auto', 'loopback', 'static', 'manual',
'dhcp', 'v4tunnel', '6to4']
IPV6_ATTR_MAP = {
'proto': __within(IPV6_VALID_PROTO),
# ipv6 static & manual
'address': __ipv6,
'addresses': __anything,
'netmask': __ipv6_netmask,
'broadcast': __ipv6,
'gateway': __ipv6, # supports a colon-delimited list
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'site', 'link', 'host'], dtype=six.text_type),
# inet6 auto
'privext': __within([0, 1, 2], dtype=int),
'dhcp': __within([0, 1], dtype=int),
# inet6 static & manual & dhcp
'media': __anything,
'accept_ra': __within([0, 1], dtype=int),
'autoconf': __within([0, 1], dtype=int),
'preferred-lifetime': __int,
'dad-attempts': __int, # 0 to disable
'dad-interval': __float,
# bond
'slaves': __anything,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
WIRELESS_ATTR_MAP = {
'wireless-essid': __anything,
'wireless-mode': __anything, # TODO
'wpa-ap-scan': __within([0, 1, 2], dtype=int), # TODO
'wpa-conf': __anything,
'wpa-driver': __anything,
'wpa-group': __anything,
'wpa-key-mgmt': __anything,
'wpa-pairwise': __anything,
'wpa-psk': __anything,
'wpa-proto': __anything, # partial(__within,
'wpa-roam': __anything,
'wpa-ssid': __anything, # TODO
}
ATTRMAPS = {
'inet': [IPV4_ATTR_MAP, WIRELESS_ATTR_MAP],
'inet6': [IPV6_ATTR_MAP, WIRELESS_ATTR_MAP]
}
def _validate_interface_option(attr, value, addrfam='inet'):
'''lookup the validation function for a [addrfam][attr] and
return the results
:param attr: attribute name
:param value: raw setting value
:param addrfam: address family (inet, inet6,
'''
valid, _value, errmsg = False, value, 'Unknown validator'
attrmaps = ATTRMAPS.get(addrfam, [])
for attrmap in attrmaps:
if attr in attrmap:
validate_func = attrmap[attr]
(valid, _value, errmsg) = validate_func(value)
break
return (valid, _value, errmsg)
def _attrmaps_contain_attr(attr):
return (
attr in WIRELESS_ATTR_MAP or
attr in IPV4_ATTR_MAP or
attr in IPV6_ATTR_MAP)
def _parse_interfaces(interface_files=None):
'''
Parse /etc/network/interfaces and return current configured interfaces
'''
if interface_files is None:
interface_files = []
# Add this later.
if os.path.exists(_DEB_NETWORK_DIR):
interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]
if os.path.isfile(_DEB_NETWORK_FILE):
interface_files.insert(0, _DEB_NETWORK_FILE)
adapters = salt.utils.odict.OrderedDict()
method = -1
for interface_file in interface_files:
with salt.utils.files.fopen(interface_file) as interfaces:
# This ensures iface_dict exists, but does not ensure we're not reading a new interface.
iface_dict = {}
for line in interfaces:
line = salt.utils.stringutils.to_unicode(line)
# Identify the clauses by the first word of each line.
# Go to the next line if the current line is a comment
# or all spaces.
if line.lstrip().startswith('#') or line.isspace():
continue
# Parse the iface clause
if line.startswith('iface'):
sline = line.split()
if len(sline) != 4:
msg = 'Interface file malformed: {0}.'
msg = msg.format(sline)
log.error(msg)
raise AttributeError(msg)
iface_name = sline[1]
addrfam = sline[2]
method = sline[3]
# Create item in dict, if not already there
if iface_name not in adapters:
adapters[iface_name] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters[iface_name]:
adapters[iface_name]['data'] = salt.utils.odict.OrderedDict()
if addrfam not in adapters[iface_name]['data']:
adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict()
iface_dict = adapters[iface_name]['data'][addrfam]
iface_dict['addrfam'] = addrfam
iface_dict['proto'] = method
iface_dict['filename'] = interface_file
# Parse the detail clauses.
elif line[0].isspace():
sline = line.split()
# conf file attr: dns-nameservers
# salt states.network attr: dns
attr, valuestr = line.rstrip().split(None, 1)
if _attrmaps_contain_attr(attr):
if '-' in attr:
attrname = attr.replace('-', '_')
else:
attrname = attr
(valid, value, errmsg) = _validate_interface_option(
attr, valuestr, addrfam)
if attrname == 'address' and 'address' in iface_dict:
if 'addresses' not in iface_dict:
iface_dict['addresses'] = []
iface_dict['addresses'].append(value)
else:
iface_dict[attrname] = value
elif attr in _REV_ETHTOOL_CONFIG_OPTS:
if 'ethtool' not in iface_dict:
iface_dict['ethtool'] = salt.utils.odict.OrderedDict()
iface_dict['ethtool'][attr] = valuestr
elif attr.startswith('bond'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bonding' not in iface_dict:
iface_dict['bonding'] = salt.utils.odict.OrderedDict()
iface_dict['bonding'][opt] = valuestr
elif attr.startswith('bridge'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bridging' not in iface_dict:
iface_dict['bridging'] = salt.utils.odict.OrderedDict()
iface_dict['bridging'][opt] = valuestr
elif attr in ['up', 'pre-up', 'post-up',
'down', 'pre-down', 'post-down']:
cmd = valuestr
cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr))
if cmd_key not in iface_dict:
iface_dict[cmd_key] = []
iface_dict[cmd_key].append(cmd)
elif line.startswith('auto'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['enabled'] = True
elif line.startswith('allow-hotplug'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['hotplug'] = True
elif line.startswith('source'):
if 'source' not in adapters:
adapters['source'] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters['source']:
adapters['source']['data'] = salt.utils.odict.OrderedDict()
adapters['source']['data']['sources'] = []
adapters['source']['data']['sources'].append(line.split()[1])
# Return a sorted list of the keys for bond, bridge and ethtool options to
# ensure a consistent order
for iface_name in adapters:
if iface_name == 'source':
continue
if 'data' not in adapters[iface_name]:
msg = 'Interface file malformed for interface: {0}.'.format(iface_name)
log.error(msg)
adapters.pop(iface_name)
continue
for opt in ['ethtool', 'bonding', 'bridging']:
for inet in ['inet', 'inet6']:
if inet in adapters[iface_name]['data']:
if opt in adapters[iface_name]['data'][inet]:
opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys())
adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys
return adapters
def _parse_ethtool_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
if 'autoneg' in opts:
if opts['autoneg'] in _CONFIG_TRUE:
config.update({'autoneg': 'on'})
elif opts['autoneg'] in _CONFIG_FALSE:
config.update({'autoneg': 'off'})
else:
_raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE)
if 'duplex' in opts:
valid = ['full', 'half']
if opts['duplex'] in valid:
config.update({'duplex': opts['duplex']})
else:
_raise_error_iface(iface, 'duplex', valid)
if 'speed' in opts:
valid = ['10', '100', '1000', '10000']
if six.text_type(opts['speed']) in valid:
config.update({'speed': opts['speed']})
else:
_raise_error_iface(iface, opts['speed'], valid)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'on'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'off'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_ethtool_pppoe_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
for opt in _DEB_CONFIG_PPPOE_OPTS:
if opt in opts:
config[opt] = opts[opt]
if 'provider' in opts and not opts['provider']:
_raise_error_iface(iface, 'provider', _CONFIG_TRUE + _CONFIG_FALSE)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('noipdefault', 'usepeerdns', 'defaultroute', 'hide-password', 'noauth', 'persist', 'noaccomp'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'True'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'False'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_settings_bond(opts, iface):
'''
Filters given options and outputs valid settings for requested
operation. If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond_def = {
# 803.ad aggregation selection logic
# 0 for stable (default)
# 1 for bandwidth
# 2 for count
'ad_select': '0',
# Max number of transmit queues (default = 16)
'tx_queues': '16',
# Link monitoring in milliseconds. Most NICs support this
'miimon': '100',
# ARP interval in milliseconds
'arp_interval': '250',
# Delay before considering link down in milliseconds (miimon * 2)
'downdelay': '200',
# lacp_rate 0: Slow - every 30 seconds
# lacp_rate 1: Fast - every 1 second
'lacp_rate': '0',
# Max bonds for this driver
'max_bonds': '1',
# Specifies the time, in milliseconds, to wait before
# enabling a slave after a link recovery has been
# detected. Only used with miimon.
'updelay': '0',
# Used with miimon.
# On: driver sends mii
# Off: ethtool sends mii
'use_carrier': 'on',
# Default. Don't change unless you know what you are doing.
'xmit_hash_policy': 'layer2',
}
if opts['mode'] in ['balance-rr', '0']:
log.info('Device: %s Bonding Mode: load balancing (round-robin)', iface)
return _parse_settings_bond_0(opts, iface, bond_def)
elif opts['mode'] in ['active-backup', '1']:
log.info('Device: %s Bonding Mode: fault-tolerance (active-backup)', iface)
return _parse_settings_bond_1(opts, iface, bond_def)
elif opts['mode'] in ['balance-xor', '2']:
log.info('Device: %s Bonding Mode: load balancing (xor)', iface)
return _parse_settings_bond_2(opts, iface, bond_def)
elif opts['mode'] in ['broadcast', '3']:
log.info('Device: %s Bonding Mode: fault-tolerance (broadcast)', iface)
return _parse_settings_bond_3(opts, iface, bond_def)
elif opts['mode'] in ['802.3ad', '4']:
log.info('Device: %s Bonding Mode: IEEE 802.3ad Dynamic link '
'aggregation', iface)
return _parse_settings_bond_4(opts, iface, bond_def)
elif opts['mode'] in ['balance-tlb', '5']:
log.info('Device: %s Bonding Mode: transmit load balancing', iface)
return _parse_settings_bond_5(opts, iface, bond_def)
elif opts['mode'] in ['balance-alb', '6']:
log.info('Device: %s Bonding Mode: adaptive load balancing', iface)
return _parse_settings_bond_6(opts, iface, bond_def)
else:
valid = [
'0', '1', '2', '3', '4', '5', '6',
'balance-rr', 'active-backup', 'balance-xor',
'broadcast', '802.3ad', 'balance-tlb', 'balance-alb'
]
_raise_error_iface(iface, 'mode', valid)
def _parse_settings_bond_0(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond0.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '0'}
# ARP targets in n.n.n.n form
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
return bond
def _parse_settings_bond_1(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '1'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
if not (__grains__['os'] == "Ubuntu" and __grains__['osrelease_info'][0] >= 16):
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_2(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond2.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '2'}
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_3(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond3.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '3'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_4(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond4.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '4'}
for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']:
if binding in opts:
if binding == 'lacp_rate':
if opts[binding] == 'fast':
opts.update({binding: '1'})
if opts[binding] == 'slow':
opts.update({binding: '0'})
valid = ['fast', '1', 'slow', '0']
else:
valid = ['integer']
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, valid)
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_5(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond5.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '5'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_settings_bond_6(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond6.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '6'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_bridge_opts(opts, iface):
'''
Filters given options and outputs valid settings for BRIDGING_OPTS
If an option has a value that is not expected, this
function will log the Interface, Setting and what was expected.
'''
config = {}
if 'ports' in opts:
if isinstance(opts['ports'], list):
opts['ports'] = ' '.join(opts['ports'])
config.update({'ports': opts['ports']})
for opt in ['ageing', 'fd', 'gcint', 'hello', 'maxage']:
if opt in opts:
try:
float(opts[opt])
config.update({opt: opts[opt]})
except ValueError:
_raise_error_iface(iface, opt, ['float'])
for opt in ['bridgeprio', 'maxwait']:
if opt in opts:
if isinstance(opts[opt], int):
config.update({opt: opts[opt]})
else:
_raise_error_iface(iface, opt, ['integer'])
if 'hw' in opts:
# match 12 hex digits with either : or - as separators between pairs
if re.match('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$',
opts['hw'].lower()):
config.update({'hw': opts['hw']})
else:
_raise_error_iface(iface, 'hw', ['valid MAC address'])
for opt in ['pathcost', 'portprio']:
if opt in opts:
try:
port, cost_or_prio = opts[opt].split()
int(cost_or_prio)
config.update({opt: '{0} {1}'.format(port, cost_or_prio)})
except ValueError:
_raise_error_iface(iface, opt, ['interface integer'])
if 'stp' in opts:
if opts['stp'] in _CONFIG_TRUE:
config.update({'stp': 'on'})
elif opts['stp'] in _CONFIG_FALSE:
config.update({'stp': 'off'})
else:
_raise_error_iface(iface, 'stp', _CONFIG_TRUE + _CONFIG_FALSE)
if 'waitport' in opts:
if isinstance(opts['waitport'], int):
config.update({'waitport': opts['waitport']})
else:
values = opts['waitport'].split()
waitport_time = values.pop(0)
if waitport_time.isdigit() and values:
config.update({
'waitport': '{0} {1}'.format(
waitport_time, ' '.join(values)
)
})
else:
_raise_error_iface(iface, opt, ['integer [interfaces]'])
return config
def _parse_settings_eth(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['inet'] = salt.utils.odict.OrderedDict()
iface_data['inet6'] = salt.utils.odict.OrderedDict()
if enabled:
adapters[iface]['enabled'] = True
if opts.get('hotplug', False):
adapters[iface]['hotplug'] = True
if opts.get('enable_ipv6', None) and opts.get('iface_type', '') == 'vlan':
iface_data['inet6']['vlan_raw_device'] = (
re.sub(r'\.\d*', '', iface))
for addrfam in ['inet', 'inet6']:
if iface_type not in ['bridge']:
tmp_ethtool = _parse_ethtool_opts(opts, iface)
if tmp_ethtool:
ethtool = {}
for item in tmp_ethtool:
ethtool[_ETHTOOL_CONFIG_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['ethtool'] = ethtool
# return a list of sorted keys to ensure consistent order
iface_data[addrfam]['ethtool_keys'] = sorted(ethtool)
if iface_type == 'bridge':
bridging = _parse_bridge_opts(opts, iface)
if bridging:
iface_data[addrfam]['bridging'] = bridging
iface_data[addrfam]['bridging_keys'] = sorted(bridging)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'bond':
bonding = _parse_settings_bond(opts, iface)
if bonding:
iface_data[addrfam]['bonding'] = bonding
iface_data[addrfam]['bonding']['slaves'] = opts['slaves']
iface_data[addrfam]['bonding_keys'] = sorted(bonding)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'slave':
adapters[iface]['master'] = opts['master']
opts['proto'] = 'manual'
iface_data[addrfam]['master'] = adapters[iface]['master']
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'vlan':
iface_data[addrfam]['vlan_raw_device'] = re.sub(r'\.\d*', '', iface)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'pppoe':
tmp_ethtool = _parse_ethtool_pppoe_opts(opts, iface)
if tmp_ethtool:
for item in tmp_ethtool:
adapters[iface]['data'][addrfam][_DEB_CONFIG_PPPOE_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['addrfam'] = addrfam
opts.pop('mode', None)
for opt, val in opts.items():
inet = None
if opt.startswith('ipv4'):
opt = opt[4:]
inet = 'inet'
iface_data['inet']['addrfam'] = 'inet'
elif opt.startswith('ipv6'):
iface_data['inet6']['addrfam'] = 'inet6'
opt = opt[4:]
inet = 'inet6'
elif opt in ['ipaddr', 'address', 'ipaddresses', 'addresses', 'gateway', 'proto']:
iface_data['inet']['addrfam'] = 'inet'
inet = 'inet'
_opt = SALT_ATTR_TO_DEBIAN_ATTR_MAP.get(opt, opt)
_debopt = _opt.replace('-', '_')
for addrfam in ['inet', 'inet6']:
(valid, value, errmsg) = _validate_interface_option(_opt, val, addrfam=addrfam)
if not valid:
continue
if inet is None and _debopt not in iface_data[addrfam]:
iface_data[addrfam][_debopt] = value
elif inet == addrfam:
iface_data[addrfam][_debopt] = value
for opt in ['up_cmds', 'pre_up_cmds', 'post_up_cmds',
'down_cmds', 'pre_down_cmds', 'post_down_cmds']:
if opt in opts:
iface_data['inet'][opt] = opts[opt]
iface_data['inet6'][opt] = opts[opt]
# Remove incomplete/disabled inet blocks
for (addrfam, opt) in [('inet', 'enable_ipv4'), ('inet6', 'enable_ipv6')]:
if opts.get(opt, None) is False:
iface_data.pop(addrfam)
elif iface_data[addrfam].get('addrfam', '') != addrfam:
iface_data.pop(addrfam)
return adapters
def _parse_settings_source(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['sources'] = [opts['source']]
return adapters
def _parse_network_settings(opts, current):
'''
Filters given options and outputs valid settings for
the global network settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
current = dict((k.lower(), v) for (k, v) in six.iteritems(current))
result = {}
valid = _CONFIG_TRUE + _CONFIG_FALSE
if 'enabled' not in opts:
try:
opts['networking'] = current['networking']
_log_default_network('networking', current['networking'])
except ValueError:
_raise_error_network('networking', valid)
else:
opts['networking'] = opts['enabled']
if opts['networking'] in valid:
if opts['networking'] in _CONFIG_TRUE:
result['networking'] = 'yes'
elif opts['networking'] in _CONFIG_FALSE:
result['networking'] = 'no'
else:
_raise_error_network('networking', valid)
if 'hostname' not in opts:
try:
opts['hostname'] = current['hostname']
_log_default_network('hostname', current['hostname'])
except ValueError:
_raise_error_network('hostname', ['server1.example.com'])
if opts['hostname']:
result['hostname'] = opts['hostname']
else:
_raise_error_network('hostname', ['server1.example.com'])
if 'search' in opts:
result['search'] = opts['search']
return result
def _parse_routes(iface, opts):
'''
Filters given options and outputs valid settings for
the route settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
result = {}
if 'routes' not in opts:
_raise_error_routes(iface, 'routes', 'List of routes')
for opt in opts:
result[opt] = opts[opt]
return result
def _write_file(iface, data, folder, pattern):
'''
Writes a file to disk
'''
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
return filename
def _write_file_routes(iface, data, folder, pattern):
'''
Writes a file to disk
'''
# ifup / ifdown is executing given folder via run-parts.
# according to run-parts man-page, only filenames with this pattern are
# executed: (^[a-zA-Z0-9_-]+$)
# In order to make the routes file work for vlan interfaces
# (default would have been in example /etc/network/if-up.d/route-bond0.12)
# these dots in the iface name need to be replaced by underscores, so it
# can be executed by run-parts
iface = iface.replace('.', '_')
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
__salt__['file.set_mode'](filename, '0755')
return filename
def _write_file_network(data, filename, create=False):
'''
Writes a file to disk
If file does not exist, only create if create
argument is True
'''
if not os.path.exists(filename) and not create:
msg = '{0} cannot be written. {0} does not exist\
and create is set to False'
msg = msg.format(filename)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
def _read_temp(data):
'''
Return what would be written to disk
'''
tout = StringIO()
tout.write(data)
tout.seek(0)
output = tout.readlines()
tout.close()
return output
def _read_temp_ifaces(iface, data):
'''
Return what would be written to disk for interfaces
'''
try:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': data})
# Return as an array so the difflib works
return [item + '\n' for item in ifcfg.split('\n')]
def _write_file_ifaces(iface, data, **settings):
'''
Writes a file to disk
'''
try:
eth_template = JINJA.get_template('debian_eth.jinja')
source_template = JINJA.get_template('debian_source.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
# Read /etc/network/interfaces into a dict
adapters = _parse_interfaces()
# Apply supplied settings over on-disk settings
adapters[iface] = data
ifcfg = ''
for adapter in adapters:
if 'type' in adapters[adapter] and adapters[adapter]['type'] == 'source':
tmp = source_template.render({'name': adapter, 'data': adapters[adapter]})
else:
tmp = eth_template.render({'name': adapter, 'data': adapters[adapter]})
ifcfg = ifcfg + tmp
if adapter == iface:
saved_ifcfg = tmp
_SEPARATE_FILE = False
if 'filename' in settings:
if not settings['filename'].startswith('/'):
filename = '{0}/{1}'.format(_DEB_NETWORK_DIR, settings['filename'])
else:
filename = settings['filename']
_SEPARATE_FILE = True
else:
if 'filename' in adapters[adapter]['data']:
filename = adapters[adapter]['data']
else:
filename = _DEB_NETWORK_FILE
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
if _SEPARATE_FILE:
fout.write(salt.utils.stringutils.to_str(saved_ifcfg))
else:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return saved_ifcfg.split('\n')
def _write_file_ppp_ifaces(iface, data):
'''
Writes a file to disk
'''
try:
template = JINJA.get_template('debian_ppp_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_ppp_eth.jinja')
return ''
adapters = _parse_interfaces()
adapters[iface] = data
ifcfg = ''
tmp = template.render({'data': adapters[iface]})
ifcfg = tmp + ifcfg
filename = _DEB_PPP_DIR + '/' + adapters[iface]['data']['inet']['provider']
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.fopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return filename
def build_bond(iface, **settings):
'''
Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb
'''
deb_major = __grains__['osrelease'][:1]
opts = _parse_settings_bond(settings, iface)
try:
template = JINJA.get_template('conf.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template conf.jinja')
return ''
data = template.render({'name': iface, 'bonding': opts})
if 'test' in settings and settings['test']:
return _read_temp(data)
_write_file(iface, data, _DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
if deb_major == '5':
for line_type in ('alias', 'options'):
cmd = ['sed', '-i', '-e', r'/^{0}\s{1}.*/d'.format(line_type, iface),
'/etc/modprobe.conf']
__salt__['cmd.run'](cmd, python_shell=False)
__salt__['file.append']('/etc/modprobe.conf', path)
# Load kernel module
__salt__['kmod.load']('bonding')
# install ifenslave-2.6
__salt__['pkg.install']('ifenslave-2.6')
return _read_file(path)
def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'vlan':
settings['vlan'] = 'yes'
__salt__['pkg.install']('vlan')
elif iface_type == 'pppoe':
settings['pppoe'] = 'yes'
if not __salt__['pkg.version']('ppp'):
inst = __salt__['pkg.install']('ppp')
elif iface_type == 'bond':
if 'slaves' not in settings:
msg = 'slaves is a required setting for bond interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'bridge':
if 'ports' not in settings:
msg = (
'ports is a required setting for bridge interfaces on Debian '
'or Ubuntu based systems'
)
log.error(msg)
raise AttributeError(msg)
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'pppoe']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
if iface_type in ['source']:
opts = _parse_settings_source(settings, iface_type, enabled, iface)
if 'test' in settings and settings['test']:
return _read_temp_ifaces(iface, opts[iface])
ifcfg = _write_file_ifaces(iface, opts[iface], **settings)
if iface_type == 'pppoe':
_write_file_ppp_ifaces(iface, opts[iface])
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg]
def build_routes(iface, **settings):
'''
Add route scripts for a network interface using up commands.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
'''
opts = _parse_routes(iface, settings)
try:
template = JINJA.get_template('route_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template route_eth.jinja')
return ''
add_routecfg = template.render(route_type='add',
routes=opts['routes'],
iface=iface)
del_routecfg = template.render(route_type='del',
routes=opts['routes'],
iface=iface)
if 'test' in settings and settings['test']:
return _read_temp(add_routecfg + del_routecfg)
filename = _write_file_routes(iface,
add_routecfg,
_DEB_NETWORK_UP_DIR,
'route-{0}')
results = _read_file(filename)
filename = _write_file_routes(iface,
del_routecfg,
_DEB_NETWORK_DOWN_DIR,
'route-{0}')
results += _read_file(filename)
return results
def down(iface, iface_type):
'''
Shutdown a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.down eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought down.
if iface_type not in ['slave', 'source']:
return __salt__['cmd.run'](['ifdown', iface])
return None
def get_bond(iface):
'''
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
'''
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
return _read_file(path)
def get_interface(iface):
'''
Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
adapters = _parse_interfaces()
if iface in adapters:
try:
if iface == 'source':
template = JINJA.get_template('debian_source.jinja')
else:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': adapters[iface]})
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg.split('\n')]
else:
return []
def up(iface, iface_type): # pylint: disable=C0103
'''
Start up a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.up eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought up.
if iface_type not in ('slave', 'source'):
return __salt__['cmd.run'](['ifup', iface])
return None
def get_network_settings():
'''
Return the contents of the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_network_settings
'''
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
settings = {}
if __salt__['service.available']('networking'):
if __salt__['service.status']('networking'):
settings['networking'] = "yes"
else:
settings['networking'] = "no"
else:
settings['networking'] = "no"
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
settings['hostname'] = hostname
settings['domainname'] = domainname
settings['searchdomain'] = searchdomain
else:
settings = _parse_current_network_settings()
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(settings)
return _read_temp(network)
def get_routes(iface):
'''
Return the routes for the interface
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0
'''
filename = os.path.join(_DEB_NETWORK_UP_DIR, 'route-{0}'.format(iface))
results = _read_file(filename)
filename = os.path.join(_DEB_NETWORK_DOWN_DIR, 'route-{0}'.format(iface))
results += _read_file(filename)
return results
def apply_network_settings(**settings):
'''
Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings
'''
if 'require_reboot' not in settings:
settings['require_reboot'] = False
if 'apply_hostname' not in settings:
settings['apply_hostname'] = False
hostname_res = True
if settings['apply_hostname'] in _CONFIG_TRUE:
if 'hostname' in settings:
hostname_res = __salt__['network.mod_hostname'](settings['hostname'])
else:
log.warning(
'The network state sls is trying to apply hostname '
'changes but no hostname is defined.'
)
hostname_res = False
res = True
if settings['require_reboot'] in _CONFIG_TRUE:
log.warning(
'The network state sls is requiring a reboot of the system to '
'properly apply network configuration.'
)
res = True
else:
stop = __salt__['service.stop']('networking')
time.sleep(2)
res = stop and __salt__['service.start']('networking')
return hostname_res and res
def build_network_settings(**settings):
'''
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
'''
changes = []
# Read current configuration and store default values
current_network_settings = _parse_current_network_settings()
# Build settings
opts = _parse_network_settings(settings, current_network_settings)
# Ubuntu has moved away from /etc/default/networking
# beginning with the 12.04 release so we disable or enable
# the networking related services on boot
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
if opts['networking'] == 'yes':
service_cmd = 'service.enable'
else:
service_cmd = 'service.disable'
if __salt__['service.available']('NetworkManager'):
__salt__[service_cmd]('NetworkManager')
if __salt__['service.available']('networking'):
__salt__[service_cmd]('networking')
else:
try:
template = JINJA.get_template('network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template network.jinja')
return ''
network = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(network)
# Write settings
_write_file_network(network, _DEB_NETWORKING_FILE, True)
# Get hostname and domain from opts
sline = opts['hostname'].split('.', 1)
opts['hostname'] = sline[0]
current_domainname = current_network_settings['domainname']
current_searchdomain = current_network_settings['searchdomain']
new_domain = False
if len(sline) > 1:
new_domainname = sline[1]
if new_domainname != current_domainname:
domainname = new_domainname
opts['domainname'] = new_domainname
new_domain = True
else:
domainname = current_domainname
opts['domainname'] = domainname
else:
domainname = current_domainname
opts['domainname'] = domainname
new_search = False
if 'search' in opts:
new_searchdomain = opts['search']
if new_searchdomain != current_searchdomain:
searchdomain = new_searchdomain
opts['searchdomain'] = new_searchdomain
new_search = True
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
# If the domain changes, then we should write the resolv.conf file.
if new_domain or new_search:
# Look for existing domain line and update if necessary
resolve = _parse_resolve()
domain_prog = re.compile(r'domain\s+')
search_prog = re.compile(r'search\s+')
new_contents = []
for item in _read_file(_DEB_RESOLV_FILE):
if domain_prog.match(item):
item = 'domain {0}'.format(domainname)
elif search_prog.match(item):
item = 'search {0}'.format(searchdomain)
new_contents.append(item)
# A domain line didn't exist so we'll add one in
# with the new domainname
if 'domain' not in resolve:
new_contents.insert(0, 'domain {0}' . format(domainname))
# A search line didn't exist so we'll add one in
# with the new search domain
if 'search' not in resolve:
new_contents.insert('domain' in resolve, 'search {0}'.format(searchdomain))
new_resolv = '\n'.join(new_contents)
# Write /etc/resolv.conf
if not ('test' in settings and settings['test']):
_write_file_network(new_resolv, _DEB_RESOLV_FILE)
# used for returning the results back
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(opts)
changes.extend(_read_temp(network))
return changes
|
saltstack/salt
|
salt/modules/debian_ip.py
|
__ipv4_netmask
|
python
|
def __ipv4_netmask(value):
'''validate an IPv4 dotted quad or integer CIDR netmask'''
valid, errmsg = False, 'dotted quad or integer CIDR (0->32)'
valid, value, _ = __int(value)
if not (valid and 0 <= value <= 32):
valid = salt.utils.validate.net.netmask(value)
return (valid, value, errmsg)
|
validate an IPv4 dotted quad or integer CIDR netmask
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_ip.py#L337-L343
| null |
# -*- coding: utf-8 -*-
'''
The networking module for Debian-based distros
References:
* http://www.debian.org/doc/manuals/debian-reference/ch05.en.html
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import functools
import logging
import os.path
import os
import re
import time
# Import third party libs
import jinja2
import jinja2.exceptions
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error,no-name-in-module
# Import salt libs
import salt.utils.dns
import salt.utils.files
import salt.utils.odict
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.validate.net
# Set up logging
log = logging.getLogger(__name__)
# Set up template environment
JINJA = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'debian_ip')
)
)
# Define the module's virtual name
__virtualname__ = 'ip'
def __virtual__():
'''
Confine this module to Debian-based distros
'''
if __grains__['os_family'] == 'Debian':
return __virtualname__
return (False, 'The debian_ip module could not be loaded: '
'unsupported OS family')
_ETHTOOL_CONFIG_OPTS = {
'speed': 'link-speed',
'duplex': 'link-duplex',
'autoneg': 'ethernet-autoneg',
'ethernet-port': 'ethernet-port',
'wol': 'ethernet-wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'rx': 'offload-rx',
'tx': 'offload-tx',
'sg': 'offload-sg',
'tso': 'offload-tso',
'ufo': 'offload-ufo',
'gso': 'offload-gso',
'gro': 'offload-gro',
'lro': 'offload-lro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_REV_ETHTOOL_CONFIG_OPTS = {
'link-speed': 'speed',
'link-duplex': 'duplex',
'ethernet-autoneg': 'autoneg',
'ethernet-port': 'ethernet-port',
'ethernet-wol': 'wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'offload-rx': 'rx',
'offload-tx': 'tx',
'offload-sg': 'sg',
'offload-tso': 'tso',
'offload-ufo': 'ufo',
'offload-gso': 'gso',
'offload-lro': 'lro',
'offload-gro': 'gro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_DEB_CONFIG_PPPOE_OPTS = {
'user': 'user',
'password': 'password',
'provider': 'provider',
'pppoe_iface': 'pppoe_iface',
'noipdefault': 'noipdefault',
'usepeerdns': 'usepeerdns',
'defaultroute': 'defaultroute',
'holdoff': 'holdoff',
'maxfail': 'maxfail',
'hide-password': 'hide-password',
'lcp-echo-interval': 'lcp-echo-interval',
'lcp-echo-failure': 'lcp-echo-failure',
'connect': 'connect',
'noauth': 'noauth',
'persist': 'persist',
'mtu': 'mtu',
'noaccomp': 'noaccomp',
'linkname': 'linkname',
}
_DEB_ROUTES_FILE = '/etc/network/routes'
_DEB_NETWORK_FILE = '/etc/network/interfaces'
_DEB_NETWORK_DIR = '/etc/network/interfaces.d/'
_DEB_NETWORK_UP_DIR = '/etc/network/if-up.d/'
_DEB_NETWORK_DOWN_DIR = '/etc/network/if-down.d/'
_DEB_NETWORK_CONF_FILES = '/etc/modprobe.d/'
_DEB_NETWORKING_FILE = '/etc/default/networking'
_DEB_HOSTNAME_FILE = '/etc/hostname'
_DEB_RESOLV_FILE = '/etc/resolv.conf'
_DEB_PPP_DIR = '/etc/ppp/peers/'
_CONFIG_TRUE = ['yes', 'on', 'true', '1', True]
_CONFIG_FALSE = ['no', 'off', 'false', '0', False]
_IFACE_TYPES = [
'eth', 'bond', 'alias', 'clone',
'ipsec', 'dialup', 'bridge', 'slave',
'vlan', 'pppoe', 'source',
]
def _error_msg_iface(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, '|'.join(str(e) for e in expected))
def _error_msg_routes(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, expected)
def _log_default_iface(iface, opt, value):
log.info(
'Using default option -- Interface: %s Option: %s Value: %s',
iface, opt, value
)
def _error_msg_network(option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]'
return msg.format(option, '|'.join(str(e) for e in expected))
def _log_default_network(opt, value):
log.info('Using existing setting -- Setting: %s Value: %s', opt, value)
def _raise_error_iface(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_iface(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_network(option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_network(option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_routes(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_routes(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _read_file(path):
'''
Reads and returns the contents of a text file
'''
try:
with salt.utils.files.flopen(path, 'rb') as contents:
return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]
except (OSError, IOError):
return ''
def _parse_resolve():
'''
Parse /etc/resolv.conf
'''
return salt.utils.dns.parse_resolv(_DEB_RESOLV_FILE)
def _parse_domainname():
'''
Parse /etc/resolv.conf and return domainname
'''
return _parse_resolve().get('domain', '')
def _parse_searchdomain():
'''
Parse /etc/resolv.conf and return searchdomain
'''
return _parse_resolve().get('search', '')
def _parse_hostname():
'''
Parse /etc/hostname and return hostname
'''
contents = _read_file(_DEB_HOSTNAME_FILE)
if contents:
return contents[0].split('\n')[0]
else:
return ''
def _parse_current_network_settings():
'''
Parse /etc/default/networking and return current configuration
'''
opts = salt.utils.odict.OrderedDict()
opts['networking'] = ''
if os.path.isfile(_DEB_NETWORKING_FILE):
with salt.utils.files.fopen(_DEB_NETWORKING_FILE) as contents:
for line in contents:
salt.utils.stringutils.to_unicode(line)
if line.startswith('#'):
continue
elif line.startswith('CONFIGURE_INTERFACES'):
opts['networking'] = line.split('=', 1)[1].strip()
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
opts['hostname'] = hostname
opts['domainname'] = domainname
opts['searchdomain'] = searchdomain
return opts
# def __validator_func(value):
# return (valid: True/False, (transformed) value, error message)
def __ipv4_quad(value):
'''validate an IPv4 address'''
return (salt.utils.validate.net.ipv4_addr(value), value,
'dotted IPv4 address')
def __ipv6(value):
'''validate an IPv6 address'''
return (salt.utils.validate.net.ipv6_addr(value), value,
'IPv6 address')
def __mac(value):
'''validate a mac address'''
return (salt.utils.validate.net.mac(value), value,
'MAC address')
def __anything(value):
return (True, value, None)
def __int(value):
'''validate an integer'''
valid, _value = False, value
try:
_value = int(value)
valid = True
except ValueError:
pass
return (valid, _value, 'integer')
def __float(value):
'''validate a float'''
valid, _value = False, value
try:
_value = float(value)
valid = True
except ValueError:
pass
return (valid, _value, 'float')
def __ipv6_netmask(value):
'''validate an IPv6 integer netmask'''
valid, errmsg = False, 'IPv6 netmask (0->128)'
valid, value, _ = __int(value)
valid = (valid and 0 <= value <= 128)
return (valid, value, errmsg)
def __within2(value, within=None, errmsg=None, dtype=None):
'''validate that a value is in ``within`` and optionally a ``dtype``'''
valid, _value = False, value
if dtype:
try:
_value = dtype(value) # TODO: this is a bit loose when dtype is a class
valid = _value in within
except ValueError:
pass
else:
valid = _value in within
if errmsg is None:
if dtype:
typename = getattr(dtype, '__name__',
hasattr(dtype, '__class__')
and getattr(dtype.__class__, 'name', dtype))
errmsg = '{0} within \'{1}\''.format(typename, within)
else:
errmsg = 'within \'{0}\''.format(within)
return (valid, _value, errmsg)
def __within(within=None, errmsg=None, dtype=None):
return functools.partial(__within2, within=within,
errmsg=errmsg, dtype=dtype)
def __space_delimited_list(value):
'''validate that a value contains one or more space-delimited values'''
if isinstance(value, six.string_types):
value = value.strip().split()
if hasattr(value, '__iter__') and value != []:
return (True, value, 'space-delimited string')
else:
return (False, value, '{0} is not a valid space-delimited value.\n'.format(value))
SALT_ATTR_TO_DEBIAN_ATTR_MAP = {
'dns': 'dns-nameservers',
'search': 'dns-search',
'hwaddr': 'hwaddress', # TODO: this limits bootp functionality
'ipaddr': 'address',
'ipaddrs': 'addresses',
}
DEBIAN_ATTR_TO_SALT_ATTR_MAP = dict(
(v, k) for (k, v) in six.iteritems(SALT_ATTR_TO_DEBIAN_ATTR_MAP))
# TODO
DEBIAN_ATTR_TO_SALT_ATTR_MAP['address'] = 'address'
DEBIAN_ATTR_TO_SALT_ATTR_MAP['hwaddress'] = 'hwaddress'
IPV4_VALID_PROTO = ['bootp', 'dhcp', 'static', 'manual', 'loopback', 'ppp']
IPV4_ATTR_MAP = {
'proto': __within(IPV4_VALID_PROTO, dtype=six.text_type),
# ipv4 static & manual
'address': __ipv4_quad,
'addresses': __anything,
'netmask': __ipv4_netmask,
'broadcast': __ipv4_quad,
'metric': __int,
'gateway': __ipv4_quad, # supports a colon-delimited list
'pointopoint': __ipv4_quad,
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'link', 'host'], dtype=six.text_type),
# dhcp
'hostname': __anything,
'leasehours': __int,
'leasetime': __int,
'vendor': __anything,
'client': __anything,
# bootp
'bootfile': __anything,
'server': __ipv4_quad,
'hwaddr': __mac,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'dstaddr': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# bond
'slaves': __anything,
# ppp
'provider': __anything,
'unit': __int,
'options': __anything,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
#
'network': __anything, # i don't know what this is
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
IPV6_VALID_PROTO = ['auto', 'loopback', 'static', 'manual',
'dhcp', 'v4tunnel', '6to4']
IPV6_ATTR_MAP = {
'proto': __within(IPV6_VALID_PROTO),
# ipv6 static & manual
'address': __ipv6,
'addresses': __anything,
'netmask': __ipv6_netmask,
'broadcast': __ipv6,
'gateway': __ipv6, # supports a colon-delimited list
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'site', 'link', 'host'], dtype=six.text_type),
# inet6 auto
'privext': __within([0, 1, 2], dtype=int),
'dhcp': __within([0, 1], dtype=int),
# inet6 static & manual & dhcp
'media': __anything,
'accept_ra': __within([0, 1], dtype=int),
'autoconf': __within([0, 1], dtype=int),
'preferred-lifetime': __int,
'dad-attempts': __int, # 0 to disable
'dad-interval': __float,
# bond
'slaves': __anything,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
WIRELESS_ATTR_MAP = {
'wireless-essid': __anything,
'wireless-mode': __anything, # TODO
'wpa-ap-scan': __within([0, 1, 2], dtype=int), # TODO
'wpa-conf': __anything,
'wpa-driver': __anything,
'wpa-group': __anything,
'wpa-key-mgmt': __anything,
'wpa-pairwise': __anything,
'wpa-psk': __anything,
'wpa-proto': __anything, # partial(__within,
'wpa-roam': __anything,
'wpa-ssid': __anything, # TODO
}
ATTRMAPS = {
'inet': [IPV4_ATTR_MAP, WIRELESS_ATTR_MAP],
'inet6': [IPV6_ATTR_MAP, WIRELESS_ATTR_MAP]
}
def _validate_interface_option(attr, value, addrfam='inet'):
'''lookup the validation function for a [addrfam][attr] and
return the results
:param attr: attribute name
:param value: raw setting value
:param addrfam: address family (inet, inet6,
'''
valid, _value, errmsg = False, value, 'Unknown validator'
attrmaps = ATTRMAPS.get(addrfam, [])
for attrmap in attrmaps:
if attr in attrmap:
validate_func = attrmap[attr]
(valid, _value, errmsg) = validate_func(value)
break
return (valid, _value, errmsg)
def _attrmaps_contain_attr(attr):
return (
attr in WIRELESS_ATTR_MAP or
attr in IPV4_ATTR_MAP or
attr in IPV6_ATTR_MAP)
def _parse_interfaces(interface_files=None):
'''
Parse /etc/network/interfaces and return current configured interfaces
'''
if interface_files is None:
interface_files = []
# Add this later.
if os.path.exists(_DEB_NETWORK_DIR):
interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]
if os.path.isfile(_DEB_NETWORK_FILE):
interface_files.insert(0, _DEB_NETWORK_FILE)
adapters = salt.utils.odict.OrderedDict()
method = -1
for interface_file in interface_files:
with salt.utils.files.fopen(interface_file) as interfaces:
# This ensures iface_dict exists, but does not ensure we're not reading a new interface.
iface_dict = {}
for line in interfaces:
line = salt.utils.stringutils.to_unicode(line)
# Identify the clauses by the first word of each line.
# Go to the next line if the current line is a comment
# or all spaces.
if line.lstrip().startswith('#') or line.isspace():
continue
# Parse the iface clause
if line.startswith('iface'):
sline = line.split()
if len(sline) != 4:
msg = 'Interface file malformed: {0}.'
msg = msg.format(sline)
log.error(msg)
raise AttributeError(msg)
iface_name = sline[1]
addrfam = sline[2]
method = sline[3]
# Create item in dict, if not already there
if iface_name not in adapters:
adapters[iface_name] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters[iface_name]:
adapters[iface_name]['data'] = salt.utils.odict.OrderedDict()
if addrfam not in adapters[iface_name]['data']:
adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict()
iface_dict = adapters[iface_name]['data'][addrfam]
iface_dict['addrfam'] = addrfam
iface_dict['proto'] = method
iface_dict['filename'] = interface_file
# Parse the detail clauses.
elif line[0].isspace():
sline = line.split()
# conf file attr: dns-nameservers
# salt states.network attr: dns
attr, valuestr = line.rstrip().split(None, 1)
if _attrmaps_contain_attr(attr):
if '-' in attr:
attrname = attr.replace('-', '_')
else:
attrname = attr
(valid, value, errmsg) = _validate_interface_option(
attr, valuestr, addrfam)
if attrname == 'address' and 'address' in iface_dict:
if 'addresses' not in iface_dict:
iface_dict['addresses'] = []
iface_dict['addresses'].append(value)
else:
iface_dict[attrname] = value
elif attr in _REV_ETHTOOL_CONFIG_OPTS:
if 'ethtool' not in iface_dict:
iface_dict['ethtool'] = salt.utils.odict.OrderedDict()
iface_dict['ethtool'][attr] = valuestr
elif attr.startswith('bond'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bonding' not in iface_dict:
iface_dict['bonding'] = salt.utils.odict.OrderedDict()
iface_dict['bonding'][opt] = valuestr
elif attr.startswith('bridge'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bridging' not in iface_dict:
iface_dict['bridging'] = salt.utils.odict.OrderedDict()
iface_dict['bridging'][opt] = valuestr
elif attr in ['up', 'pre-up', 'post-up',
'down', 'pre-down', 'post-down']:
cmd = valuestr
cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr))
if cmd_key not in iface_dict:
iface_dict[cmd_key] = []
iface_dict[cmd_key].append(cmd)
elif line.startswith('auto'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['enabled'] = True
elif line.startswith('allow-hotplug'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['hotplug'] = True
elif line.startswith('source'):
if 'source' not in adapters:
adapters['source'] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters['source']:
adapters['source']['data'] = salt.utils.odict.OrderedDict()
adapters['source']['data']['sources'] = []
adapters['source']['data']['sources'].append(line.split()[1])
# Return a sorted list of the keys for bond, bridge and ethtool options to
# ensure a consistent order
for iface_name in adapters:
if iface_name == 'source':
continue
if 'data' not in adapters[iface_name]:
msg = 'Interface file malformed for interface: {0}.'.format(iface_name)
log.error(msg)
adapters.pop(iface_name)
continue
for opt in ['ethtool', 'bonding', 'bridging']:
for inet in ['inet', 'inet6']:
if inet in adapters[iface_name]['data']:
if opt in adapters[iface_name]['data'][inet]:
opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys())
adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys
return adapters
def _parse_ethtool_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
if 'autoneg' in opts:
if opts['autoneg'] in _CONFIG_TRUE:
config.update({'autoneg': 'on'})
elif opts['autoneg'] in _CONFIG_FALSE:
config.update({'autoneg': 'off'})
else:
_raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE)
if 'duplex' in opts:
valid = ['full', 'half']
if opts['duplex'] in valid:
config.update({'duplex': opts['duplex']})
else:
_raise_error_iface(iface, 'duplex', valid)
if 'speed' in opts:
valid = ['10', '100', '1000', '10000']
if six.text_type(opts['speed']) in valid:
config.update({'speed': opts['speed']})
else:
_raise_error_iface(iface, opts['speed'], valid)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'on'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'off'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_ethtool_pppoe_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
for opt in _DEB_CONFIG_PPPOE_OPTS:
if opt in opts:
config[opt] = opts[opt]
if 'provider' in opts and not opts['provider']:
_raise_error_iface(iface, 'provider', _CONFIG_TRUE + _CONFIG_FALSE)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('noipdefault', 'usepeerdns', 'defaultroute', 'hide-password', 'noauth', 'persist', 'noaccomp'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'True'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'False'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_settings_bond(opts, iface):
'''
Filters given options and outputs valid settings for requested
operation. If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond_def = {
# 803.ad aggregation selection logic
# 0 for stable (default)
# 1 for bandwidth
# 2 for count
'ad_select': '0',
# Max number of transmit queues (default = 16)
'tx_queues': '16',
# Link monitoring in milliseconds. Most NICs support this
'miimon': '100',
# ARP interval in milliseconds
'arp_interval': '250',
# Delay before considering link down in milliseconds (miimon * 2)
'downdelay': '200',
# lacp_rate 0: Slow - every 30 seconds
# lacp_rate 1: Fast - every 1 second
'lacp_rate': '0',
# Max bonds for this driver
'max_bonds': '1',
# Specifies the time, in milliseconds, to wait before
# enabling a slave after a link recovery has been
# detected. Only used with miimon.
'updelay': '0',
# Used with miimon.
# On: driver sends mii
# Off: ethtool sends mii
'use_carrier': 'on',
# Default. Don't change unless you know what you are doing.
'xmit_hash_policy': 'layer2',
}
if opts['mode'] in ['balance-rr', '0']:
log.info('Device: %s Bonding Mode: load balancing (round-robin)', iface)
return _parse_settings_bond_0(opts, iface, bond_def)
elif opts['mode'] in ['active-backup', '1']:
log.info('Device: %s Bonding Mode: fault-tolerance (active-backup)', iface)
return _parse_settings_bond_1(opts, iface, bond_def)
elif opts['mode'] in ['balance-xor', '2']:
log.info('Device: %s Bonding Mode: load balancing (xor)', iface)
return _parse_settings_bond_2(opts, iface, bond_def)
elif opts['mode'] in ['broadcast', '3']:
log.info('Device: %s Bonding Mode: fault-tolerance (broadcast)', iface)
return _parse_settings_bond_3(opts, iface, bond_def)
elif opts['mode'] in ['802.3ad', '4']:
log.info('Device: %s Bonding Mode: IEEE 802.3ad Dynamic link '
'aggregation', iface)
return _parse_settings_bond_4(opts, iface, bond_def)
elif opts['mode'] in ['balance-tlb', '5']:
log.info('Device: %s Bonding Mode: transmit load balancing', iface)
return _parse_settings_bond_5(opts, iface, bond_def)
elif opts['mode'] in ['balance-alb', '6']:
log.info('Device: %s Bonding Mode: adaptive load balancing', iface)
return _parse_settings_bond_6(opts, iface, bond_def)
else:
valid = [
'0', '1', '2', '3', '4', '5', '6',
'balance-rr', 'active-backup', 'balance-xor',
'broadcast', '802.3ad', 'balance-tlb', 'balance-alb'
]
_raise_error_iface(iface, 'mode', valid)
def _parse_settings_bond_0(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond0.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '0'}
# ARP targets in n.n.n.n form
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
return bond
def _parse_settings_bond_1(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '1'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
if not (__grains__['os'] == "Ubuntu" and __grains__['osrelease_info'][0] >= 16):
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_2(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond2.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '2'}
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_3(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond3.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '3'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_4(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond4.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '4'}
for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']:
if binding in opts:
if binding == 'lacp_rate':
if opts[binding] == 'fast':
opts.update({binding: '1'})
if opts[binding] == 'slow':
opts.update({binding: '0'})
valid = ['fast', '1', 'slow', '0']
else:
valid = ['integer']
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, valid)
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_5(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond5.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '5'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_settings_bond_6(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond6.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '6'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_bridge_opts(opts, iface):
'''
Filters given options and outputs valid settings for BRIDGING_OPTS
If an option has a value that is not expected, this
function will log the Interface, Setting and what was expected.
'''
config = {}
if 'ports' in opts:
if isinstance(opts['ports'], list):
opts['ports'] = ' '.join(opts['ports'])
config.update({'ports': opts['ports']})
for opt in ['ageing', 'fd', 'gcint', 'hello', 'maxage']:
if opt in opts:
try:
float(opts[opt])
config.update({opt: opts[opt]})
except ValueError:
_raise_error_iface(iface, opt, ['float'])
for opt in ['bridgeprio', 'maxwait']:
if opt in opts:
if isinstance(opts[opt], int):
config.update({opt: opts[opt]})
else:
_raise_error_iface(iface, opt, ['integer'])
if 'hw' in opts:
# match 12 hex digits with either : or - as separators between pairs
if re.match('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$',
opts['hw'].lower()):
config.update({'hw': opts['hw']})
else:
_raise_error_iface(iface, 'hw', ['valid MAC address'])
for opt in ['pathcost', 'portprio']:
if opt in opts:
try:
port, cost_or_prio = opts[opt].split()
int(cost_or_prio)
config.update({opt: '{0} {1}'.format(port, cost_or_prio)})
except ValueError:
_raise_error_iface(iface, opt, ['interface integer'])
if 'stp' in opts:
if opts['stp'] in _CONFIG_TRUE:
config.update({'stp': 'on'})
elif opts['stp'] in _CONFIG_FALSE:
config.update({'stp': 'off'})
else:
_raise_error_iface(iface, 'stp', _CONFIG_TRUE + _CONFIG_FALSE)
if 'waitport' in opts:
if isinstance(opts['waitport'], int):
config.update({'waitport': opts['waitport']})
else:
values = opts['waitport'].split()
waitport_time = values.pop(0)
if waitport_time.isdigit() and values:
config.update({
'waitport': '{0} {1}'.format(
waitport_time, ' '.join(values)
)
})
else:
_raise_error_iface(iface, opt, ['integer [interfaces]'])
return config
def _parse_settings_eth(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['inet'] = salt.utils.odict.OrderedDict()
iface_data['inet6'] = salt.utils.odict.OrderedDict()
if enabled:
adapters[iface]['enabled'] = True
if opts.get('hotplug', False):
adapters[iface]['hotplug'] = True
if opts.get('enable_ipv6', None) and opts.get('iface_type', '') == 'vlan':
iface_data['inet6']['vlan_raw_device'] = (
re.sub(r'\.\d*', '', iface))
for addrfam in ['inet', 'inet6']:
if iface_type not in ['bridge']:
tmp_ethtool = _parse_ethtool_opts(opts, iface)
if tmp_ethtool:
ethtool = {}
for item in tmp_ethtool:
ethtool[_ETHTOOL_CONFIG_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['ethtool'] = ethtool
# return a list of sorted keys to ensure consistent order
iface_data[addrfam]['ethtool_keys'] = sorted(ethtool)
if iface_type == 'bridge':
bridging = _parse_bridge_opts(opts, iface)
if bridging:
iface_data[addrfam]['bridging'] = bridging
iface_data[addrfam]['bridging_keys'] = sorted(bridging)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'bond':
bonding = _parse_settings_bond(opts, iface)
if bonding:
iface_data[addrfam]['bonding'] = bonding
iface_data[addrfam]['bonding']['slaves'] = opts['slaves']
iface_data[addrfam]['bonding_keys'] = sorted(bonding)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'slave':
adapters[iface]['master'] = opts['master']
opts['proto'] = 'manual'
iface_data[addrfam]['master'] = adapters[iface]['master']
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'vlan':
iface_data[addrfam]['vlan_raw_device'] = re.sub(r'\.\d*', '', iface)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'pppoe':
tmp_ethtool = _parse_ethtool_pppoe_opts(opts, iface)
if tmp_ethtool:
for item in tmp_ethtool:
adapters[iface]['data'][addrfam][_DEB_CONFIG_PPPOE_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['addrfam'] = addrfam
opts.pop('mode', None)
for opt, val in opts.items():
inet = None
if opt.startswith('ipv4'):
opt = opt[4:]
inet = 'inet'
iface_data['inet']['addrfam'] = 'inet'
elif opt.startswith('ipv6'):
iface_data['inet6']['addrfam'] = 'inet6'
opt = opt[4:]
inet = 'inet6'
elif opt in ['ipaddr', 'address', 'ipaddresses', 'addresses', 'gateway', 'proto']:
iface_data['inet']['addrfam'] = 'inet'
inet = 'inet'
_opt = SALT_ATTR_TO_DEBIAN_ATTR_MAP.get(opt, opt)
_debopt = _opt.replace('-', '_')
for addrfam in ['inet', 'inet6']:
(valid, value, errmsg) = _validate_interface_option(_opt, val, addrfam=addrfam)
if not valid:
continue
if inet is None and _debopt not in iface_data[addrfam]:
iface_data[addrfam][_debopt] = value
elif inet == addrfam:
iface_data[addrfam][_debopt] = value
for opt in ['up_cmds', 'pre_up_cmds', 'post_up_cmds',
'down_cmds', 'pre_down_cmds', 'post_down_cmds']:
if opt in opts:
iface_data['inet'][opt] = opts[opt]
iface_data['inet6'][opt] = opts[opt]
# Remove incomplete/disabled inet blocks
for (addrfam, opt) in [('inet', 'enable_ipv4'), ('inet6', 'enable_ipv6')]:
if opts.get(opt, None) is False:
iface_data.pop(addrfam)
elif iface_data[addrfam].get('addrfam', '') != addrfam:
iface_data.pop(addrfam)
return adapters
def _parse_settings_source(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['sources'] = [opts['source']]
return adapters
def _parse_network_settings(opts, current):
'''
Filters given options and outputs valid settings for
the global network settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
current = dict((k.lower(), v) for (k, v) in six.iteritems(current))
result = {}
valid = _CONFIG_TRUE + _CONFIG_FALSE
if 'enabled' not in opts:
try:
opts['networking'] = current['networking']
_log_default_network('networking', current['networking'])
except ValueError:
_raise_error_network('networking', valid)
else:
opts['networking'] = opts['enabled']
if opts['networking'] in valid:
if opts['networking'] in _CONFIG_TRUE:
result['networking'] = 'yes'
elif opts['networking'] in _CONFIG_FALSE:
result['networking'] = 'no'
else:
_raise_error_network('networking', valid)
if 'hostname' not in opts:
try:
opts['hostname'] = current['hostname']
_log_default_network('hostname', current['hostname'])
except ValueError:
_raise_error_network('hostname', ['server1.example.com'])
if opts['hostname']:
result['hostname'] = opts['hostname']
else:
_raise_error_network('hostname', ['server1.example.com'])
if 'search' in opts:
result['search'] = opts['search']
return result
def _parse_routes(iface, opts):
'''
Filters given options and outputs valid settings for
the route settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
result = {}
if 'routes' not in opts:
_raise_error_routes(iface, 'routes', 'List of routes')
for opt in opts:
result[opt] = opts[opt]
return result
def _write_file(iface, data, folder, pattern):
'''
Writes a file to disk
'''
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
return filename
def _write_file_routes(iface, data, folder, pattern):
'''
Writes a file to disk
'''
# ifup / ifdown is executing given folder via run-parts.
# according to run-parts man-page, only filenames with this pattern are
# executed: (^[a-zA-Z0-9_-]+$)
# In order to make the routes file work for vlan interfaces
# (default would have been in example /etc/network/if-up.d/route-bond0.12)
# these dots in the iface name need to be replaced by underscores, so it
# can be executed by run-parts
iface = iface.replace('.', '_')
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
__salt__['file.set_mode'](filename, '0755')
return filename
def _write_file_network(data, filename, create=False):
'''
Writes a file to disk
If file does not exist, only create if create
argument is True
'''
if not os.path.exists(filename) and not create:
msg = '{0} cannot be written. {0} does not exist\
and create is set to False'
msg = msg.format(filename)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
def _read_temp(data):
'''
Return what would be written to disk
'''
tout = StringIO()
tout.write(data)
tout.seek(0)
output = tout.readlines()
tout.close()
return output
def _read_temp_ifaces(iface, data):
'''
Return what would be written to disk for interfaces
'''
try:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': data})
# Return as an array so the difflib works
return [item + '\n' for item in ifcfg.split('\n')]
def _write_file_ifaces(iface, data, **settings):
'''
Writes a file to disk
'''
try:
eth_template = JINJA.get_template('debian_eth.jinja')
source_template = JINJA.get_template('debian_source.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
# Read /etc/network/interfaces into a dict
adapters = _parse_interfaces()
# Apply supplied settings over on-disk settings
adapters[iface] = data
ifcfg = ''
for adapter in adapters:
if 'type' in adapters[adapter] and adapters[adapter]['type'] == 'source':
tmp = source_template.render({'name': adapter, 'data': adapters[adapter]})
else:
tmp = eth_template.render({'name': adapter, 'data': adapters[adapter]})
ifcfg = ifcfg + tmp
if adapter == iface:
saved_ifcfg = tmp
_SEPARATE_FILE = False
if 'filename' in settings:
if not settings['filename'].startswith('/'):
filename = '{0}/{1}'.format(_DEB_NETWORK_DIR, settings['filename'])
else:
filename = settings['filename']
_SEPARATE_FILE = True
else:
if 'filename' in adapters[adapter]['data']:
filename = adapters[adapter]['data']
else:
filename = _DEB_NETWORK_FILE
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
if _SEPARATE_FILE:
fout.write(salt.utils.stringutils.to_str(saved_ifcfg))
else:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return saved_ifcfg.split('\n')
def _write_file_ppp_ifaces(iface, data):
'''
Writes a file to disk
'''
try:
template = JINJA.get_template('debian_ppp_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_ppp_eth.jinja')
return ''
adapters = _parse_interfaces()
adapters[iface] = data
ifcfg = ''
tmp = template.render({'data': adapters[iface]})
ifcfg = tmp + ifcfg
filename = _DEB_PPP_DIR + '/' + adapters[iface]['data']['inet']['provider']
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.fopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return filename
def build_bond(iface, **settings):
'''
Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb
'''
deb_major = __grains__['osrelease'][:1]
opts = _parse_settings_bond(settings, iface)
try:
template = JINJA.get_template('conf.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template conf.jinja')
return ''
data = template.render({'name': iface, 'bonding': opts})
if 'test' in settings and settings['test']:
return _read_temp(data)
_write_file(iface, data, _DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
if deb_major == '5':
for line_type in ('alias', 'options'):
cmd = ['sed', '-i', '-e', r'/^{0}\s{1}.*/d'.format(line_type, iface),
'/etc/modprobe.conf']
__salt__['cmd.run'](cmd, python_shell=False)
__salt__['file.append']('/etc/modprobe.conf', path)
# Load kernel module
__salt__['kmod.load']('bonding')
# install ifenslave-2.6
__salt__['pkg.install']('ifenslave-2.6')
return _read_file(path)
def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'vlan':
settings['vlan'] = 'yes'
__salt__['pkg.install']('vlan')
elif iface_type == 'pppoe':
settings['pppoe'] = 'yes'
if not __salt__['pkg.version']('ppp'):
inst = __salt__['pkg.install']('ppp')
elif iface_type == 'bond':
if 'slaves' not in settings:
msg = 'slaves is a required setting for bond interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'bridge':
if 'ports' not in settings:
msg = (
'ports is a required setting for bridge interfaces on Debian '
'or Ubuntu based systems'
)
log.error(msg)
raise AttributeError(msg)
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'pppoe']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
if iface_type in ['source']:
opts = _parse_settings_source(settings, iface_type, enabled, iface)
if 'test' in settings and settings['test']:
return _read_temp_ifaces(iface, opts[iface])
ifcfg = _write_file_ifaces(iface, opts[iface], **settings)
if iface_type == 'pppoe':
_write_file_ppp_ifaces(iface, opts[iface])
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg]
def build_routes(iface, **settings):
'''
Add route scripts for a network interface using up commands.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
'''
opts = _parse_routes(iface, settings)
try:
template = JINJA.get_template('route_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template route_eth.jinja')
return ''
add_routecfg = template.render(route_type='add',
routes=opts['routes'],
iface=iface)
del_routecfg = template.render(route_type='del',
routes=opts['routes'],
iface=iface)
if 'test' in settings and settings['test']:
return _read_temp(add_routecfg + del_routecfg)
filename = _write_file_routes(iface,
add_routecfg,
_DEB_NETWORK_UP_DIR,
'route-{0}')
results = _read_file(filename)
filename = _write_file_routes(iface,
del_routecfg,
_DEB_NETWORK_DOWN_DIR,
'route-{0}')
results += _read_file(filename)
return results
def down(iface, iface_type):
'''
Shutdown a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.down eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought down.
if iface_type not in ['slave', 'source']:
return __salt__['cmd.run'](['ifdown', iface])
return None
def get_bond(iface):
'''
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
'''
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
return _read_file(path)
def get_interface(iface):
'''
Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
adapters = _parse_interfaces()
if iface in adapters:
try:
if iface == 'source':
template = JINJA.get_template('debian_source.jinja')
else:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': adapters[iface]})
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg.split('\n')]
else:
return []
def up(iface, iface_type): # pylint: disable=C0103
'''
Start up a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.up eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought up.
if iface_type not in ('slave', 'source'):
return __salt__['cmd.run'](['ifup', iface])
return None
def get_network_settings():
'''
Return the contents of the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_network_settings
'''
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
settings = {}
if __salt__['service.available']('networking'):
if __salt__['service.status']('networking'):
settings['networking'] = "yes"
else:
settings['networking'] = "no"
else:
settings['networking'] = "no"
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
settings['hostname'] = hostname
settings['domainname'] = domainname
settings['searchdomain'] = searchdomain
else:
settings = _parse_current_network_settings()
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(settings)
return _read_temp(network)
def get_routes(iface):
'''
Return the routes for the interface
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0
'''
filename = os.path.join(_DEB_NETWORK_UP_DIR, 'route-{0}'.format(iface))
results = _read_file(filename)
filename = os.path.join(_DEB_NETWORK_DOWN_DIR, 'route-{0}'.format(iface))
results += _read_file(filename)
return results
def apply_network_settings(**settings):
'''
Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings
'''
if 'require_reboot' not in settings:
settings['require_reboot'] = False
if 'apply_hostname' not in settings:
settings['apply_hostname'] = False
hostname_res = True
if settings['apply_hostname'] in _CONFIG_TRUE:
if 'hostname' in settings:
hostname_res = __salt__['network.mod_hostname'](settings['hostname'])
else:
log.warning(
'The network state sls is trying to apply hostname '
'changes but no hostname is defined.'
)
hostname_res = False
res = True
if settings['require_reboot'] in _CONFIG_TRUE:
log.warning(
'The network state sls is requiring a reboot of the system to '
'properly apply network configuration.'
)
res = True
else:
stop = __salt__['service.stop']('networking')
time.sleep(2)
res = stop and __salt__['service.start']('networking')
return hostname_res and res
def build_network_settings(**settings):
'''
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
'''
changes = []
# Read current configuration and store default values
current_network_settings = _parse_current_network_settings()
# Build settings
opts = _parse_network_settings(settings, current_network_settings)
# Ubuntu has moved away from /etc/default/networking
# beginning with the 12.04 release so we disable or enable
# the networking related services on boot
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
if opts['networking'] == 'yes':
service_cmd = 'service.enable'
else:
service_cmd = 'service.disable'
if __salt__['service.available']('NetworkManager'):
__salt__[service_cmd]('NetworkManager')
if __salt__['service.available']('networking'):
__salt__[service_cmd]('networking')
else:
try:
template = JINJA.get_template('network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template network.jinja')
return ''
network = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(network)
# Write settings
_write_file_network(network, _DEB_NETWORKING_FILE, True)
# Get hostname and domain from opts
sline = opts['hostname'].split('.', 1)
opts['hostname'] = sline[0]
current_domainname = current_network_settings['domainname']
current_searchdomain = current_network_settings['searchdomain']
new_domain = False
if len(sline) > 1:
new_domainname = sline[1]
if new_domainname != current_domainname:
domainname = new_domainname
opts['domainname'] = new_domainname
new_domain = True
else:
domainname = current_domainname
opts['domainname'] = domainname
else:
domainname = current_domainname
opts['domainname'] = domainname
new_search = False
if 'search' in opts:
new_searchdomain = opts['search']
if new_searchdomain != current_searchdomain:
searchdomain = new_searchdomain
opts['searchdomain'] = new_searchdomain
new_search = True
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
# If the domain changes, then we should write the resolv.conf file.
if new_domain or new_search:
# Look for existing domain line and update if necessary
resolve = _parse_resolve()
domain_prog = re.compile(r'domain\s+')
search_prog = re.compile(r'search\s+')
new_contents = []
for item in _read_file(_DEB_RESOLV_FILE):
if domain_prog.match(item):
item = 'domain {0}'.format(domainname)
elif search_prog.match(item):
item = 'search {0}'.format(searchdomain)
new_contents.append(item)
# A domain line didn't exist so we'll add one in
# with the new domainname
if 'domain' not in resolve:
new_contents.insert(0, 'domain {0}' . format(domainname))
# A search line didn't exist so we'll add one in
# with the new search domain
if 'search' not in resolve:
new_contents.insert('domain' in resolve, 'search {0}'.format(searchdomain))
new_resolv = '\n'.join(new_contents)
# Write /etc/resolv.conf
if not ('test' in settings and settings['test']):
_write_file_network(new_resolv, _DEB_RESOLV_FILE)
# used for returning the results back
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(opts)
changes.extend(_read_temp(network))
return changes
|
saltstack/salt
|
salt/modules/debian_ip.py
|
__ipv6_netmask
|
python
|
def __ipv6_netmask(value):
'''validate an IPv6 integer netmask'''
valid, errmsg = False, 'IPv6 netmask (0->128)'
valid, value, _ = __int(value)
valid = (valid and 0 <= value <= 128)
return (valid, value, errmsg)
|
validate an IPv6 integer netmask
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_ip.py#L346-L351
| null |
# -*- coding: utf-8 -*-
'''
The networking module for Debian-based distros
References:
* http://www.debian.org/doc/manuals/debian-reference/ch05.en.html
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import functools
import logging
import os.path
import os
import re
import time
# Import third party libs
import jinja2
import jinja2.exceptions
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error,no-name-in-module
# Import salt libs
import salt.utils.dns
import salt.utils.files
import salt.utils.odict
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.validate.net
# Set up logging
log = logging.getLogger(__name__)
# Set up template environment
JINJA = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'debian_ip')
)
)
# Define the module's virtual name
__virtualname__ = 'ip'
def __virtual__():
'''
Confine this module to Debian-based distros
'''
if __grains__['os_family'] == 'Debian':
return __virtualname__
return (False, 'The debian_ip module could not be loaded: '
'unsupported OS family')
_ETHTOOL_CONFIG_OPTS = {
'speed': 'link-speed',
'duplex': 'link-duplex',
'autoneg': 'ethernet-autoneg',
'ethernet-port': 'ethernet-port',
'wol': 'ethernet-wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'rx': 'offload-rx',
'tx': 'offload-tx',
'sg': 'offload-sg',
'tso': 'offload-tso',
'ufo': 'offload-ufo',
'gso': 'offload-gso',
'gro': 'offload-gro',
'lro': 'offload-lro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_REV_ETHTOOL_CONFIG_OPTS = {
'link-speed': 'speed',
'link-duplex': 'duplex',
'ethernet-autoneg': 'autoneg',
'ethernet-port': 'ethernet-port',
'ethernet-wol': 'wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'offload-rx': 'rx',
'offload-tx': 'tx',
'offload-sg': 'sg',
'offload-tso': 'tso',
'offload-ufo': 'ufo',
'offload-gso': 'gso',
'offload-lro': 'lro',
'offload-gro': 'gro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_DEB_CONFIG_PPPOE_OPTS = {
'user': 'user',
'password': 'password',
'provider': 'provider',
'pppoe_iface': 'pppoe_iface',
'noipdefault': 'noipdefault',
'usepeerdns': 'usepeerdns',
'defaultroute': 'defaultroute',
'holdoff': 'holdoff',
'maxfail': 'maxfail',
'hide-password': 'hide-password',
'lcp-echo-interval': 'lcp-echo-interval',
'lcp-echo-failure': 'lcp-echo-failure',
'connect': 'connect',
'noauth': 'noauth',
'persist': 'persist',
'mtu': 'mtu',
'noaccomp': 'noaccomp',
'linkname': 'linkname',
}
_DEB_ROUTES_FILE = '/etc/network/routes'
_DEB_NETWORK_FILE = '/etc/network/interfaces'
_DEB_NETWORK_DIR = '/etc/network/interfaces.d/'
_DEB_NETWORK_UP_DIR = '/etc/network/if-up.d/'
_DEB_NETWORK_DOWN_DIR = '/etc/network/if-down.d/'
_DEB_NETWORK_CONF_FILES = '/etc/modprobe.d/'
_DEB_NETWORKING_FILE = '/etc/default/networking'
_DEB_HOSTNAME_FILE = '/etc/hostname'
_DEB_RESOLV_FILE = '/etc/resolv.conf'
_DEB_PPP_DIR = '/etc/ppp/peers/'
_CONFIG_TRUE = ['yes', 'on', 'true', '1', True]
_CONFIG_FALSE = ['no', 'off', 'false', '0', False]
_IFACE_TYPES = [
'eth', 'bond', 'alias', 'clone',
'ipsec', 'dialup', 'bridge', 'slave',
'vlan', 'pppoe', 'source',
]
def _error_msg_iface(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, '|'.join(str(e) for e in expected))
def _error_msg_routes(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, expected)
def _log_default_iface(iface, opt, value):
log.info(
'Using default option -- Interface: %s Option: %s Value: %s',
iface, opt, value
)
def _error_msg_network(option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]'
return msg.format(option, '|'.join(str(e) for e in expected))
def _log_default_network(opt, value):
log.info('Using existing setting -- Setting: %s Value: %s', opt, value)
def _raise_error_iface(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_iface(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_network(option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_network(option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_routes(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_routes(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _read_file(path):
'''
Reads and returns the contents of a text file
'''
try:
with salt.utils.files.flopen(path, 'rb') as contents:
return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]
except (OSError, IOError):
return ''
def _parse_resolve():
'''
Parse /etc/resolv.conf
'''
return salt.utils.dns.parse_resolv(_DEB_RESOLV_FILE)
def _parse_domainname():
'''
Parse /etc/resolv.conf and return domainname
'''
return _parse_resolve().get('domain', '')
def _parse_searchdomain():
'''
Parse /etc/resolv.conf and return searchdomain
'''
return _parse_resolve().get('search', '')
def _parse_hostname():
'''
Parse /etc/hostname and return hostname
'''
contents = _read_file(_DEB_HOSTNAME_FILE)
if contents:
return contents[0].split('\n')[0]
else:
return ''
def _parse_current_network_settings():
'''
Parse /etc/default/networking and return current configuration
'''
opts = salt.utils.odict.OrderedDict()
opts['networking'] = ''
if os.path.isfile(_DEB_NETWORKING_FILE):
with salt.utils.files.fopen(_DEB_NETWORKING_FILE) as contents:
for line in contents:
salt.utils.stringutils.to_unicode(line)
if line.startswith('#'):
continue
elif line.startswith('CONFIGURE_INTERFACES'):
opts['networking'] = line.split('=', 1)[1].strip()
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
opts['hostname'] = hostname
opts['domainname'] = domainname
opts['searchdomain'] = searchdomain
return opts
# def __validator_func(value):
# return (valid: True/False, (transformed) value, error message)
def __ipv4_quad(value):
'''validate an IPv4 address'''
return (salt.utils.validate.net.ipv4_addr(value), value,
'dotted IPv4 address')
def __ipv6(value):
'''validate an IPv6 address'''
return (salt.utils.validate.net.ipv6_addr(value), value,
'IPv6 address')
def __mac(value):
'''validate a mac address'''
return (salt.utils.validate.net.mac(value), value,
'MAC address')
def __anything(value):
return (True, value, None)
def __int(value):
'''validate an integer'''
valid, _value = False, value
try:
_value = int(value)
valid = True
except ValueError:
pass
return (valid, _value, 'integer')
def __float(value):
'''validate a float'''
valid, _value = False, value
try:
_value = float(value)
valid = True
except ValueError:
pass
return (valid, _value, 'float')
def __ipv4_netmask(value):
'''validate an IPv4 dotted quad or integer CIDR netmask'''
valid, errmsg = False, 'dotted quad or integer CIDR (0->32)'
valid, value, _ = __int(value)
if not (valid and 0 <= value <= 32):
valid = salt.utils.validate.net.netmask(value)
return (valid, value, errmsg)
def __within2(value, within=None, errmsg=None, dtype=None):
'''validate that a value is in ``within`` and optionally a ``dtype``'''
valid, _value = False, value
if dtype:
try:
_value = dtype(value) # TODO: this is a bit loose when dtype is a class
valid = _value in within
except ValueError:
pass
else:
valid = _value in within
if errmsg is None:
if dtype:
typename = getattr(dtype, '__name__',
hasattr(dtype, '__class__')
and getattr(dtype.__class__, 'name', dtype))
errmsg = '{0} within \'{1}\''.format(typename, within)
else:
errmsg = 'within \'{0}\''.format(within)
return (valid, _value, errmsg)
def __within(within=None, errmsg=None, dtype=None):
return functools.partial(__within2, within=within,
errmsg=errmsg, dtype=dtype)
def __space_delimited_list(value):
'''validate that a value contains one or more space-delimited values'''
if isinstance(value, six.string_types):
value = value.strip().split()
if hasattr(value, '__iter__') and value != []:
return (True, value, 'space-delimited string')
else:
return (False, value, '{0} is not a valid space-delimited value.\n'.format(value))
SALT_ATTR_TO_DEBIAN_ATTR_MAP = {
'dns': 'dns-nameservers',
'search': 'dns-search',
'hwaddr': 'hwaddress', # TODO: this limits bootp functionality
'ipaddr': 'address',
'ipaddrs': 'addresses',
}
DEBIAN_ATTR_TO_SALT_ATTR_MAP = dict(
(v, k) for (k, v) in six.iteritems(SALT_ATTR_TO_DEBIAN_ATTR_MAP))
# TODO
DEBIAN_ATTR_TO_SALT_ATTR_MAP['address'] = 'address'
DEBIAN_ATTR_TO_SALT_ATTR_MAP['hwaddress'] = 'hwaddress'
IPV4_VALID_PROTO = ['bootp', 'dhcp', 'static', 'manual', 'loopback', 'ppp']
IPV4_ATTR_MAP = {
'proto': __within(IPV4_VALID_PROTO, dtype=six.text_type),
# ipv4 static & manual
'address': __ipv4_quad,
'addresses': __anything,
'netmask': __ipv4_netmask,
'broadcast': __ipv4_quad,
'metric': __int,
'gateway': __ipv4_quad, # supports a colon-delimited list
'pointopoint': __ipv4_quad,
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'link', 'host'], dtype=six.text_type),
# dhcp
'hostname': __anything,
'leasehours': __int,
'leasetime': __int,
'vendor': __anything,
'client': __anything,
# bootp
'bootfile': __anything,
'server': __ipv4_quad,
'hwaddr': __mac,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'dstaddr': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# bond
'slaves': __anything,
# ppp
'provider': __anything,
'unit': __int,
'options': __anything,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
#
'network': __anything, # i don't know what this is
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
IPV6_VALID_PROTO = ['auto', 'loopback', 'static', 'manual',
'dhcp', 'v4tunnel', '6to4']
IPV6_ATTR_MAP = {
'proto': __within(IPV6_VALID_PROTO),
# ipv6 static & manual
'address': __ipv6,
'addresses': __anything,
'netmask': __ipv6_netmask,
'broadcast': __ipv6,
'gateway': __ipv6, # supports a colon-delimited list
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'site', 'link', 'host'], dtype=six.text_type),
# inet6 auto
'privext': __within([0, 1, 2], dtype=int),
'dhcp': __within([0, 1], dtype=int),
# inet6 static & manual & dhcp
'media': __anything,
'accept_ra': __within([0, 1], dtype=int),
'autoconf': __within([0, 1], dtype=int),
'preferred-lifetime': __int,
'dad-attempts': __int, # 0 to disable
'dad-interval': __float,
# bond
'slaves': __anything,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
WIRELESS_ATTR_MAP = {
'wireless-essid': __anything,
'wireless-mode': __anything, # TODO
'wpa-ap-scan': __within([0, 1, 2], dtype=int), # TODO
'wpa-conf': __anything,
'wpa-driver': __anything,
'wpa-group': __anything,
'wpa-key-mgmt': __anything,
'wpa-pairwise': __anything,
'wpa-psk': __anything,
'wpa-proto': __anything, # partial(__within,
'wpa-roam': __anything,
'wpa-ssid': __anything, # TODO
}
ATTRMAPS = {
'inet': [IPV4_ATTR_MAP, WIRELESS_ATTR_MAP],
'inet6': [IPV6_ATTR_MAP, WIRELESS_ATTR_MAP]
}
def _validate_interface_option(attr, value, addrfam='inet'):
'''lookup the validation function for a [addrfam][attr] and
return the results
:param attr: attribute name
:param value: raw setting value
:param addrfam: address family (inet, inet6,
'''
valid, _value, errmsg = False, value, 'Unknown validator'
attrmaps = ATTRMAPS.get(addrfam, [])
for attrmap in attrmaps:
if attr in attrmap:
validate_func = attrmap[attr]
(valid, _value, errmsg) = validate_func(value)
break
return (valid, _value, errmsg)
def _attrmaps_contain_attr(attr):
return (
attr in WIRELESS_ATTR_MAP or
attr in IPV4_ATTR_MAP or
attr in IPV6_ATTR_MAP)
def _parse_interfaces(interface_files=None):
'''
Parse /etc/network/interfaces and return current configured interfaces
'''
if interface_files is None:
interface_files = []
# Add this later.
if os.path.exists(_DEB_NETWORK_DIR):
interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]
if os.path.isfile(_DEB_NETWORK_FILE):
interface_files.insert(0, _DEB_NETWORK_FILE)
adapters = salt.utils.odict.OrderedDict()
method = -1
for interface_file in interface_files:
with salt.utils.files.fopen(interface_file) as interfaces:
# This ensures iface_dict exists, but does not ensure we're not reading a new interface.
iface_dict = {}
for line in interfaces:
line = salt.utils.stringutils.to_unicode(line)
# Identify the clauses by the first word of each line.
# Go to the next line if the current line is a comment
# or all spaces.
if line.lstrip().startswith('#') or line.isspace():
continue
# Parse the iface clause
if line.startswith('iface'):
sline = line.split()
if len(sline) != 4:
msg = 'Interface file malformed: {0}.'
msg = msg.format(sline)
log.error(msg)
raise AttributeError(msg)
iface_name = sline[1]
addrfam = sline[2]
method = sline[3]
# Create item in dict, if not already there
if iface_name not in adapters:
adapters[iface_name] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters[iface_name]:
adapters[iface_name]['data'] = salt.utils.odict.OrderedDict()
if addrfam not in adapters[iface_name]['data']:
adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict()
iface_dict = adapters[iface_name]['data'][addrfam]
iface_dict['addrfam'] = addrfam
iface_dict['proto'] = method
iface_dict['filename'] = interface_file
# Parse the detail clauses.
elif line[0].isspace():
sline = line.split()
# conf file attr: dns-nameservers
# salt states.network attr: dns
attr, valuestr = line.rstrip().split(None, 1)
if _attrmaps_contain_attr(attr):
if '-' in attr:
attrname = attr.replace('-', '_')
else:
attrname = attr
(valid, value, errmsg) = _validate_interface_option(
attr, valuestr, addrfam)
if attrname == 'address' and 'address' in iface_dict:
if 'addresses' not in iface_dict:
iface_dict['addresses'] = []
iface_dict['addresses'].append(value)
else:
iface_dict[attrname] = value
elif attr in _REV_ETHTOOL_CONFIG_OPTS:
if 'ethtool' not in iface_dict:
iface_dict['ethtool'] = salt.utils.odict.OrderedDict()
iface_dict['ethtool'][attr] = valuestr
elif attr.startswith('bond'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bonding' not in iface_dict:
iface_dict['bonding'] = salt.utils.odict.OrderedDict()
iface_dict['bonding'][opt] = valuestr
elif attr.startswith('bridge'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bridging' not in iface_dict:
iface_dict['bridging'] = salt.utils.odict.OrderedDict()
iface_dict['bridging'][opt] = valuestr
elif attr in ['up', 'pre-up', 'post-up',
'down', 'pre-down', 'post-down']:
cmd = valuestr
cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr))
if cmd_key not in iface_dict:
iface_dict[cmd_key] = []
iface_dict[cmd_key].append(cmd)
elif line.startswith('auto'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['enabled'] = True
elif line.startswith('allow-hotplug'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['hotplug'] = True
elif line.startswith('source'):
if 'source' not in adapters:
adapters['source'] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters['source']:
adapters['source']['data'] = salt.utils.odict.OrderedDict()
adapters['source']['data']['sources'] = []
adapters['source']['data']['sources'].append(line.split()[1])
# Return a sorted list of the keys for bond, bridge and ethtool options to
# ensure a consistent order
for iface_name in adapters:
if iface_name == 'source':
continue
if 'data' not in adapters[iface_name]:
msg = 'Interface file malformed for interface: {0}.'.format(iface_name)
log.error(msg)
adapters.pop(iface_name)
continue
for opt in ['ethtool', 'bonding', 'bridging']:
for inet in ['inet', 'inet6']:
if inet in adapters[iface_name]['data']:
if opt in adapters[iface_name]['data'][inet]:
opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys())
adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys
return adapters
def _parse_ethtool_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
if 'autoneg' in opts:
if opts['autoneg'] in _CONFIG_TRUE:
config.update({'autoneg': 'on'})
elif opts['autoneg'] in _CONFIG_FALSE:
config.update({'autoneg': 'off'})
else:
_raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE)
if 'duplex' in opts:
valid = ['full', 'half']
if opts['duplex'] in valid:
config.update({'duplex': opts['duplex']})
else:
_raise_error_iface(iface, 'duplex', valid)
if 'speed' in opts:
valid = ['10', '100', '1000', '10000']
if six.text_type(opts['speed']) in valid:
config.update({'speed': opts['speed']})
else:
_raise_error_iface(iface, opts['speed'], valid)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'on'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'off'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_ethtool_pppoe_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
for opt in _DEB_CONFIG_PPPOE_OPTS:
if opt in opts:
config[opt] = opts[opt]
if 'provider' in opts and not opts['provider']:
_raise_error_iface(iface, 'provider', _CONFIG_TRUE + _CONFIG_FALSE)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('noipdefault', 'usepeerdns', 'defaultroute', 'hide-password', 'noauth', 'persist', 'noaccomp'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'True'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'False'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_settings_bond(opts, iface):
'''
Filters given options and outputs valid settings for requested
operation. If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond_def = {
# 803.ad aggregation selection logic
# 0 for stable (default)
# 1 for bandwidth
# 2 for count
'ad_select': '0',
# Max number of transmit queues (default = 16)
'tx_queues': '16',
# Link monitoring in milliseconds. Most NICs support this
'miimon': '100',
# ARP interval in milliseconds
'arp_interval': '250',
# Delay before considering link down in milliseconds (miimon * 2)
'downdelay': '200',
# lacp_rate 0: Slow - every 30 seconds
# lacp_rate 1: Fast - every 1 second
'lacp_rate': '0',
# Max bonds for this driver
'max_bonds': '1',
# Specifies the time, in milliseconds, to wait before
# enabling a slave after a link recovery has been
# detected. Only used with miimon.
'updelay': '0',
# Used with miimon.
# On: driver sends mii
# Off: ethtool sends mii
'use_carrier': 'on',
# Default. Don't change unless you know what you are doing.
'xmit_hash_policy': 'layer2',
}
if opts['mode'] in ['balance-rr', '0']:
log.info('Device: %s Bonding Mode: load balancing (round-robin)', iface)
return _parse_settings_bond_0(opts, iface, bond_def)
elif opts['mode'] in ['active-backup', '1']:
log.info('Device: %s Bonding Mode: fault-tolerance (active-backup)', iface)
return _parse_settings_bond_1(opts, iface, bond_def)
elif opts['mode'] in ['balance-xor', '2']:
log.info('Device: %s Bonding Mode: load balancing (xor)', iface)
return _parse_settings_bond_2(opts, iface, bond_def)
elif opts['mode'] in ['broadcast', '3']:
log.info('Device: %s Bonding Mode: fault-tolerance (broadcast)', iface)
return _parse_settings_bond_3(opts, iface, bond_def)
elif opts['mode'] in ['802.3ad', '4']:
log.info('Device: %s Bonding Mode: IEEE 802.3ad Dynamic link '
'aggregation', iface)
return _parse_settings_bond_4(opts, iface, bond_def)
elif opts['mode'] in ['balance-tlb', '5']:
log.info('Device: %s Bonding Mode: transmit load balancing', iface)
return _parse_settings_bond_5(opts, iface, bond_def)
elif opts['mode'] in ['balance-alb', '6']:
log.info('Device: %s Bonding Mode: adaptive load balancing', iface)
return _parse_settings_bond_6(opts, iface, bond_def)
else:
valid = [
'0', '1', '2', '3', '4', '5', '6',
'balance-rr', 'active-backup', 'balance-xor',
'broadcast', '802.3ad', 'balance-tlb', 'balance-alb'
]
_raise_error_iface(iface, 'mode', valid)
def _parse_settings_bond_0(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond0.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '0'}
# ARP targets in n.n.n.n form
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
return bond
def _parse_settings_bond_1(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '1'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
if not (__grains__['os'] == "Ubuntu" and __grains__['osrelease_info'][0] >= 16):
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_2(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond2.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '2'}
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_3(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond3.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '3'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_4(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond4.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '4'}
for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']:
if binding in opts:
if binding == 'lacp_rate':
if opts[binding] == 'fast':
opts.update({binding: '1'})
if opts[binding] == 'slow':
opts.update({binding: '0'})
valid = ['fast', '1', 'slow', '0']
else:
valid = ['integer']
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, valid)
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_5(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond5.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '5'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_settings_bond_6(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond6.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '6'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_bridge_opts(opts, iface):
'''
Filters given options and outputs valid settings for BRIDGING_OPTS
If an option has a value that is not expected, this
function will log the Interface, Setting and what was expected.
'''
config = {}
if 'ports' in opts:
if isinstance(opts['ports'], list):
opts['ports'] = ' '.join(opts['ports'])
config.update({'ports': opts['ports']})
for opt in ['ageing', 'fd', 'gcint', 'hello', 'maxage']:
if opt in opts:
try:
float(opts[opt])
config.update({opt: opts[opt]})
except ValueError:
_raise_error_iface(iface, opt, ['float'])
for opt in ['bridgeprio', 'maxwait']:
if opt in opts:
if isinstance(opts[opt], int):
config.update({opt: opts[opt]})
else:
_raise_error_iface(iface, opt, ['integer'])
if 'hw' in opts:
# match 12 hex digits with either : or - as separators between pairs
if re.match('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$',
opts['hw'].lower()):
config.update({'hw': opts['hw']})
else:
_raise_error_iface(iface, 'hw', ['valid MAC address'])
for opt in ['pathcost', 'portprio']:
if opt in opts:
try:
port, cost_or_prio = opts[opt].split()
int(cost_or_prio)
config.update({opt: '{0} {1}'.format(port, cost_or_prio)})
except ValueError:
_raise_error_iface(iface, opt, ['interface integer'])
if 'stp' in opts:
if opts['stp'] in _CONFIG_TRUE:
config.update({'stp': 'on'})
elif opts['stp'] in _CONFIG_FALSE:
config.update({'stp': 'off'})
else:
_raise_error_iface(iface, 'stp', _CONFIG_TRUE + _CONFIG_FALSE)
if 'waitport' in opts:
if isinstance(opts['waitport'], int):
config.update({'waitport': opts['waitport']})
else:
values = opts['waitport'].split()
waitport_time = values.pop(0)
if waitport_time.isdigit() and values:
config.update({
'waitport': '{0} {1}'.format(
waitport_time, ' '.join(values)
)
})
else:
_raise_error_iface(iface, opt, ['integer [interfaces]'])
return config
def _parse_settings_eth(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['inet'] = salt.utils.odict.OrderedDict()
iface_data['inet6'] = salt.utils.odict.OrderedDict()
if enabled:
adapters[iface]['enabled'] = True
if opts.get('hotplug', False):
adapters[iface]['hotplug'] = True
if opts.get('enable_ipv6', None) and opts.get('iface_type', '') == 'vlan':
iface_data['inet6']['vlan_raw_device'] = (
re.sub(r'\.\d*', '', iface))
for addrfam in ['inet', 'inet6']:
if iface_type not in ['bridge']:
tmp_ethtool = _parse_ethtool_opts(opts, iface)
if tmp_ethtool:
ethtool = {}
for item in tmp_ethtool:
ethtool[_ETHTOOL_CONFIG_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['ethtool'] = ethtool
# return a list of sorted keys to ensure consistent order
iface_data[addrfam]['ethtool_keys'] = sorted(ethtool)
if iface_type == 'bridge':
bridging = _parse_bridge_opts(opts, iface)
if bridging:
iface_data[addrfam]['bridging'] = bridging
iface_data[addrfam]['bridging_keys'] = sorted(bridging)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'bond':
bonding = _parse_settings_bond(opts, iface)
if bonding:
iface_data[addrfam]['bonding'] = bonding
iface_data[addrfam]['bonding']['slaves'] = opts['slaves']
iface_data[addrfam]['bonding_keys'] = sorted(bonding)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'slave':
adapters[iface]['master'] = opts['master']
opts['proto'] = 'manual'
iface_data[addrfam]['master'] = adapters[iface]['master']
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'vlan':
iface_data[addrfam]['vlan_raw_device'] = re.sub(r'\.\d*', '', iface)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'pppoe':
tmp_ethtool = _parse_ethtool_pppoe_opts(opts, iface)
if tmp_ethtool:
for item in tmp_ethtool:
adapters[iface]['data'][addrfam][_DEB_CONFIG_PPPOE_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['addrfam'] = addrfam
opts.pop('mode', None)
for opt, val in opts.items():
inet = None
if opt.startswith('ipv4'):
opt = opt[4:]
inet = 'inet'
iface_data['inet']['addrfam'] = 'inet'
elif opt.startswith('ipv6'):
iface_data['inet6']['addrfam'] = 'inet6'
opt = opt[4:]
inet = 'inet6'
elif opt in ['ipaddr', 'address', 'ipaddresses', 'addresses', 'gateway', 'proto']:
iface_data['inet']['addrfam'] = 'inet'
inet = 'inet'
_opt = SALT_ATTR_TO_DEBIAN_ATTR_MAP.get(opt, opt)
_debopt = _opt.replace('-', '_')
for addrfam in ['inet', 'inet6']:
(valid, value, errmsg) = _validate_interface_option(_opt, val, addrfam=addrfam)
if not valid:
continue
if inet is None and _debopt not in iface_data[addrfam]:
iface_data[addrfam][_debopt] = value
elif inet == addrfam:
iface_data[addrfam][_debopt] = value
for opt in ['up_cmds', 'pre_up_cmds', 'post_up_cmds',
'down_cmds', 'pre_down_cmds', 'post_down_cmds']:
if opt in opts:
iface_data['inet'][opt] = opts[opt]
iface_data['inet6'][opt] = opts[opt]
# Remove incomplete/disabled inet blocks
for (addrfam, opt) in [('inet', 'enable_ipv4'), ('inet6', 'enable_ipv6')]:
if opts.get(opt, None) is False:
iface_data.pop(addrfam)
elif iface_data[addrfam].get('addrfam', '') != addrfam:
iface_data.pop(addrfam)
return adapters
def _parse_settings_source(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['sources'] = [opts['source']]
return adapters
def _parse_network_settings(opts, current):
'''
Filters given options and outputs valid settings for
the global network settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
current = dict((k.lower(), v) for (k, v) in six.iteritems(current))
result = {}
valid = _CONFIG_TRUE + _CONFIG_FALSE
if 'enabled' not in opts:
try:
opts['networking'] = current['networking']
_log_default_network('networking', current['networking'])
except ValueError:
_raise_error_network('networking', valid)
else:
opts['networking'] = opts['enabled']
if opts['networking'] in valid:
if opts['networking'] in _CONFIG_TRUE:
result['networking'] = 'yes'
elif opts['networking'] in _CONFIG_FALSE:
result['networking'] = 'no'
else:
_raise_error_network('networking', valid)
if 'hostname' not in opts:
try:
opts['hostname'] = current['hostname']
_log_default_network('hostname', current['hostname'])
except ValueError:
_raise_error_network('hostname', ['server1.example.com'])
if opts['hostname']:
result['hostname'] = opts['hostname']
else:
_raise_error_network('hostname', ['server1.example.com'])
if 'search' in opts:
result['search'] = opts['search']
return result
def _parse_routes(iface, opts):
'''
Filters given options and outputs valid settings for
the route settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
result = {}
if 'routes' not in opts:
_raise_error_routes(iface, 'routes', 'List of routes')
for opt in opts:
result[opt] = opts[opt]
return result
def _write_file(iface, data, folder, pattern):
'''
Writes a file to disk
'''
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
return filename
def _write_file_routes(iface, data, folder, pattern):
'''
Writes a file to disk
'''
# ifup / ifdown is executing given folder via run-parts.
# according to run-parts man-page, only filenames with this pattern are
# executed: (^[a-zA-Z0-9_-]+$)
# In order to make the routes file work for vlan interfaces
# (default would have been in example /etc/network/if-up.d/route-bond0.12)
# these dots in the iface name need to be replaced by underscores, so it
# can be executed by run-parts
iface = iface.replace('.', '_')
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
__salt__['file.set_mode'](filename, '0755')
return filename
def _write_file_network(data, filename, create=False):
'''
Writes a file to disk
If file does not exist, only create if create
argument is True
'''
if not os.path.exists(filename) and not create:
msg = '{0} cannot be written. {0} does not exist\
and create is set to False'
msg = msg.format(filename)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
def _read_temp(data):
'''
Return what would be written to disk
'''
tout = StringIO()
tout.write(data)
tout.seek(0)
output = tout.readlines()
tout.close()
return output
def _read_temp_ifaces(iface, data):
'''
Return what would be written to disk for interfaces
'''
try:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': data})
# Return as an array so the difflib works
return [item + '\n' for item in ifcfg.split('\n')]
def _write_file_ifaces(iface, data, **settings):
'''
Writes a file to disk
'''
try:
eth_template = JINJA.get_template('debian_eth.jinja')
source_template = JINJA.get_template('debian_source.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
# Read /etc/network/interfaces into a dict
adapters = _parse_interfaces()
# Apply supplied settings over on-disk settings
adapters[iface] = data
ifcfg = ''
for adapter in adapters:
if 'type' in adapters[adapter] and adapters[adapter]['type'] == 'source':
tmp = source_template.render({'name': adapter, 'data': adapters[adapter]})
else:
tmp = eth_template.render({'name': adapter, 'data': adapters[adapter]})
ifcfg = ifcfg + tmp
if adapter == iface:
saved_ifcfg = tmp
_SEPARATE_FILE = False
if 'filename' in settings:
if not settings['filename'].startswith('/'):
filename = '{0}/{1}'.format(_DEB_NETWORK_DIR, settings['filename'])
else:
filename = settings['filename']
_SEPARATE_FILE = True
else:
if 'filename' in adapters[adapter]['data']:
filename = adapters[adapter]['data']
else:
filename = _DEB_NETWORK_FILE
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
if _SEPARATE_FILE:
fout.write(salt.utils.stringutils.to_str(saved_ifcfg))
else:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return saved_ifcfg.split('\n')
def _write_file_ppp_ifaces(iface, data):
'''
Writes a file to disk
'''
try:
template = JINJA.get_template('debian_ppp_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_ppp_eth.jinja')
return ''
adapters = _parse_interfaces()
adapters[iface] = data
ifcfg = ''
tmp = template.render({'data': adapters[iface]})
ifcfg = tmp + ifcfg
filename = _DEB_PPP_DIR + '/' + adapters[iface]['data']['inet']['provider']
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.fopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return filename
def build_bond(iface, **settings):
'''
Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb
'''
deb_major = __grains__['osrelease'][:1]
opts = _parse_settings_bond(settings, iface)
try:
template = JINJA.get_template('conf.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template conf.jinja')
return ''
data = template.render({'name': iface, 'bonding': opts})
if 'test' in settings and settings['test']:
return _read_temp(data)
_write_file(iface, data, _DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
if deb_major == '5':
for line_type in ('alias', 'options'):
cmd = ['sed', '-i', '-e', r'/^{0}\s{1}.*/d'.format(line_type, iface),
'/etc/modprobe.conf']
__salt__['cmd.run'](cmd, python_shell=False)
__salt__['file.append']('/etc/modprobe.conf', path)
# Load kernel module
__salt__['kmod.load']('bonding')
# install ifenslave-2.6
__salt__['pkg.install']('ifenslave-2.6')
return _read_file(path)
def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'vlan':
settings['vlan'] = 'yes'
__salt__['pkg.install']('vlan')
elif iface_type == 'pppoe':
settings['pppoe'] = 'yes'
if not __salt__['pkg.version']('ppp'):
inst = __salt__['pkg.install']('ppp')
elif iface_type == 'bond':
if 'slaves' not in settings:
msg = 'slaves is a required setting for bond interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'bridge':
if 'ports' not in settings:
msg = (
'ports is a required setting for bridge interfaces on Debian '
'or Ubuntu based systems'
)
log.error(msg)
raise AttributeError(msg)
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'pppoe']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
if iface_type in ['source']:
opts = _parse_settings_source(settings, iface_type, enabled, iface)
if 'test' in settings and settings['test']:
return _read_temp_ifaces(iface, opts[iface])
ifcfg = _write_file_ifaces(iface, opts[iface], **settings)
if iface_type == 'pppoe':
_write_file_ppp_ifaces(iface, opts[iface])
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg]
def build_routes(iface, **settings):
'''
Add route scripts for a network interface using up commands.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
'''
opts = _parse_routes(iface, settings)
try:
template = JINJA.get_template('route_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template route_eth.jinja')
return ''
add_routecfg = template.render(route_type='add',
routes=opts['routes'],
iface=iface)
del_routecfg = template.render(route_type='del',
routes=opts['routes'],
iface=iface)
if 'test' in settings and settings['test']:
return _read_temp(add_routecfg + del_routecfg)
filename = _write_file_routes(iface,
add_routecfg,
_DEB_NETWORK_UP_DIR,
'route-{0}')
results = _read_file(filename)
filename = _write_file_routes(iface,
del_routecfg,
_DEB_NETWORK_DOWN_DIR,
'route-{0}')
results += _read_file(filename)
return results
def down(iface, iface_type):
'''
Shutdown a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.down eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought down.
if iface_type not in ['slave', 'source']:
return __salt__['cmd.run'](['ifdown', iface])
return None
def get_bond(iface):
'''
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
'''
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
return _read_file(path)
def get_interface(iface):
'''
Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
adapters = _parse_interfaces()
if iface in adapters:
try:
if iface == 'source':
template = JINJA.get_template('debian_source.jinja')
else:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': adapters[iface]})
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg.split('\n')]
else:
return []
def up(iface, iface_type): # pylint: disable=C0103
'''
Start up a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.up eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought up.
if iface_type not in ('slave', 'source'):
return __salt__['cmd.run'](['ifup', iface])
return None
def get_network_settings():
'''
Return the contents of the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_network_settings
'''
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
settings = {}
if __salt__['service.available']('networking'):
if __salt__['service.status']('networking'):
settings['networking'] = "yes"
else:
settings['networking'] = "no"
else:
settings['networking'] = "no"
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
settings['hostname'] = hostname
settings['domainname'] = domainname
settings['searchdomain'] = searchdomain
else:
settings = _parse_current_network_settings()
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(settings)
return _read_temp(network)
def get_routes(iface):
'''
Return the routes for the interface
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0
'''
filename = os.path.join(_DEB_NETWORK_UP_DIR, 'route-{0}'.format(iface))
results = _read_file(filename)
filename = os.path.join(_DEB_NETWORK_DOWN_DIR, 'route-{0}'.format(iface))
results += _read_file(filename)
return results
def apply_network_settings(**settings):
'''
Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings
'''
if 'require_reboot' not in settings:
settings['require_reboot'] = False
if 'apply_hostname' not in settings:
settings['apply_hostname'] = False
hostname_res = True
if settings['apply_hostname'] in _CONFIG_TRUE:
if 'hostname' in settings:
hostname_res = __salt__['network.mod_hostname'](settings['hostname'])
else:
log.warning(
'The network state sls is trying to apply hostname '
'changes but no hostname is defined.'
)
hostname_res = False
res = True
if settings['require_reboot'] in _CONFIG_TRUE:
log.warning(
'The network state sls is requiring a reboot of the system to '
'properly apply network configuration.'
)
res = True
else:
stop = __salt__['service.stop']('networking')
time.sleep(2)
res = stop and __salt__['service.start']('networking')
return hostname_res and res
def build_network_settings(**settings):
'''
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
'''
changes = []
# Read current configuration and store default values
current_network_settings = _parse_current_network_settings()
# Build settings
opts = _parse_network_settings(settings, current_network_settings)
# Ubuntu has moved away from /etc/default/networking
# beginning with the 12.04 release so we disable or enable
# the networking related services on boot
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
if opts['networking'] == 'yes':
service_cmd = 'service.enable'
else:
service_cmd = 'service.disable'
if __salt__['service.available']('NetworkManager'):
__salt__[service_cmd]('NetworkManager')
if __salt__['service.available']('networking'):
__salt__[service_cmd]('networking')
else:
try:
template = JINJA.get_template('network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template network.jinja')
return ''
network = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(network)
# Write settings
_write_file_network(network, _DEB_NETWORKING_FILE, True)
# Get hostname and domain from opts
sline = opts['hostname'].split('.', 1)
opts['hostname'] = sline[0]
current_domainname = current_network_settings['domainname']
current_searchdomain = current_network_settings['searchdomain']
new_domain = False
if len(sline) > 1:
new_domainname = sline[1]
if new_domainname != current_domainname:
domainname = new_domainname
opts['domainname'] = new_domainname
new_domain = True
else:
domainname = current_domainname
opts['domainname'] = domainname
else:
domainname = current_domainname
opts['domainname'] = domainname
new_search = False
if 'search' in opts:
new_searchdomain = opts['search']
if new_searchdomain != current_searchdomain:
searchdomain = new_searchdomain
opts['searchdomain'] = new_searchdomain
new_search = True
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
# If the domain changes, then we should write the resolv.conf file.
if new_domain or new_search:
# Look for existing domain line and update if necessary
resolve = _parse_resolve()
domain_prog = re.compile(r'domain\s+')
search_prog = re.compile(r'search\s+')
new_contents = []
for item in _read_file(_DEB_RESOLV_FILE):
if domain_prog.match(item):
item = 'domain {0}'.format(domainname)
elif search_prog.match(item):
item = 'search {0}'.format(searchdomain)
new_contents.append(item)
# A domain line didn't exist so we'll add one in
# with the new domainname
if 'domain' not in resolve:
new_contents.insert(0, 'domain {0}' . format(domainname))
# A search line didn't exist so we'll add one in
# with the new search domain
if 'search' not in resolve:
new_contents.insert('domain' in resolve, 'search {0}'.format(searchdomain))
new_resolv = '\n'.join(new_contents)
# Write /etc/resolv.conf
if not ('test' in settings and settings['test']):
_write_file_network(new_resolv, _DEB_RESOLV_FILE)
# used for returning the results back
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(opts)
changes.extend(_read_temp(network))
return changes
|
saltstack/salt
|
salt/modules/debian_ip.py
|
__within2
|
python
|
def __within2(value, within=None, errmsg=None, dtype=None):
'''validate that a value is in ``within`` and optionally a ``dtype``'''
valid, _value = False, value
if dtype:
try:
_value = dtype(value) # TODO: this is a bit loose when dtype is a class
valid = _value in within
except ValueError:
pass
else:
valid = _value in within
if errmsg is None:
if dtype:
typename = getattr(dtype, '__name__',
hasattr(dtype, '__class__')
and getattr(dtype.__class__, 'name', dtype))
errmsg = '{0} within \'{1}\''.format(typename, within)
else:
errmsg = 'within \'{0}\''.format(within)
return (valid, _value, errmsg)
|
validate that a value is in ``within`` and optionally a ``dtype``
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_ip.py#L354-L373
| null |
# -*- coding: utf-8 -*-
'''
The networking module for Debian-based distros
References:
* http://www.debian.org/doc/manuals/debian-reference/ch05.en.html
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import functools
import logging
import os.path
import os
import re
import time
# Import third party libs
import jinja2
import jinja2.exceptions
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error,no-name-in-module
# Import salt libs
import salt.utils.dns
import salt.utils.files
import salt.utils.odict
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.validate.net
# Set up logging
log = logging.getLogger(__name__)
# Set up template environment
JINJA = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'debian_ip')
)
)
# Define the module's virtual name
__virtualname__ = 'ip'
def __virtual__():
'''
Confine this module to Debian-based distros
'''
if __grains__['os_family'] == 'Debian':
return __virtualname__
return (False, 'The debian_ip module could not be loaded: '
'unsupported OS family')
_ETHTOOL_CONFIG_OPTS = {
'speed': 'link-speed',
'duplex': 'link-duplex',
'autoneg': 'ethernet-autoneg',
'ethernet-port': 'ethernet-port',
'wol': 'ethernet-wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'rx': 'offload-rx',
'tx': 'offload-tx',
'sg': 'offload-sg',
'tso': 'offload-tso',
'ufo': 'offload-ufo',
'gso': 'offload-gso',
'gro': 'offload-gro',
'lro': 'offload-lro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_REV_ETHTOOL_CONFIG_OPTS = {
'link-speed': 'speed',
'link-duplex': 'duplex',
'ethernet-autoneg': 'autoneg',
'ethernet-port': 'ethernet-port',
'ethernet-wol': 'wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'offload-rx': 'rx',
'offload-tx': 'tx',
'offload-sg': 'sg',
'offload-tso': 'tso',
'offload-ufo': 'ufo',
'offload-gso': 'gso',
'offload-lro': 'lro',
'offload-gro': 'gro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_DEB_CONFIG_PPPOE_OPTS = {
'user': 'user',
'password': 'password',
'provider': 'provider',
'pppoe_iface': 'pppoe_iface',
'noipdefault': 'noipdefault',
'usepeerdns': 'usepeerdns',
'defaultroute': 'defaultroute',
'holdoff': 'holdoff',
'maxfail': 'maxfail',
'hide-password': 'hide-password',
'lcp-echo-interval': 'lcp-echo-interval',
'lcp-echo-failure': 'lcp-echo-failure',
'connect': 'connect',
'noauth': 'noauth',
'persist': 'persist',
'mtu': 'mtu',
'noaccomp': 'noaccomp',
'linkname': 'linkname',
}
_DEB_ROUTES_FILE = '/etc/network/routes'
_DEB_NETWORK_FILE = '/etc/network/interfaces'
_DEB_NETWORK_DIR = '/etc/network/interfaces.d/'
_DEB_NETWORK_UP_DIR = '/etc/network/if-up.d/'
_DEB_NETWORK_DOWN_DIR = '/etc/network/if-down.d/'
_DEB_NETWORK_CONF_FILES = '/etc/modprobe.d/'
_DEB_NETWORKING_FILE = '/etc/default/networking'
_DEB_HOSTNAME_FILE = '/etc/hostname'
_DEB_RESOLV_FILE = '/etc/resolv.conf'
_DEB_PPP_DIR = '/etc/ppp/peers/'
_CONFIG_TRUE = ['yes', 'on', 'true', '1', True]
_CONFIG_FALSE = ['no', 'off', 'false', '0', False]
_IFACE_TYPES = [
'eth', 'bond', 'alias', 'clone',
'ipsec', 'dialup', 'bridge', 'slave',
'vlan', 'pppoe', 'source',
]
def _error_msg_iface(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, '|'.join(str(e) for e in expected))
def _error_msg_routes(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, expected)
def _log_default_iface(iface, opt, value):
log.info(
'Using default option -- Interface: %s Option: %s Value: %s',
iface, opt, value
)
def _error_msg_network(option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]'
return msg.format(option, '|'.join(str(e) for e in expected))
def _log_default_network(opt, value):
log.info('Using existing setting -- Setting: %s Value: %s', opt, value)
def _raise_error_iface(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_iface(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_network(option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_network(option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_routes(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_routes(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _read_file(path):
'''
Reads and returns the contents of a text file
'''
try:
with salt.utils.files.flopen(path, 'rb') as contents:
return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]
except (OSError, IOError):
return ''
def _parse_resolve():
'''
Parse /etc/resolv.conf
'''
return salt.utils.dns.parse_resolv(_DEB_RESOLV_FILE)
def _parse_domainname():
'''
Parse /etc/resolv.conf and return domainname
'''
return _parse_resolve().get('domain', '')
def _parse_searchdomain():
'''
Parse /etc/resolv.conf and return searchdomain
'''
return _parse_resolve().get('search', '')
def _parse_hostname():
'''
Parse /etc/hostname and return hostname
'''
contents = _read_file(_DEB_HOSTNAME_FILE)
if contents:
return contents[0].split('\n')[0]
else:
return ''
def _parse_current_network_settings():
'''
Parse /etc/default/networking and return current configuration
'''
opts = salt.utils.odict.OrderedDict()
opts['networking'] = ''
if os.path.isfile(_DEB_NETWORKING_FILE):
with salt.utils.files.fopen(_DEB_NETWORKING_FILE) as contents:
for line in contents:
salt.utils.stringutils.to_unicode(line)
if line.startswith('#'):
continue
elif line.startswith('CONFIGURE_INTERFACES'):
opts['networking'] = line.split('=', 1)[1].strip()
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
opts['hostname'] = hostname
opts['domainname'] = domainname
opts['searchdomain'] = searchdomain
return opts
# def __validator_func(value):
# return (valid: True/False, (transformed) value, error message)
def __ipv4_quad(value):
'''validate an IPv4 address'''
return (salt.utils.validate.net.ipv4_addr(value), value,
'dotted IPv4 address')
def __ipv6(value):
'''validate an IPv6 address'''
return (salt.utils.validate.net.ipv6_addr(value), value,
'IPv6 address')
def __mac(value):
'''validate a mac address'''
return (salt.utils.validate.net.mac(value), value,
'MAC address')
def __anything(value):
return (True, value, None)
def __int(value):
'''validate an integer'''
valid, _value = False, value
try:
_value = int(value)
valid = True
except ValueError:
pass
return (valid, _value, 'integer')
def __float(value):
'''validate a float'''
valid, _value = False, value
try:
_value = float(value)
valid = True
except ValueError:
pass
return (valid, _value, 'float')
def __ipv4_netmask(value):
'''validate an IPv4 dotted quad or integer CIDR netmask'''
valid, errmsg = False, 'dotted quad or integer CIDR (0->32)'
valid, value, _ = __int(value)
if not (valid and 0 <= value <= 32):
valid = salt.utils.validate.net.netmask(value)
return (valid, value, errmsg)
def __ipv6_netmask(value):
'''validate an IPv6 integer netmask'''
valid, errmsg = False, 'IPv6 netmask (0->128)'
valid, value, _ = __int(value)
valid = (valid and 0 <= value <= 128)
return (valid, value, errmsg)
def __within(within=None, errmsg=None, dtype=None):
return functools.partial(__within2, within=within,
errmsg=errmsg, dtype=dtype)
def __space_delimited_list(value):
'''validate that a value contains one or more space-delimited values'''
if isinstance(value, six.string_types):
value = value.strip().split()
if hasattr(value, '__iter__') and value != []:
return (True, value, 'space-delimited string')
else:
return (False, value, '{0} is not a valid space-delimited value.\n'.format(value))
SALT_ATTR_TO_DEBIAN_ATTR_MAP = {
'dns': 'dns-nameservers',
'search': 'dns-search',
'hwaddr': 'hwaddress', # TODO: this limits bootp functionality
'ipaddr': 'address',
'ipaddrs': 'addresses',
}
DEBIAN_ATTR_TO_SALT_ATTR_MAP = dict(
(v, k) for (k, v) in six.iteritems(SALT_ATTR_TO_DEBIAN_ATTR_MAP))
# TODO
DEBIAN_ATTR_TO_SALT_ATTR_MAP['address'] = 'address'
DEBIAN_ATTR_TO_SALT_ATTR_MAP['hwaddress'] = 'hwaddress'
IPV4_VALID_PROTO = ['bootp', 'dhcp', 'static', 'manual', 'loopback', 'ppp']
IPV4_ATTR_MAP = {
'proto': __within(IPV4_VALID_PROTO, dtype=six.text_type),
# ipv4 static & manual
'address': __ipv4_quad,
'addresses': __anything,
'netmask': __ipv4_netmask,
'broadcast': __ipv4_quad,
'metric': __int,
'gateway': __ipv4_quad, # supports a colon-delimited list
'pointopoint': __ipv4_quad,
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'link', 'host'], dtype=six.text_type),
# dhcp
'hostname': __anything,
'leasehours': __int,
'leasetime': __int,
'vendor': __anything,
'client': __anything,
# bootp
'bootfile': __anything,
'server': __ipv4_quad,
'hwaddr': __mac,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'dstaddr': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# bond
'slaves': __anything,
# ppp
'provider': __anything,
'unit': __int,
'options': __anything,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
#
'network': __anything, # i don't know what this is
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
IPV6_VALID_PROTO = ['auto', 'loopback', 'static', 'manual',
'dhcp', 'v4tunnel', '6to4']
IPV6_ATTR_MAP = {
'proto': __within(IPV6_VALID_PROTO),
# ipv6 static & manual
'address': __ipv6,
'addresses': __anything,
'netmask': __ipv6_netmask,
'broadcast': __ipv6,
'gateway': __ipv6, # supports a colon-delimited list
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'site', 'link', 'host'], dtype=six.text_type),
# inet6 auto
'privext': __within([0, 1, 2], dtype=int),
'dhcp': __within([0, 1], dtype=int),
# inet6 static & manual & dhcp
'media': __anything,
'accept_ra': __within([0, 1], dtype=int),
'autoconf': __within([0, 1], dtype=int),
'preferred-lifetime': __int,
'dad-attempts': __int, # 0 to disable
'dad-interval': __float,
# bond
'slaves': __anything,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
WIRELESS_ATTR_MAP = {
'wireless-essid': __anything,
'wireless-mode': __anything, # TODO
'wpa-ap-scan': __within([0, 1, 2], dtype=int), # TODO
'wpa-conf': __anything,
'wpa-driver': __anything,
'wpa-group': __anything,
'wpa-key-mgmt': __anything,
'wpa-pairwise': __anything,
'wpa-psk': __anything,
'wpa-proto': __anything, # partial(__within,
'wpa-roam': __anything,
'wpa-ssid': __anything, # TODO
}
ATTRMAPS = {
'inet': [IPV4_ATTR_MAP, WIRELESS_ATTR_MAP],
'inet6': [IPV6_ATTR_MAP, WIRELESS_ATTR_MAP]
}
def _validate_interface_option(attr, value, addrfam='inet'):
'''lookup the validation function for a [addrfam][attr] and
return the results
:param attr: attribute name
:param value: raw setting value
:param addrfam: address family (inet, inet6,
'''
valid, _value, errmsg = False, value, 'Unknown validator'
attrmaps = ATTRMAPS.get(addrfam, [])
for attrmap in attrmaps:
if attr in attrmap:
validate_func = attrmap[attr]
(valid, _value, errmsg) = validate_func(value)
break
return (valid, _value, errmsg)
def _attrmaps_contain_attr(attr):
return (
attr in WIRELESS_ATTR_MAP or
attr in IPV4_ATTR_MAP or
attr in IPV6_ATTR_MAP)
def _parse_interfaces(interface_files=None):
'''
Parse /etc/network/interfaces and return current configured interfaces
'''
if interface_files is None:
interface_files = []
# Add this later.
if os.path.exists(_DEB_NETWORK_DIR):
interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]
if os.path.isfile(_DEB_NETWORK_FILE):
interface_files.insert(0, _DEB_NETWORK_FILE)
adapters = salt.utils.odict.OrderedDict()
method = -1
for interface_file in interface_files:
with salt.utils.files.fopen(interface_file) as interfaces:
# This ensures iface_dict exists, but does not ensure we're not reading a new interface.
iface_dict = {}
for line in interfaces:
line = salt.utils.stringutils.to_unicode(line)
# Identify the clauses by the first word of each line.
# Go to the next line if the current line is a comment
# or all spaces.
if line.lstrip().startswith('#') or line.isspace():
continue
# Parse the iface clause
if line.startswith('iface'):
sline = line.split()
if len(sline) != 4:
msg = 'Interface file malformed: {0}.'
msg = msg.format(sline)
log.error(msg)
raise AttributeError(msg)
iface_name = sline[1]
addrfam = sline[2]
method = sline[3]
# Create item in dict, if not already there
if iface_name not in adapters:
adapters[iface_name] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters[iface_name]:
adapters[iface_name]['data'] = salt.utils.odict.OrderedDict()
if addrfam not in adapters[iface_name]['data']:
adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict()
iface_dict = adapters[iface_name]['data'][addrfam]
iface_dict['addrfam'] = addrfam
iface_dict['proto'] = method
iface_dict['filename'] = interface_file
# Parse the detail clauses.
elif line[0].isspace():
sline = line.split()
# conf file attr: dns-nameservers
# salt states.network attr: dns
attr, valuestr = line.rstrip().split(None, 1)
if _attrmaps_contain_attr(attr):
if '-' in attr:
attrname = attr.replace('-', '_')
else:
attrname = attr
(valid, value, errmsg) = _validate_interface_option(
attr, valuestr, addrfam)
if attrname == 'address' and 'address' in iface_dict:
if 'addresses' not in iface_dict:
iface_dict['addresses'] = []
iface_dict['addresses'].append(value)
else:
iface_dict[attrname] = value
elif attr in _REV_ETHTOOL_CONFIG_OPTS:
if 'ethtool' not in iface_dict:
iface_dict['ethtool'] = salt.utils.odict.OrderedDict()
iface_dict['ethtool'][attr] = valuestr
elif attr.startswith('bond'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bonding' not in iface_dict:
iface_dict['bonding'] = salt.utils.odict.OrderedDict()
iface_dict['bonding'][opt] = valuestr
elif attr.startswith('bridge'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bridging' not in iface_dict:
iface_dict['bridging'] = salt.utils.odict.OrderedDict()
iface_dict['bridging'][opt] = valuestr
elif attr in ['up', 'pre-up', 'post-up',
'down', 'pre-down', 'post-down']:
cmd = valuestr
cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr))
if cmd_key not in iface_dict:
iface_dict[cmd_key] = []
iface_dict[cmd_key].append(cmd)
elif line.startswith('auto'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['enabled'] = True
elif line.startswith('allow-hotplug'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['hotplug'] = True
elif line.startswith('source'):
if 'source' not in adapters:
adapters['source'] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters['source']:
adapters['source']['data'] = salt.utils.odict.OrderedDict()
adapters['source']['data']['sources'] = []
adapters['source']['data']['sources'].append(line.split()[1])
# Return a sorted list of the keys for bond, bridge and ethtool options to
# ensure a consistent order
for iface_name in adapters:
if iface_name == 'source':
continue
if 'data' not in adapters[iface_name]:
msg = 'Interface file malformed for interface: {0}.'.format(iface_name)
log.error(msg)
adapters.pop(iface_name)
continue
for opt in ['ethtool', 'bonding', 'bridging']:
for inet in ['inet', 'inet6']:
if inet in adapters[iface_name]['data']:
if opt in adapters[iface_name]['data'][inet]:
opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys())
adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys
return adapters
def _parse_ethtool_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
if 'autoneg' in opts:
if opts['autoneg'] in _CONFIG_TRUE:
config.update({'autoneg': 'on'})
elif opts['autoneg'] in _CONFIG_FALSE:
config.update({'autoneg': 'off'})
else:
_raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE)
if 'duplex' in opts:
valid = ['full', 'half']
if opts['duplex'] in valid:
config.update({'duplex': opts['duplex']})
else:
_raise_error_iface(iface, 'duplex', valid)
if 'speed' in opts:
valid = ['10', '100', '1000', '10000']
if six.text_type(opts['speed']) in valid:
config.update({'speed': opts['speed']})
else:
_raise_error_iface(iface, opts['speed'], valid)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'on'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'off'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_ethtool_pppoe_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
for opt in _DEB_CONFIG_PPPOE_OPTS:
if opt in opts:
config[opt] = opts[opt]
if 'provider' in opts and not opts['provider']:
_raise_error_iface(iface, 'provider', _CONFIG_TRUE + _CONFIG_FALSE)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('noipdefault', 'usepeerdns', 'defaultroute', 'hide-password', 'noauth', 'persist', 'noaccomp'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'True'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'False'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_settings_bond(opts, iface):
'''
Filters given options and outputs valid settings for requested
operation. If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond_def = {
# 803.ad aggregation selection logic
# 0 for stable (default)
# 1 for bandwidth
# 2 for count
'ad_select': '0',
# Max number of transmit queues (default = 16)
'tx_queues': '16',
# Link monitoring in milliseconds. Most NICs support this
'miimon': '100',
# ARP interval in milliseconds
'arp_interval': '250',
# Delay before considering link down in milliseconds (miimon * 2)
'downdelay': '200',
# lacp_rate 0: Slow - every 30 seconds
# lacp_rate 1: Fast - every 1 second
'lacp_rate': '0',
# Max bonds for this driver
'max_bonds': '1',
# Specifies the time, in milliseconds, to wait before
# enabling a slave after a link recovery has been
# detected. Only used with miimon.
'updelay': '0',
# Used with miimon.
# On: driver sends mii
# Off: ethtool sends mii
'use_carrier': 'on',
# Default. Don't change unless you know what you are doing.
'xmit_hash_policy': 'layer2',
}
if opts['mode'] in ['balance-rr', '0']:
log.info('Device: %s Bonding Mode: load balancing (round-robin)', iface)
return _parse_settings_bond_0(opts, iface, bond_def)
elif opts['mode'] in ['active-backup', '1']:
log.info('Device: %s Bonding Mode: fault-tolerance (active-backup)', iface)
return _parse_settings_bond_1(opts, iface, bond_def)
elif opts['mode'] in ['balance-xor', '2']:
log.info('Device: %s Bonding Mode: load balancing (xor)', iface)
return _parse_settings_bond_2(opts, iface, bond_def)
elif opts['mode'] in ['broadcast', '3']:
log.info('Device: %s Bonding Mode: fault-tolerance (broadcast)', iface)
return _parse_settings_bond_3(opts, iface, bond_def)
elif opts['mode'] in ['802.3ad', '4']:
log.info('Device: %s Bonding Mode: IEEE 802.3ad Dynamic link '
'aggregation', iface)
return _parse_settings_bond_4(opts, iface, bond_def)
elif opts['mode'] in ['balance-tlb', '5']:
log.info('Device: %s Bonding Mode: transmit load balancing', iface)
return _parse_settings_bond_5(opts, iface, bond_def)
elif opts['mode'] in ['balance-alb', '6']:
log.info('Device: %s Bonding Mode: adaptive load balancing', iface)
return _parse_settings_bond_6(opts, iface, bond_def)
else:
valid = [
'0', '1', '2', '3', '4', '5', '6',
'balance-rr', 'active-backup', 'balance-xor',
'broadcast', '802.3ad', 'balance-tlb', 'balance-alb'
]
_raise_error_iface(iface, 'mode', valid)
def _parse_settings_bond_0(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond0.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '0'}
# ARP targets in n.n.n.n form
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
return bond
def _parse_settings_bond_1(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '1'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
if not (__grains__['os'] == "Ubuntu" and __grains__['osrelease_info'][0] >= 16):
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_2(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond2.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '2'}
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_3(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond3.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '3'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_4(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond4.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '4'}
for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']:
if binding in opts:
if binding == 'lacp_rate':
if opts[binding] == 'fast':
opts.update({binding: '1'})
if opts[binding] == 'slow':
opts.update({binding: '0'})
valid = ['fast', '1', 'slow', '0']
else:
valid = ['integer']
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, valid)
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_5(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond5.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '5'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_settings_bond_6(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond6.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '6'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_bridge_opts(opts, iface):
'''
Filters given options and outputs valid settings for BRIDGING_OPTS
If an option has a value that is not expected, this
function will log the Interface, Setting and what was expected.
'''
config = {}
if 'ports' in opts:
if isinstance(opts['ports'], list):
opts['ports'] = ' '.join(opts['ports'])
config.update({'ports': opts['ports']})
for opt in ['ageing', 'fd', 'gcint', 'hello', 'maxage']:
if opt in opts:
try:
float(opts[opt])
config.update({opt: opts[opt]})
except ValueError:
_raise_error_iface(iface, opt, ['float'])
for opt in ['bridgeprio', 'maxwait']:
if opt in opts:
if isinstance(opts[opt], int):
config.update({opt: opts[opt]})
else:
_raise_error_iface(iface, opt, ['integer'])
if 'hw' in opts:
# match 12 hex digits with either : or - as separators between pairs
if re.match('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$',
opts['hw'].lower()):
config.update({'hw': opts['hw']})
else:
_raise_error_iface(iface, 'hw', ['valid MAC address'])
for opt in ['pathcost', 'portprio']:
if opt in opts:
try:
port, cost_or_prio = opts[opt].split()
int(cost_or_prio)
config.update({opt: '{0} {1}'.format(port, cost_or_prio)})
except ValueError:
_raise_error_iface(iface, opt, ['interface integer'])
if 'stp' in opts:
if opts['stp'] in _CONFIG_TRUE:
config.update({'stp': 'on'})
elif opts['stp'] in _CONFIG_FALSE:
config.update({'stp': 'off'})
else:
_raise_error_iface(iface, 'stp', _CONFIG_TRUE + _CONFIG_FALSE)
if 'waitport' in opts:
if isinstance(opts['waitport'], int):
config.update({'waitport': opts['waitport']})
else:
values = opts['waitport'].split()
waitport_time = values.pop(0)
if waitport_time.isdigit() and values:
config.update({
'waitport': '{0} {1}'.format(
waitport_time, ' '.join(values)
)
})
else:
_raise_error_iface(iface, opt, ['integer [interfaces]'])
return config
def _parse_settings_eth(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['inet'] = salt.utils.odict.OrderedDict()
iface_data['inet6'] = salt.utils.odict.OrderedDict()
if enabled:
adapters[iface]['enabled'] = True
if opts.get('hotplug', False):
adapters[iface]['hotplug'] = True
if opts.get('enable_ipv6', None) and opts.get('iface_type', '') == 'vlan':
iface_data['inet6']['vlan_raw_device'] = (
re.sub(r'\.\d*', '', iface))
for addrfam in ['inet', 'inet6']:
if iface_type not in ['bridge']:
tmp_ethtool = _parse_ethtool_opts(opts, iface)
if tmp_ethtool:
ethtool = {}
for item in tmp_ethtool:
ethtool[_ETHTOOL_CONFIG_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['ethtool'] = ethtool
# return a list of sorted keys to ensure consistent order
iface_data[addrfam]['ethtool_keys'] = sorted(ethtool)
if iface_type == 'bridge':
bridging = _parse_bridge_opts(opts, iface)
if bridging:
iface_data[addrfam]['bridging'] = bridging
iface_data[addrfam]['bridging_keys'] = sorted(bridging)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'bond':
bonding = _parse_settings_bond(opts, iface)
if bonding:
iface_data[addrfam]['bonding'] = bonding
iface_data[addrfam]['bonding']['slaves'] = opts['slaves']
iface_data[addrfam]['bonding_keys'] = sorted(bonding)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'slave':
adapters[iface]['master'] = opts['master']
opts['proto'] = 'manual'
iface_data[addrfam]['master'] = adapters[iface]['master']
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'vlan':
iface_data[addrfam]['vlan_raw_device'] = re.sub(r'\.\d*', '', iface)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'pppoe':
tmp_ethtool = _parse_ethtool_pppoe_opts(opts, iface)
if tmp_ethtool:
for item in tmp_ethtool:
adapters[iface]['data'][addrfam][_DEB_CONFIG_PPPOE_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['addrfam'] = addrfam
opts.pop('mode', None)
for opt, val in opts.items():
inet = None
if opt.startswith('ipv4'):
opt = opt[4:]
inet = 'inet'
iface_data['inet']['addrfam'] = 'inet'
elif opt.startswith('ipv6'):
iface_data['inet6']['addrfam'] = 'inet6'
opt = opt[4:]
inet = 'inet6'
elif opt in ['ipaddr', 'address', 'ipaddresses', 'addresses', 'gateway', 'proto']:
iface_data['inet']['addrfam'] = 'inet'
inet = 'inet'
_opt = SALT_ATTR_TO_DEBIAN_ATTR_MAP.get(opt, opt)
_debopt = _opt.replace('-', '_')
for addrfam in ['inet', 'inet6']:
(valid, value, errmsg) = _validate_interface_option(_opt, val, addrfam=addrfam)
if not valid:
continue
if inet is None and _debopt not in iface_data[addrfam]:
iface_data[addrfam][_debopt] = value
elif inet == addrfam:
iface_data[addrfam][_debopt] = value
for opt in ['up_cmds', 'pre_up_cmds', 'post_up_cmds',
'down_cmds', 'pre_down_cmds', 'post_down_cmds']:
if opt in opts:
iface_data['inet'][opt] = opts[opt]
iface_data['inet6'][opt] = opts[opt]
# Remove incomplete/disabled inet blocks
for (addrfam, opt) in [('inet', 'enable_ipv4'), ('inet6', 'enable_ipv6')]:
if opts.get(opt, None) is False:
iface_data.pop(addrfam)
elif iface_data[addrfam].get('addrfam', '') != addrfam:
iface_data.pop(addrfam)
return adapters
def _parse_settings_source(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['sources'] = [opts['source']]
return adapters
def _parse_network_settings(opts, current):
'''
Filters given options and outputs valid settings for
the global network settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
current = dict((k.lower(), v) for (k, v) in six.iteritems(current))
result = {}
valid = _CONFIG_TRUE + _CONFIG_FALSE
if 'enabled' not in opts:
try:
opts['networking'] = current['networking']
_log_default_network('networking', current['networking'])
except ValueError:
_raise_error_network('networking', valid)
else:
opts['networking'] = opts['enabled']
if opts['networking'] in valid:
if opts['networking'] in _CONFIG_TRUE:
result['networking'] = 'yes'
elif opts['networking'] in _CONFIG_FALSE:
result['networking'] = 'no'
else:
_raise_error_network('networking', valid)
if 'hostname' not in opts:
try:
opts['hostname'] = current['hostname']
_log_default_network('hostname', current['hostname'])
except ValueError:
_raise_error_network('hostname', ['server1.example.com'])
if opts['hostname']:
result['hostname'] = opts['hostname']
else:
_raise_error_network('hostname', ['server1.example.com'])
if 'search' in opts:
result['search'] = opts['search']
return result
def _parse_routes(iface, opts):
'''
Filters given options and outputs valid settings for
the route settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
result = {}
if 'routes' not in opts:
_raise_error_routes(iface, 'routes', 'List of routes')
for opt in opts:
result[opt] = opts[opt]
return result
def _write_file(iface, data, folder, pattern):
'''
Writes a file to disk
'''
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
return filename
def _write_file_routes(iface, data, folder, pattern):
'''
Writes a file to disk
'''
# ifup / ifdown is executing given folder via run-parts.
# according to run-parts man-page, only filenames with this pattern are
# executed: (^[a-zA-Z0-9_-]+$)
# In order to make the routes file work for vlan interfaces
# (default would have been in example /etc/network/if-up.d/route-bond0.12)
# these dots in the iface name need to be replaced by underscores, so it
# can be executed by run-parts
iface = iface.replace('.', '_')
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
__salt__['file.set_mode'](filename, '0755')
return filename
def _write_file_network(data, filename, create=False):
'''
Writes a file to disk
If file does not exist, only create if create
argument is True
'''
if not os.path.exists(filename) and not create:
msg = '{0} cannot be written. {0} does not exist\
and create is set to False'
msg = msg.format(filename)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
def _read_temp(data):
'''
Return what would be written to disk
'''
tout = StringIO()
tout.write(data)
tout.seek(0)
output = tout.readlines()
tout.close()
return output
def _read_temp_ifaces(iface, data):
'''
Return what would be written to disk for interfaces
'''
try:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': data})
# Return as an array so the difflib works
return [item + '\n' for item in ifcfg.split('\n')]
def _write_file_ifaces(iface, data, **settings):
'''
Writes a file to disk
'''
try:
eth_template = JINJA.get_template('debian_eth.jinja')
source_template = JINJA.get_template('debian_source.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
# Read /etc/network/interfaces into a dict
adapters = _parse_interfaces()
# Apply supplied settings over on-disk settings
adapters[iface] = data
ifcfg = ''
for adapter in adapters:
if 'type' in adapters[adapter] and adapters[adapter]['type'] == 'source':
tmp = source_template.render({'name': adapter, 'data': adapters[adapter]})
else:
tmp = eth_template.render({'name': adapter, 'data': adapters[adapter]})
ifcfg = ifcfg + tmp
if adapter == iface:
saved_ifcfg = tmp
_SEPARATE_FILE = False
if 'filename' in settings:
if not settings['filename'].startswith('/'):
filename = '{0}/{1}'.format(_DEB_NETWORK_DIR, settings['filename'])
else:
filename = settings['filename']
_SEPARATE_FILE = True
else:
if 'filename' in adapters[adapter]['data']:
filename = adapters[adapter]['data']
else:
filename = _DEB_NETWORK_FILE
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
if _SEPARATE_FILE:
fout.write(salt.utils.stringutils.to_str(saved_ifcfg))
else:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return saved_ifcfg.split('\n')
def _write_file_ppp_ifaces(iface, data):
'''
Writes a file to disk
'''
try:
template = JINJA.get_template('debian_ppp_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_ppp_eth.jinja')
return ''
adapters = _parse_interfaces()
adapters[iface] = data
ifcfg = ''
tmp = template.render({'data': adapters[iface]})
ifcfg = tmp + ifcfg
filename = _DEB_PPP_DIR + '/' + adapters[iface]['data']['inet']['provider']
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.fopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return filename
def build_bond(iface, **settings):
'''
Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb
'''
deb_major = __grains__['osrelease'][:1]
opts = _parse_settings_bond(settings, iface)
try:
template = JINJA.get_template('conf.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template conf.jinja')
return ''
data = template.render({'name': iface, 'bonding': opts})
if 'test' in settings and settings['test']:
return _read_temp(data)
_write_file(iface, data, _DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
if deb_major == '5':
for line_type in ('alias', 'options'):
cmd = ['sed', '-i', '-e', r'/^{0}\s{1}.*/d'.format(line_type, iface),
'/etc/modprobe.conf']
__salt__['cmd.run'](cmd, python_shell=False)
__salt__['file.append']('/etc/modprobe.conf', path)
# Load kernel module
__salt__['kmod.load']('bonding')
# install ifenslave-2.6
__salt__['pkg.install']('ifenslave-2.6')
return _read_file(path)
def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'vlan':
settings['vlan'] = 'yes'
__salt__['pkg.install']('vlan')
elif iface_type == 'pppoe':
settings['pppoe'] = 'yes'
if not __salt__['pkg.version']('ppp'):
inst = __salt__['pkg.install']('ppp')
elif iface_type == 'bond':
if 'slaves' not in settings:
msg = 'slaves is a required setting for bond interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'bridge':
if 'ports' not in settings:
msg = (
'ports is a required setting for bridge interfaces on Debian '
'or Ubuntu based systems'
)
log.error(msg)
raise AttributeError(msg)
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'pppoe']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
if iface_type in ['source']:
opts = _parse_settings_source(settings, iface_type, enabled, iface)
if 'test' in settings and settings['test']:
return _read_temp_ifaces(iface, opts[iface])
ifcfg = _write_file_ifaces(iface, opts[iface], **settings)
if iface_type == 'pppoe':
_write_file_ppp_ifaces(iface, opts[iface])
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg]
def build_routes(iface, **settings):
'''
Add route scripts for a network interface using up commands.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
'''
opts = _parse_routes(iface, settings)
try:
template = JINJA.get_template('route_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template route_eth.jinja')
return ''
add_routecfg = template.render(route_type='add',
routes=opts['routes'],
iface=iface)
del_routecfg = template.render(route_type='del',
routes=opts['routes'],
iface=iface)
if 'test' in settings and settings['test']:
return _read_temp(add_routecfg + del_routecfg)
filename = _write_file_routes(iface,
add_routecfg,
_DEB_NETWORK_UP_DIR,
'route-{0}')
results = _read_file(filename)
filename = _write_file_routes(iface,
del_routecfg,
_DEB_NETWORK_DOWN_DIR,
'route-{0}')
results += _read_file(filename)
return results
def down(iface, iface_type):
'''
Shutdown a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.down eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought down.
if iface_type not in ['slave', 'source']:
return __salt__['cmd.run'](['ifdown', iface])
return None
def get_bond(iface):
'''
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
'''
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
return _read_file(path)
def get_interface(iface):
'''
Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
adapters = _parse_interfaces()
if iface in adapters:
try:
if iface == 'source':
template = JINJA.get_template('debian_source.jinja')
else:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': adapters[iface]})
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg.split('\n')]
else:
return []
def up(iface, iface_type): # pylint: disable=C0103
'''
Start up a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.up eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought up.
if iface_type not in ('slave', 'source'):
return __salt__['cmd.run'](['ifup', iface])
return None
def get_network_settings():
'''
Return the contents of the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_network_settings
'''
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
settings = {}
if __salt__['service.available']('networking'):
if __salt__['service.status']('networking'):
settings['networking'] = "yes"
else:
settings['networking'] = "no"
else:
settings['networking'] = "no"
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
settings['hostname'] = hostname
settings['domainname'] = domainname
settings['searchdomain'] = searchdomain
else:
settings = _parse_current_network_settings()
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(settings)
return _read_temp(network)
def get_routes(iface):
'''
Return the routes for the interface
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0
'''
filename = os.path.join(_DEB_NETWORK_UP_DIR, 'route-{0}'.format(iface))
results = _read_file(filename)
filename = os.path.join(_DEB_NETWORK_DOWN_DIR, 'route-{0}'.format(iface))
results += _read_file(filename)
return results
def apply_network_settings(**settings):
'''
Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings
'''
if 'require_reboot' not in settings:
settings['require_reboot'] = False
if 'apply_hostname' not in settings:
settings['apply_hostname'] = False
hostname_res = True
if settings['apply_hostname'] in _CONFIG_TRUE:
if 'hostname' in settings:
hostname_res = __salt__['network.mod_hostname'](settings['hostname'])
else:
log.warning(
'The network state sls is trying to apply hostname '
'changes but no hostname is defined.'
)
hostname_res = False
res = True
if settings['require_reboot'] in _CONFIG_TRUE:
log.warning(
'The network state sls is requiring a reboot of the system to '
'properly apply network configuration.'
)
res = True
else:
stop = __salt__['service.stop']('networking')
time.sleep(2)
res = stop and __salt__['service.start']('networking')
return hostname_res and res
def build_network_settings(**settings):
'''
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
'''
changes = []
# Read current configuration and store default values
current_network_settings = _parse_current_network_settings()
# Build settings
opts = _parse_network_settings(settings, current_network_settings)
# Ubuntu has moved away from /etc/default/networking
# beginning with the 12.04 release so we disable or enable
# the networking related services on boot
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
if opts['networking'] == 'yes':
service_cmd = 'service.enable'
else:
service_cmd = 'service.disable'
if __salt__['service.available']('NetworkManager'):
__salt__[service_cmd]('NetworkManager')
if __salt__['service.available']('networking'):
__salt__[service_cmd]('networking')
else:
try:
template = JINJA.get_template('network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template network.jinja')
return ''
network = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(network)
# Write settings
_write_file_network(network, _DEB_NETWORKING_FILE, True)
# Get hostname and domain from opts
sline = opts['hostname'].split('.', 1)
opts['hostname'] = sline[0]
current_domainname = current_network_settings['domainname']
current_searchdomain = current_network_settings['searchdomain']
new_domain = False
if len(sline) > 1:
new_domainname = sline[1]
if new_domainname != current_domainname:
domainname = new_domainname
opts['domainname'] = new_domainname
new_domain = True
else:
domainname = current_domainname
opts['domainname'] = domainname
else:
domainname = current_domainname
opts['domainname'] = domainname
new_search = False
if 'search' in opts:
new_searchdomain = opts['search']
if new_searchdomain != current_searchdomain:
searchdomain = new_searchdomain
opts['searchdomain'] = new_searchdomain
new_search = True
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
# If the domain changes, then we should write the resolv.conf file.
if new_domain or new_search:
# Look for existing domain line and update if necessary
resolve = _parse_resolve()
domain_prog = re.compile(r'domain\s+')
search_prog = re.compile(r'search\s+')
new_contents = []
for item in _read_file(_DEB_RESOLV_FILE):
if domain_prog.match(item):
item = 'domain {0}'.format(domainname)
elif search_prog.match(item):
item = 'search {0}'.format(searchdomain)
new_contents.append(item)
# A domain line didn't exist so we'll add one in
# with the new domainname
if 'domain' not in resolve:
new_contents.insert(0, 'domain {0}' . format(domainname))
# A search line didn't exist so we'll add one in
# with the new search domain
if 'search' not in resolve:
new_contents.insert('domain' in resolve, 'search {0}'.format(searchdomain))
new_resolv = '\n'.join(new_contents)
# Write /etc/resolv.conf
if not ('test' in settings and settings['test']):
_write_file_network(new_resolv, _DEB_RESOLV_FILE)
# used for returning the results back
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(opts)
changes.extend(_read_temp(network))
return changes
|
saltstack/salt
|
salt/modules/debian_ip.py
|
__space_delimited_list
|
python
|
def __space_delimited_list(value):
'''validate that a value contains one or more space-delimited values'''
if isinstance(value, six.string_types):
value = value.strip().split()
if hasattr(value, '__iter__') and value != []:
return (True, value, 'space-delimited string')
else:
return (False, value, '{0} is not a valid space-delimited value.\n'.format(value))
|
validate that a value contains one or more space-delimited values
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_ip.py#L381-L389
| null |
# -*- coding: utf-8 -*-
'''
The networking module for Debian-based distros
References:
* http://www.debian.org/doc/manuals/debian-reference/ch05.en.html
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import functools
import logging
import os.path
import os
import re
import time
# Import third party libs
import jinja2
import jinja2.exceptions
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error,no-name-in-module
# Import salt libs
import salt.utils.dns
import salt.utils.files
import salt.utils.odict
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.validate.net
# Set up logging
log = logging.getLogger(__name__)
# Set up template environment
JINJA = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'debian_ip')
)
)
# Define the module's virtual name
__virtualname__ = 'ip'
def __virtual__():
'''
Confine this module to Debian-based distros
'''
if __grains__['os_family'] == 'Debian':
return __virtualname__
return (False, 'The debian_ip module could not be loaded: '
'unsupported OS family')
_ETHTOOL_CONFIG_OPTS = {
'speed': 'link-speed',
'duplex': 'link-duplex',
'autoneg': 'ethernet-autoneg',
'ethernet-port': 'ethernet-port',
'wol': 'ethernet-wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'rx': 'offload-rx',
'tx': 'offload-tx',
'sg': 'offload-sg',
'tso': 'offload-tso',
'ufo': 'offload-ufo',
'gso': 'offload-gso',
'gro': 'offload-gro',
'lro': 'offload-lro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_REV_ETHTOOL_CONFIG_OPTS = {
'link-speed': 'speed',
'link-duplex': 'duplex',
'ethernet-autoneg': 'autoneg',
'ethernet-port': 'ethernet-port',
'ethernet-wol': 'wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'offload-rx': 'rx',
'offload-tx': 'tx',
'offload-sg': 'sg',
'offload-tso': 'tso',
'offload-ufo': 'ufo',
'offload-gso': 'gso',
'offload-lro': 'lro',
'offload-gro': 'gro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_DEB_CONFIG_PPPOE_OPTS = {
'user': 'user',
'password': 'password',
'provider': 'provider',
'pppoe_iface': 'pppoe_iface',
'noipdefault': 'noipdefault',
'usepeerdns': 'usepeerdns',
'defaultroute': 'defaultroute',
'holdoff': 'holdoff',
'maxfail': 'maxfail',
'hide-password': 'hide-password',
'lcp-echo-interval': 'lcp-echo-interval',
'lcp-echo-failure': 'lcp-echo-failure',
'connect': 'connect',
'noauth': 'noauth',
'persist': 'persist',
'mtu': 'mtu',
'noaccomp': 'noaccomp',
'linkname': 'linkname',
}
_DEB_ROUTES_FILE = '/etc/network/routes'
_DEB_NETWORK_FILE = '/etc/network/interfaces'
_DEB_NETWORK_DIR = '/etc/network/interfaces.d/'
_DEB_NETWORK_UP_DIR = '/etc/network/if-up.d/'
_DEB_NETWORK_DOWN_DIR = '/etc/network/if-down.d/'
_DEB_NETWORK_CONF_FILES = '/etc/modprobe.d/'
_DEB_NETWORKING_FILE = '/etc/default/networking'
_DEB_HOSTNAME_FILE = '/etc/hostname'
_DEB_RESOLV_FILE = '/etc/resolv.conf'
_DEB_PPP_DIR = '/etc/ppp/peers/'
_CONFIG_TRUE = ['yes', 'on', 'true', '1', True]
_CONFIG_FALSE = ['no', 'off', 'false', '0', False]
_IFACE_TYPES = [
'eth', 'bond', 'alias', 'clone',
'ipsec', 'dialup', 'bridge', 'slave',
'vlan', 'pppoe', 'source',
]
def _error_msg_iface(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, '|'.join(str(e) for e in expected))
def _error_msg_routes(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, expected)
def _log_default_iface(iface, opt, value):
log.info(
'Using default option -- Interface: %s Option: %s Value: %s',
iface, opt, value
)
def _error_msg_network(option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]'
return msg.format(option, '|'.join(str(e) for e in expected))
def _log_default_network(opt, value):
log.info('Using existing setting -- Setting: %s Value: %s', opt, value)
def _raise_error_iface(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_iface(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_network(option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_network(option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_routes(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_routes(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _read_file(path):
'''
Reads and returns the contents of a text file
'''
try:
with salt.utils.files.flopen(path, 'rb') as contents:
return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]
except (OSError, IOError):
return ''
def _parse_resolve():
'''
Parse /etc/resolv.conf
'''
return salt.utils.dns.parse_resolv(_DEB_RESOLV_FILE)
def _parse_domainname():
'''
Parse /etc/resolv.conf and return domainname
'''
return _parse_resolve().get('domain', '')
def _parse_searchdomain():
'''
Parse /etc/resolv.conf and return searchdomain
'''
return _parse_resolve().get('search', '')
def _parse_hostname():
'''
Parse /etc/hostname and return hostname
'''
contents = _read_file(_DEB_HOSTNAME_FILE)
if contents:
return contents[0].split('\n')[0]
else:
return ''
def _parse_current_network_settings():
'''
Parse /etc/default/networking and return current configuration
'''
opts = salt.utils.odict.OrderedDict()
opts['networking'] = ''
if os.path.isfile(_DEB_NETWORKING_FILE):
with salt.utils.files.fopen(_DEB_NETWORKING_FILE) as contents:
for line in contents:
salt.utils.stringutils.to_unicode(line)
if line.startswith('#'):
continue
elif line.startswith('CONFIGURE_INTERFACES'):
opts['networking'] = line.split('=', 1)[1].strip()
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
opts['hostname'] = hostname
opts['domainname'] = domainname
opts['searchdomain'] = searchdomain
return opts
# def __validator_func(value):
# return (valid: True/False, (transformed) value, error message)
def __ipv4_quad(value):
'''validate an IPv4 address'''
return (salt.utils.validate.net.ipv4_addr(value), value,
'dotted IPv4 address')
def __ipv6(value):
'''validate an IPv6 address'''
return (salt.utils.validate.net.ipv6_addr(value), value,
'IPv6 address')
def __mac(value):
'''validate a mac address'''
return (salt.utils.validate.net.mac(value), value,
'MAC address')
def __anything(value):
return (True, value, None)
def __int(value):
'''validate an integer'''
valid, _value = False, value
try:
_value = int(value)
valid = True
except ValueError:
pass
return (valid, _value, 'integer')
def __float(value):
'''validate a float'''
valid, _value = False, value
try:
_value = float(value)
valid = True
except ValueError:
pass
return (valid, _value, 'float')
def __ipv4_netmask(value):
'''validate an IPv4 dotted quad or integer CIDR netmask'''
valid, errmsg = False, 'dotted quad or integer CIDR (0->32)'
valid, value, _ = __int(value)
if not (valid and 0 <= value <= 32):
valid = salt.utils.validate.net.netmask(value)
return (valid, value, errmsg)
def __ipv6_netmask(value):
'''validate an IPv6 integer netmask'''
valid, errmsg = False, 'IPv6 netmask (0->128)'
valid, value, _ = __int(value)
valid = (valid and 0 <= value <= 128)
return (valid, value, errmsg)
def __within2(value, within=None, errmsg=None, dtype=None):
'''validate that a value is in ``within`` and optionally a ``dtype``'''
valid, _value = False, value
if dtype:
try:
_value = dtype(value) # TODO: this is a bit loose when dtype is a class
valid = _value in within
except ValueError:
pass
else:
valid = _value in within
if errmsg is None:
if dtype:
typename = getattr(dtype, '__name__',
hasattr(dtype, '__class__')
and getattr(dtype.__class__, 'name', dtype))
errmsg = '{0} within \'{1}\''.format(typename, within)
else:
errmsg = 'within \'{0}\''.format(within)
return (valid, _value, errmsg)
def __within(within=None, errmsg=None, dtype=None):
return functools.partial(__within2, within=within,
errmsg=errmsg, dtype=dtype)
SALT_ATTR_TO_DEBIAN_ATTR_MAP = {
'dns': 'dns-nameservers',
'search': 'dns-search',
'hwaddr': 'hwaddress', # TODO: this limits bootp functionality
'ipaddr': 'address',
'ipaddrs': 'addresses',
}
DEBIAN_ATTR_TO_SALT_ATTR_MAP = dict(
(v, k) for (k, v) in six.iteritems(SALT_ATTR_TO_DEBIAN_ATTR_MAP))
# TODO
DEBIAN_ATTR_TO_SALT_ATTR_MAP['address'] = 'address'
DEBIAN_ATTR_TO_SALT_ATTR_MAP['hwaddress'] = 'hwaddress'
IPV4_VALID_PROTO = ['bootp', 'dhcp', 'static', 'manual', 'loopback', 'ppp']
IPV4_ATTR_MAP = {
'proto': __within(IPV4_VALID_PROTO, dtype=six.text_type),
# ipv4 static & manual
'address': __ipv4_quad,
'addresses': __anything,
'netmask': __ipv4_netmask,
'broadcast': __ipv4_quad,
'metric': __int,
'gateway': __ipv4_quad, # supports a colon-delimited list
'pointopoint': __ipv4_quad,
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'link', 'host'], dtype=six.text_type),
# dhcp
'hostname': __anything,
'leasehours': __int,
'leasetime': __int,
'vendor': __anything,
'client': __anything,
# bootp
'bootfile': __anything,
'server': __ipv4_quad,
'hwaddr': __mac,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'dstaddr': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# bond
'slaves': __anything,
# ppp
'provider': __anything,
'unit': __int,
'options': __anything,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
#
'network': __anything, # i don't know what this is
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
IPV6_VALID_PROTO = ['auto', 'loopback', 'static', 'manual',
'dhcp', 'v4tunnel', '6to4']
IPV6_ATTR_MAP = {
'proto': __within(IPV6_VALID_PROTO),
# ipv6 static & manual
'address': __ipv6,
'addresses': __anything,
'netmask': __ipv6_netmask,
'broadcast': __ipv6,
'gateway': __ipv6, # supports a colon-delimited list
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'site', 'link', 'host'], dtype=six.text_type),
# inet6 auto
'privext': __within([0, 1, 2], dtype=int),
'dhcp': __within([0, 1], dtype=int),
# inet6 static & manual & dhcp
'media': __anything,
'accept_ra': __within([0, 1], dtype=int),
'autoconf': __within([0, 1], dtype=int),
'preferred-lifetime': __int,
'dad-attempts': __int, # 0 to disable
'dad-interval': __float,
# bond
'slaves': __anything,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
WIRELESS_ATTR_MAP = {
'wireless-essid': __anything,
'wireless-mode': __anything, # TODO
'wpa-ap-scan': __within([0, 1, 2], dtype=int), # TODO
'wpa-conf': __anything,
'wpa-driver': __anything,
'wpa-group': __anything,
'wpa-key-mgmt': __anything,
'wpa-pairwise': __anything,
'wpa-psk': __anything,
'wpa-proto': __anything, # partial(__within,
'wpa-roam': __anything,
'wpa-ssid': __anything, # TODO
}
ATTRMAPS = {
'inet': [IPV4_ATTR_MAP, WIRELESS_ATTR_MAP],
'inet6': [IPV6_ATTR_MAP, WIRELESS_ATTR_MAP]
}
def _validate_interface_option(attr, value, addrfam='inet'):
'''lookup the validation function for a [addrfam][attr] and
return the results
:param attr: attribute name
:param value: raw setting value
:param addrfam: address family (inet, inet6,
'''
valid, _value, errmsg = False, value, 'Unknown validator'
attrmaps = ATTRMAPS.get(addrfam, [])
for attrmap in attrmaps:
if attr in attrmap:
validate_func = attrmap[attr]
(valid, _value, errmsg) = validate_func(value)
break
return (valid, _value, errmsg)
def _attrmaps_contain_attr(attr):
return (
attr in WIRELESS_ATTR_MAP or
attr in IPV4_ATTR_MAP or
attr in IPV6_ATTR_MAP)
def _parse_interfaces(interface_files=None):
'''
Parse /etc/network/interfaces and return current configured interfaces
'''
if interface_files is None:
interface_files = []
# Add this later.
if os.path.exists(_DEB_NETWORK_DIR):
interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]
if os.path.isfile(_DEB_NETWORK_FILE):
interface_files.insert(0, _DEB_NETWORK_FILE)
adapters = salt.utils.odict.OrderedDict()
method = -1
for interface_file in interface_files:
with salt.utils.files.fopen(interface_file) as interfaces:
# This ensures iface_dict exists, but does not ensure we're not reading a new interface.
iface_dict = {}
for line in interfaces:
line = salt.utils.stringutils.to_unicode(line)
# Identify the clauses by the first word of each line.
# Go to the next line if the current line is a comment
# or all spaces.
if line.lstrip().startswith('#') or line.isspace():
continue
# Parse the iface clause
if line.startswith('iface'):
sline = line.split()
if len(sline) != 4:
msg = 'Interface file malformed: {0}.'
msg = msg.format(sline)
log.error(msg)
raise AttributeError(msg)
iface_name = sline[1]
addrfam = sline[2]
method = sline[3]
# Create item in dict, if not already there
if iface_name not in adapters:
adapters[iface_name] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters[iface_name]:
adapters[iface_name]['data'] = salt.utils.odict.OrderedDict()
if addrfam not in adapters[iface_name]['data']:
adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict()
iface_dict = adapters[iface_name]['data'][addrfam]
iface_dict['addrfam'] = addrfam
iface_dict['proto'] = method
iface_dict['filename'] = interface_file
# Parse the detail clauses.
elif line[0].isspace():
sline = line.split()
# conf file attr: dns-nameservers
# salt states.network attr: dns
attr, valuestr = line.rstrip().split(None, 1)
if _attrmaps_contain_attr(attr):
if '-' in attr:
attrname = attr.replace('-', '_')
else:
attrname = attr
(valid, value, errmsg) = _validate_interface_option(
attr, valuestr, addrfam)
if attrname == 'address' and 'address' in iface_dict:
if 'addresses' not in iface_dict:
iface_dict['addresses'] = []
iface_dict['addresses'].append(value)
else:
iface_dict[attrname] = value
elif attr in _REV_ETHTOOL_CONFIG_OPTS:
if 'ethtool' not in iface_dict:
iface_dict['ethtool'] = salt.utils.odict.OrderedDict()
iface_dict['ethtool'][attr] = valuestr
elif attr.startswith('bond'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bonding' not in iface_dict:
iface_dict['bonding'] = salt.utils.odict.OrderedDict()
iface_dict['bonding'][opt] = valuestr
elif attr.startswith('bridge'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bridging' not in iface_dict:
iface_dict['bridging'] = salt.utils.odict.OrderedDict()
iface_dict['bridging'][opt] = valuestr
elif attr in ['up', 'pre-up', 'post-up',
'down', 'pre-down', 'post-down']:
cmd = valuestr
cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr))
if cmd_key not in iface_dict:
iface_dict[cmd_key] = []
iface_dict[cmd_key].append(cmd)
elif line.startswith('auto'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['enabled'] = True
elif line.startswith('allow-hotplug'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['hotplug'] = True
elif line.startswith('source'):
if 'source' not in adapters:
adapters['source'] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters['source']:
adapters['source']['data'] = salt.utils.odict.OrderedDict()
adapters['source']['data']['sources'] = []
adapters['source']['data']['sources'].append(line.split()[1])
# Return a sorted list of the keys for bond, bridge and ethtool options to
# ensure a consistent order
for iface_name in adapters:
if iface_name == 'source':
continue
if 'data' not in adapters[iface_name]:
msg = 'Interface file malformed for interface: {0}.'.format(iface_name)
log.error(msg)
adapters.pop(iface_name)
continue
for opt in ['ethtool', 'bonding', 'bridging']:
for inet in ['inet', 'inet6']:
if inet in adapters[iface_name]['data']:
if opt in adapters[iface_name]['data'][inet]:
opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys())
adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys
return adapters
def _parse_ethtool_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
if 'autoneg' in opts:
if opts['autoneg'] in _CONFIG_TRUE:
config.update({'autoneg': 'on'})
elif opts['autoneg'] in _CONFIG_FALSE:
config.update({'autoneg': 'off'})
else:
_raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE)
if 'duplex' in opts:
valid = ['full', 'half']
if opts['duplex'] in valid:
config.update({'duplex': opts['duplex']})
else:
_raise_error_iface(iface, 'duplex', valid)
if 'speed' in opts:
valid = ['10', '100', '1000', '10000']
if six.text_type(opts['speed']) in valid:
config.update({'speed': opts['speed']})
else:
_raise_error_iface(iface, opts['speed'], valid)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'on'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'off'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_ethtool_pppoe_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
for opt in _DEB_CONFIG_PPPOE_OPTS:
if opt in opts:
config[opt] = opts[opt]
if 'provider' in opts and not opts['provider']:
_raise_error_iface(iface, 'provider', _CONFIG_TRUE + _CONFIG_FALSE)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('noipdefault', 'usepeerdns', 'defaultroute', 'hide-password', 'noauth', 'persist', 'noaccomp'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'True'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'False'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_settings_bond(opts, iface):
'''
Filters given options and outputs valid settings for requested
operation. If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond_def = {
# 803.ad aggregation selection logic
# 0 for stable (default)
# 1 for bandwidth
# 2 for count
'ad_select': '0',
# Max number of transmit queues (default = 16)
'tx_queues': '16',
# Link monitoring in milliseconds. Most NICs support this
'miimon': '100',
# ARP interval in milliseconds
'arp_interval': '250',
# Delay before considering link down in milliseconds (miimon * 2)
'downdelay': '200',
# lacp_rate 0: Slow - every 30 seconds
# lacp_rate 1: Fast - every 1 second
'lacp_rate': '0',
# Max bonds for this driver
'max_bonds': '1',
# Specifies the time, in milliseconds, to wait before
# enabling a slave after a link recovery has been
# detected. Only used with miimon.
'updelay': '0',
# Used with miimon.
# On: driver sends mii
# Off: ethtool sends mii
'use_carrier': 'on',
# Default. Don't change unless you know what you are doing.
'xmit_hash_policy': 'layer2',
}
if opts['mode'] in ['balance-rr', '0']:
log.info('Device: %s Bonding Mode: load balancing (round-robin)', iface)
return _parse_settings_bond_0(opts, iface, bond_def)
elif opts['mode'] in ['active-backup', '1']:
log.info('Device: %s Bonding Mode: fault-tolerance (active-backup)', iface)
return _parse_settings_bond_1(opts, iface, bond_def)
elif opts['mode'] in ['balance-xor', '2']:
log.info('Device: %s Bonding Mode: load balancing (xor)', iface)
return _parse_settings_bond_2(opts, iface, bond_def)
elif opts['mode'] in ['broadcast', '3']:
log.info('Device: %s Bonding Mode: fault-tolerance (broadcast)', iface)
return _parse_settings_bond_3(opts, iface, bond_def)
elif opts['mode'] in ['802.3ad', '4']:
log.info('Device: %s Bonding Mode: IEEE 802.3ad Dynamic link '
'aggregation', iface)
return _parse_settings_bond_4(opts, iface, bond_def)
elif opts['mode'] in ['balance-tlb', '5']:
log.info('Device: %s Bonding Mode: transmit load balancing', iface)
return _parse_settings_bond_5(opts, iface, bond_def)
elif opts['mode'] in ['balance-alb', '6']:
log.info('Device: %s Bonding Mode: adaptive load balancing', iface)
return _parse_settings_bond_6(opts, iface, bond_def)
else:
valid = [
'0', '1', '2', '3', '4', '5', '6',
'balance-rr', 'active-backup', 'balance-xor',
'broadcast', '802.3ad', 'balance-tlb', 'balance-alb'
]
_raise_error_iface(iface, 'mode', valid)
def _parse_settings_bond_0(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond0.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '0'}
# ARP targets in n.n.n.n form
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
return bond
def _parse_settings_bond_1(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '1'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
if not (__grains__['os'] == "Ubuntu" and __grains__['osrelease_info'][0] >= 16):
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_2(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond2.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '2'}
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_3(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond3.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '3'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_4(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond4.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '4'}
for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']:
if binding in opts:
if binding == 'lacp_rate':
if opts[binding] == 'fast':
opts.update({binding: '1'})
if opts[binding] == 'slow':
opts.update({binding: '0'})
valid = ['fast', '1', 'slow', '0']
else:
valid = ['integer']
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, valid)
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_5(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond5.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '5'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_settings_bond_6(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond6.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '6'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_bridge_opts(opts, iface):
'''
Filters given options and outputs valid settings for BRIDGING_OPTS
If an option has a value that is not expected, this
function will log the Interface, Setting and what was expected.
'''
config = {}
if 'ports' in opts:
if isinstance(opts['ports'], list):
opts['ports'] = ' '.join(opts['ports'])
config.update({'ports': opts['ports']})
for opt in ['ageing', 'fd', 'gcint', 'hello', 'maxage']:
if opt in opts:
try:
float(opts[opt])
config.update({opt: opts[opt]})
except ValueError:
_raise_error_iface(iface, opt, ['float'])
for opt in ['bridgeprio', 'maxwait']:
if opt in opts:
if isinstance(opts[opt], int):
config.update({opt: opts[opt]})
else:
_raise_error_iface(iface, opt, ['integer'])
if 'hw' in opts:
# match 12 hex digits with either : or - as separators between pairs
if re.match('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$',
opts['hw'].lower()):
config.update({'hw': opts['hw']})
else:
_raise_error_iface(iface, 'hw', ['valid MAC address'])
for opt in ['pathcost', 'portprio']:
if opt in opts:
try:
port, cost_or_prio = opts[opt].split()
int(cost_or_prio)
config.update({opt: '{0} {1}'.format(port, cost_or_prio)})
except ValueError:
_raise_error_iface(iface, opt, ['interface integer'])
if 'stp' in opts:
if opts['stp'] in _CONFIG_TRUE:
config.update({'stp': 'on'})
elif opts['stp'] in _CONFIG_FALSE:
config.update({'stp': 'off'})
else:
_raise_error_iface(iface, 'stp', _CONFIG_TRUE + _CONFIG_FALSE)
if 'waitport' in opts:
if isinstance(opts['waitport'], int):
config.update({'waitport': opts['waitport']})
else:
values = opts['waitport'].split()
waitport_time = values.pop(0)
if waitport_time.isdigit() and values:
config.update({
'waitport': '{0} {1}'.format(
waitport_time, ' '.join(values)
)
})
else:
_raise_error_iface(iface, opt, ['integer [interfaces]'])
return config
def _parse_settings_eth(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['inet'] = salt.utils.odict.OrderedDict()
iface_data['inet6'] = salt.utils.odict.OrderedDict()
if enabled:
adapters[iface]['enabled'] = True
if opts.get('hotplug', False):
adapters[iface]['hotplug'] = True
if opts.get('enable_ipv6', None) and opts.get('iface_type', '') == 'vlan':
iface_data['inet6']['vlan_raw_device'] = (
re.sub(r'\.\d*', '', iface))
for addrfam in ['inet', 'inet6']:
if iface_type not in ['bridge']:
tmp_ethtool = _parse_ethtool_opts(opts, iface)
if tmp_ethtool:
ethtool = {}
for item in tmp_ethtool:
ethtool[_ETHTOOL_CONFIG_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['ethtool'] = ethtool
# return a list of sorted keys to ensure consistent order
iface_data[addrfam]['ethtool_keys'] = sorted(ethtool)
if iface_type == 'bridge':
bridging = _parse_bridge_opts(opts, iface)
if bridging:
iface_data[addrfam]['bridging'] = bridging
iface_data[addrfam]['bridging_keys'] = sorted(bridging)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'bond':
bonding = _parse_settings_bond(opts, iface)
if bonding:
iface_data[addrfam]['bonding'] = bonding
iface_data[addrfam]['bonding']['slaves'] = opts['slaves']
iface_data[addrfam]['bonding_keys'] = sorted(bonding)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'slave':
adapters[iface]['master'] = opts['master']
opts['proto'] = 'manual'
iface_data[addrfam]['master'] = adapters[iface]['master']
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'vlan':
iface_data[addrfam]['vlan_raw_device'] = re.sub(r'\.\d*', '', iface)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'pppoe':
tmp_ethtool = _parse_ethtool_pppoe_opts(opts, iface)
if tmp_ethtool:
for item in tmp_ethtool:
adapters[iface]['data'][addrfam][_DEB_CONFIG_PPPOE_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['addrfam'] = addrfam
opts.pop('mode', None)
for opt, val in opts.items():
inet = None
if opt.startswith('ipv4'):
opt = opt[4:]
inet = 'inet'
iface_data['inet']['addrfam'] = 'inet'
elif opt.startswith('ipv6'):
iface_data['inet6']['addrfam'] = 'inet6'
opt = opt[4:]
inet = 'inet6'
elif opt in ['ipaddr', 'address', 'ipaddresses', 'addresses', 'gateway', 'proto']:
iface_data['inet']['addrfam'] = 'inet'
inet = 'inet'
_opt = SALT_ATTR_TO_DEBIAN_ATTR_MAP.get(opt, opt)
_debopt = _opt.replace('-', '_')
for addrfam in ['inet', 'inet6']:
(valid, value, errmsg) = _validate_interface_option(_opt, val, addrfam=addrfam)
if not valid:
continue
if inet is None and _debopt not in iface_data[addrfam]:
iface_data[addrfam][_debopt] = value
elif inet == addrfam:
iface_data[addrfam][_debopt] = value
for opt in ['up_cmds', 'pre_up_cmds', 'post_up_cmds',
'down_cmds', 'pre_down_cmds', 'post_down_cmds']:
if opt in opts:
iface_data['inet'][opt] = opts[opt]
iface_data['inet6'][opt] = opts[opt]
# Remove incomplete/disabled inet blocks
for (addrfam, opt) in [('inet', 'enable_ipv4'), ('inet6', 'enable_ipv6')]:
if opts.get(opt, None) is False:
iface_data.pop(addrfam)
elif iface_data[addrfam].get('addrfam', '') != addrfam:
iface_data.pop(addrfam)
return adapters
def _parse_settings_source(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['sources'] = [opts['source']]
return adapters
def _parse_network_settings(opts, current):
'''
Filters given options and outputs valid settings for
the global network settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
current = dict((k.lower(), v) for (k, v) in six.iteritems(current))
result = {}
valid = _CONFIG_TRUE + _CONFIG_FALSE
if 'enabled' not in opts:
try:
opts['networking'] = current['networking']
_log_default_network('networking', current['networking'])
except ValueError:
_raise_error_network('networking', valid)
else:
opts['networking'] = opts['enabled']
if opts['networking'] in valid:
if opts['networking'] in _CONFIG_TRUE:
result['networking'] = 'yes'
elif opts['networking'] in _CONFIG_FALSE:
result['networking'] = 'no'
else:
_raise_error_network('networking', valid)
if 'hostname' not in opts:
try:
opts['hostname'] = current['hostname']
_log_default_network('hostname', current['hostname'])
except ValueError:
_raise_error_network('hostname', ['server1.example.com'])
if opts['hostname']:
result['hostname'] = opts['hostname']
else:
_raise_error_network('hostname', ['server1.example.com'])
if 'search' in opts:
result['search'] = opts['search']
return result
def _parse_routes(iface, opts):
'''
Filters given options and outputs valid settings for
the route settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
result = {}
if 'routes' not in opts:
_raise_error_routes(iface, 'routes', 'List of routes')
for opt in opts:
result[opt] = opts[opt]
return result
def _write_file(iface, data, folder, pattern):
'''
Writes a file to disk
'''
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
return filename
def _write_file_routes(iface, data, folder, pattern):
'''
Writes a file to disk
'''
# ifup / ifdown is executing given folder via run-parts.
# according to run-parts man-page, only filenames with this pattern are
# executed: (^[a-zA-Z0-9_-]+$)
# In order to make the routes file work for vlan interfaces
# (default would have been in example /etc/network/if-up.d/route-bond0.12)
# these dots in the iface name need to be replaced by underscores, so it
# can be executed by run-parts
iface = iface.replace('.', '_')
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
__salt__['file.set_mode'](filename, '0755')
return filename
def _write_file_network(data, filename, create=False):
'''
Writes a file to disk
If file does not exist, only create if create
argument is True
'''
if not os.path.exists(filename) and not create:
msg = '{0} cannot be written. {0} does not exist\
and create is set to False'
msg = msg.format(filename)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
def _read_temp(data):
'''
Return what would be written to disk
'''
tout = StringIO()
tout.write(data)
tout.seek(0)
output = tout.readlines()
tout.close()
return output
def _read_temp_ifaces(iface, data):
'''
Return what would be written to disk for interfaces
'''
try:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': data})
# Return as an array so the difflib works
return [item + '\n' for item in ifcfg.split('\n')]
def _write_file_ifaces(iface, data, **settings):
'''
Writes a file to disk
'''
try:
eth_template = JINJA.get_template('debian_eth.jinja')
source_template = JINJA.get_template('debian_source.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
# Read /etc/network/interfaces into a dict
adapters = _parse_interfaces()
# Apply supplied settings over on-disk settings
adapters[iface] = data
ifcfg = ''
for adapter in adapters:
if 'type' in adapters[adapter] and adapters[adapter]['type'] == 'source':
tmp = source_template.render({'name': adapter, 'data': adapters[adapter]})
else:
tmp = eth_template.render({'name': adapter, 'data': adapters[adapter]})
ifcfg = ifcfg + tmp
if adapter == iface:
saved_ifcfg = tmp
_SEPARATE_FILE = False
if 'filename' in settings:
if not settings['filename'].startswith('/'):
filename = '{0}/{1}'.format(_DEB_NETWORK_DIR, settings['filename'])
else:
filename = settings['filename']
_SEPARATE_FILE = True
else:
if 'filename' in adapters[adapter]['data']:
filename = adapters[adapter]['data']
else:
filename = _DEB_NETWORK_FILE
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
if _SEPARATE_FILE:
fout.write(salt.utils.stringutils.to_str(saved_ifcfg))
else:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return saved_ifcfg.split('\n')
def _write_file_ppp_ifaces(iface, data):
'''
Writes a file to disk
'''
try:
template = JINJA.get_template('debian_ppp_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_ppp_eth.jinja')
return ''
adapters = _parse_interfaces()
adapters[iface] = data
ifcfg = ''
tmp = template.render({'data': adapters[iface]})
ifcfg = tmp + ifcfg
filename = _DEB_PPP_DIR + '/' + adapters[iface]['data']['inet']['provider']
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.fopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return filename
def build_bond(iface, **settings):
'''
Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb
'''
deb_major = __grains__['osrelease'][:1]
opts = _parse_settings_bond(settings, iface)
try:
template = JINJA.get_template('conf.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template conf.jinja')
return ''
data = template.render({'name': iface, 'bonding': opts})
if 'test' in settings and settings['test']:
return _read_temp(data)
_write_file(iface, data, _DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
if deb_major == '5':
for line_type in ('alias', 'options'):
cmd = ['sed', '-i', '-e', r'/^{0}\s{1}.*/d'.format(line_type, iface),
'/etc/modprobe.conf']
__salt__['cmd.run'](cmd, python_shell=False)
__salt__['file.append']('/etc/modprobe.conf', path)
# Load kernel module
__salt__['kmod.load']('bonding')
# install ifenslave-2.6
__salt__['pkg.install']('ifenslave-2.6')
return _read_file(path)
def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'vlan':
settings['vlan'] = 'yes'
__salt__['pkg.install']('vlan')
elif iface_type == 'pppoe':
settings['pppoe'] = 'yes'
if not __salt__['pkg.version']('ppp'):
inst = __salt__['pkg.install']('ppp')
elif iface_type == 'bond':
if 'slaves' not in settings:
msg = 'slaves is a required setting for bond interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'bridge':
if 'ports' not in settings:
msg = (
'ports is a required setting for bridge interfaces on Debian '
'or Ubuntu based systems'
)
log.error(msg)
raise AttributeError(msg)
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'pppoe']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
if iface_type in ['source']:
opts = _parse_settings_source(settings, iface_type, enabled, iface)
if 'test' in settings and settings['test']:
return _read_temp_ifaces(iface, opts[iface])
ifcfg = _write_file_ifaces(iface, opts[iface], **settings)
if iface_type == 'pppoe':
_write_file_ppp_ifaces(iface, opts[iface])
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg]
def build_routes(iface, **settings):
'''
Add route scripts for a network interface using up commands.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
'''
opts = _parse_routes(iface, settings)
try:
template = JINJA.get_template('route_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template route_eth.jinja')
return ''
add_routecfg = template.render(route_type='add',
routes=opts['routes'],
iface=iface)
del_routecfg = template.render(route_type='del',
routes=opts['routes'],
iface=iface)
if 'test' in settings and settings['test']:
return _read_temp(add_routecfg + del_routecfg)
filename = _write_file_routes(iface,
add_routecfg,
_DEB_NETWORK_UP_DIR,
'route-{0}')
results = _read_file(filename)
filename = _write_file_routes(iface,
del_routecfg,
_DEB_NETWORK_DOWN_DIR,
'route-{0}')
results += _read_file(filename)
return results
def down(iface, iface_type):
'''
Shutdown a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.down eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought down.
if iface_type not in ['slave', 'source']:
return __salt__['cmd.run'](['ifdown', iface])
return None
def get_bond(iface):
'''
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
'''
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
return _read_file(path)
def get_interface(iface):
'''
Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
adapters = _parse_interfaces()
if iface in adapters:
try:
if iface == 'source':
template = JINJA.get_template('debian_source.jinja')
else:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': adapters[iface]})
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg.split('\n')]
else:
return []
def up(iface, iface_type): # pylint: disable=C0103
'''
Start up a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.up eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought up.
if iface_type not in ('slave', 'source'):
return __salt__['cmd.run'](['ifup', iface])
return None
def get_network_settings():
'''
Return the contents of the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_network_settings
'''
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
settings = {}
if __salt__['service.available']('networking'):
if __salt__['service.status']('networking'):
settings['networking'] = "yes"
else:
settings['networking'] = "no"
else:
settings['networking'] = "no"
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
settings['hostname'] = hostname
settings['domainname'] = domainname
settings['searchdomain'] = searchdomain
else:
settings = _parse_current_network_settings()
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(settings)
return _read_temp(network)
def get_routes(iface):
'''
Return the routes for the interface
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0
'''
filename = os.path.join(_DEB_NETWORK_UP_DIR, 'route-{0}'.format(iface))
results = _read_file(filename)
filename = os.path.join(_DEB_NETWORK_DOWN_DIR, 'route-{0}'.format(iface))
results += _read_file(filename)
return results
def apply_network_settings(**settings):
'''
Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings
'''
if 'require_reboot' not in settings:
settings['require_reboot'] = False
if 'apply_hostname' not in settings:
settings['apply_hostname'] = False
hostname_res = True
if settings['apply_hostname'] in _CONFIG_TRUE:
if 'hostname' in settings:
hostname_res = __salt__['network.mod_hostname'](settings['hostname'])
else:
log.warning(
'The network state sls is trying to apply hostname '
'changes but no hostname is defined.'
)
hostname_res = False
res = True
if settings['require_reboot'] in _CONFIG_TRUE:
log.warning(
'The network state sls is requiring a reboot of the system to '
'properly apply network configuration.'
)
res = True
else:
stop = __salt__['service.stop']('networking')
time.sleep(2)
res = stop and __salt__['service.start']('networking')
return hostname_res and res
def build_network_settings(**settings):
'''
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
'''
changes = []
# Read current configuration and store default values
current_network_settings = _parse_current_network_settings()
# Build settings
opts = _parse_network_settings(settings, current_network_settings)
# Ubuntu has moved away from /etc/default/networking
# beginning with the 12.04 release so we disable or enable
# the networking related services on boot
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
if opts['networking'] == 'yes':
service_cmd = 'service.enable'
else:
service_cmd = 'service.disable'
if __salt__['service.available']('NetworkManager'):
__salt__[service_cmd]('NetworkManager')
if __salt__['service.available']('networking'):
__salt__[service_cmd]('networking')
else:
try:
template = JINJA.get_template('network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template network.jinja')
return ''
network = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(network)
# Write settings
_write_file_network(network, _DEB_NETWORKING_FILE, True)
# Get hostname and domain from opts
sline = opts['hostname'].split('.', 1)
opts['hostname'] = sline[0]
current_domainname = current_network_settings['domainname']
current_searchdomain = current_network_settings['searchdomain']
new_domain = False
if len(sline) > 1:
new_domainname = sline[1]
if new_domainname != current_domainname:
domainname = new_domainname
opts['domainname'] = new_domainname
new_domain = True
else:
domainname = current_domainname
opts['domainname'] = domainname
else:
domainname = current_domainname
opts['domainname'] = domainname
new_search = False
if 'search' in opts:
new_searchdomain = opts['search']
if new_searchdomain != current_searchdomain:
searchdomain = new_searchdomain
opts['searchdomain'] = new_searchdomain
new_search = True
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
# If the domain changes, then we should write the resolv.conf file.
if new_domain or new_search:
# Look for existing domain line and update if necessary
resolve = _parse_resolve()
domain_prog = re.compile(r'domain\s+')
search_prog = re.compile(r'search\s+')
new_contents = []
for item in _read_file(_DEB_RESOLV_FILE):
if domain_prog.match(item):
item = 'domain {0}'.format(domainname)
elif search_prog.match(item):
item = 'search {0}'.format(searchdomain)
new_contents.append(item)
# A domain line didn't exist so we'll add one in
# with the new domainname
if 'domain' not in resolve:
new_contents.insert(0, 'domain {0}' . format(domainname))
# A search line didn't exist so we'll add one in
# with the new search domain
if 'search' not in resolve:
new_contents.insert('domain' in resolve, 'search {0}'.format(searchdomain))
new_resolv = '\n'.join(new_contents)
# Write /etc/resolv.conf
if not ('test' in settings and settings['test']):
_write_file_network(new_resolv, _DEB_RESOLV_FILE)
# used for returning the results back
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(opts)
changes.extend(_read_temp(network))
return changes
|
saltstack/salt
|
salt/modules/debian_ip.py
|
_validate_interface_option
|
python
|
def _validate_interface_option(attr, value, addrfam='inet'):
'''lookup the validation function for a [addrfam][attr] and
return the results
:param attr: attribute name
:param value: raw setting value
:param addrfam: address family (inet, inet6,
'''
valid, _value, errmsg = False, value, 'Unknown validator'
attrmaps = ATTRMAPS.get(addrfam, [])
for attrmap in attrmaps:
if attr in attrmap:
validate_func = attrmap[attr]
(valid, _value, errmsg) = validate_func(value)
break
return (valid, _value, errmsg)
|
lookup the validation function for a [addrfam][attr] and
return the results
:param attr: attribute name
:param value: raw setting value
:param addrfam: address family (inet, inet6,
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_ip.py#L523-L538
| null |
# -*- coding: utf-8 -*-
'''
The networking module for Debian-based distros
References:
* http://www.debian.org/doc/manuals/debian-reference/ch05.en.html
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import functools
import logging
import os.path
import os
import re
import time
# Import third party libs
import jinja2
import jinja2.exceptions
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error,no-name-in-module
# Import salt libs
import salt.utils.dns
import salt.utils.files
import salt.utils.odict
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.validate.net
# Set up logging
log = logging.getLogger(__name__)
# Set up template environment
JINJA = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'debian_ip')
)
)
# Define the module's virtual name
__virtualname__ = 'ip'
def __virtual__():
'''
Confine this module to Debian-based distros
'''
if __grains__['os_family'] == 'Debian':
return __virtualname__
return (False, 'The debian_ip module could not be loaded: '
'unsupported OS family')
_ETHTOOL_CONFIG_OPTS = {
'speed': 'link-speed',
'duplex': 'link-duplex',
'autoneg': 'ethernet-autoneg',
'ethernet-port': 'ethernet-port',
'wol': 'ethernet-wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'rx': 'offload-rx',
'tx': 'offload-tx',
'sg': 'offload-sg',
'tso': 'offload-tso',
'ufo': 'offload-ufo',
'gso': 'offload-gso',
'gro': 'offload-gro',
'lro': 'offload-lro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_REV_ETHTOOL_CONFIG_OPTS = {
'link-speed': 'speed',
'link-duplex': 'duplex',
'ethernet-autoneg': 'autoneg',
'ethernet-port': 'ethernet-port',
'ethernet-wol': 'wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'offload-rx': 'rx',
'offload-tx': 'tx',
'offload-sg': 'sg',
'offload-tso': 'tso',
'offload-ufo': 'ufo',
'offload-gso': 'gso',
'offload-lro': 'lro',
'offload-gro': 'gro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_DEB_CONFIG_PPPOE_OPTS = {
'user': 'user',
'password': 'password',
'provider': 'provider',
'pppoe_iface': 'pppoe_iface',
'noipdefault': 'noipdefault',
'usepeerdns': 'usepeerdns',
'defaultroute': 'defaultroute',
'holdoff': 'holdoff',
'maxfail': 'maxfail',
'hide-password': 'hide-password',
'lcp-echo-interval': 'lcp-echo-interval',
'lcp-echo-failure': 'lcp-echo-failure',
'connect': 'connect',
'noauth': 'noauth',
'persist': 'persist',
'mtu': 'mtu',
'noaccomp': 'noaccomp',
'linkname': 'linkname',
}
_DEB_ROUTES_FILE = '/etc/network/routes'
_DEB_NETWORK_FILE = '/etc/network/interfaces'
_DEB_NETWORK_DIR = '/etc/network/interfaces.d/'
_DEB_NETWORK_UP_DIR = '/etc/network/if-up.d/'
_DEB_NETWORK_DOWN_DIR = '/etc/network/if-down.d/'
_DEB_NETWORK_CONF_FILES = '/etc/modprobe.d/'
_DEB_NETWORKING_FILE = '/etc/default/networking'
_DEB_HOSTNAME_FILE = '/etc/hostname'
_DEB_RESOLV_FILE = '/etc/resolv.conf'
_DEB_PPP_DIR = '/etc/ppp/peers/'
_CONFIG_TRUE = ['yes', 'on', 'true', '1', True]
_CONFIG_FALSE = ['no', 'off', 'false', '0', False]
_IFACE_TYPES = [
'eth', 'bond', 'alias', 'clone',
'ipsec', 'dialup', 'bridge', 'slave',
'vlan', 'pppoe', 'source',
]
def _error_msg_iface(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, '|'.join(str(e) for e in expected))
def _error_msg_routes(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, expected)
def _log_default_iface(iface, opt, value):
log.info(
'Using default option -- Interface: %s Option: %s Value: %s',
iface, opt, value
)
def _error_msg_network(option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]'
return msg.format(option, '|'.join(str(e) for e in expected))
def _log_default_network(opt, value):
log.info('Using existing setting -- Setting: %s Value: %s', opt, value)
def _raise_error_iface(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_iface(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_network(option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_network(option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_routes(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_routes(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _read_file(path):
'''
Reads and returns the contents of a text file
'''
try:
with salt.utils.files.flopen(path, 'rb') as contents:
return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]
except (OSError, IOError):
return ''
def _parse_resolve():
'''
Parse /etc/resolv.conf
'''
return salt.utils.dns.parse_resolv(_DEB_RESOLV_FILE)
def _parse_domainname():
'''
Parse /etc/resolv.conf and return domainname
'''
return _parse_resolve().get('domain', '')
def _parse_searchdomain():
'''
Parse /etc/resolv.conf and return searchdomain
'''
return _parse_resolve().get('search', '')
def _parse_hostname():
'''
Parse /etc/hostname and return hostname
'''
contents = _read_file(_DEB_HOSTNAME_FILE)
if contents:
return contents[0].split('\n')[0]
else:
return ''
def _parse_current_network_settings():
'''
Parse /etc/default/networking and return current configuration
'''
opts = salt.utils.odict.OrderedDict()
opts['networking'] = ''
if os.path.isfile(_DEB_NETWORKING_FILE):
with salt.utils.files.fopen(_DEB_NETWORKING_FILE) as contents:
for line in contents:
salt.utils.stringutils.to_unicode(line)
if line.startswith('#'):
continue
elif line.startswith('CONFIGURE_INTERFACES'):
opts['networking'] = line.split('=', 1)[1].strip()
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
opts['hostname'] = hostname
opts['domainname'] = domainname
opts['searchdomain'] = searchdomain
return opts
# def __validator_func(value):
# return (valid: True/False, (transformed) value, error message)
def __ipv4_quad(value):
'''validate an IPv4 address'''
return (salt.utils.validate.net.ipv4_addr(value), value,
'dotted IPv4 address')
def __ipv6(value):
'''validate an IPv6 address'''
return (salt.utils.validate.net.ipv6_addr(value), value,
'IPv6 address')
def __mac(value):
'''validate a mac address'''
return (salt.utils.validate.net.mac(value), value,
'MAC address')
def __anything(value):
return (True, value, None)
def __int(value):
'''validate an integer'''
valid, _value = False, value
try:
_value = int(value)
valid = True
except ValueError:
pass
return (valid, _value, 'integer')
def __float(value):
'''validate a float'''
valid, _value = False, value
try:
_value = float(value)
valid = True
except ValueError:
pass
return (valid, _value, 'float')
def __ipv4_netmask(value):
'''validate an IPv4 dotted quad or integer CIDR netmask'''
valid, errmsg = False, 'dotted quad or integer CIDR (0->32)'
valid, value, _ = __int(value)
if not (valid and 0 <= value <= 32):
valid = salt.utils.validate.net.netmask(value)
return (valid, value, errmsg)
def __ipv6_netmask(value):
'''validate an IPv6 integer netmask'''
valid, errmsg = False, 'IPv6 netmask (0->128)'
valid, value, _ = __int(value)
valid = (valid and 0 <= value <= 128)
return (valid, value, errmsg)
def __within2(value, within=None, errmsg=None, dtype=None):
'''validate that a value is in ``within`` and optionally a ``dtype``'''
valid, _value = False, value
if dtype:
try:
_value = dtype(value) # TODO: this is a bit loose when dtype is a class
valid = _value in within
except ValueError:
pass
else:
valid = _value in within
if errmsg is None:
if dtype:
typename = getattr(dtype, '__name__',
hasattr(dtype, '__class__')
and getattr(dtype.__class__, 'name', dtype))
errmsg = '{0} within \'{1}\''.format(typename, within)
else:
errmsg = 'within \'{0}\''.format(within)
return (valid, _value, errmsg)
def __within(within=None, errmsg=None, dtype=None):
return functools.partial(__within2, within=within,
errmsg=errmsg, dtype=dtype)
def __space_delimited_list(value):
'''validate that a value contains one or more space-delimited values'''
if isinstance(value, six.string_types):
value = value.strip().split()
if hasattr(value, '__iter__') and value != []:
return (True, value, 'space-delimited string')
else:
return (False, value, '{0} is not a valid space-delimited value.\n'.format(value))
SALT_ATTR_TO_DEBIAN_ATTR_MAP = {
'dns': 'dns-nameservers',
'search': 'dns-search',
'hwaddr': 'hwaddress', # TODO: this limits bootp functionality
'ipaddr': 'address',
'ipaddrs': 'addresses',
}
DEBIAN_ATTR_TO_SALT_ATTR_MAP = dict(
(v, k) for (k, v) in six.iteritems(SALT_ATTR_TO_DEBIAN_ATTR_MAP))
# TODO
DEBIAN_ATTR_TO_SALT_ATTR_MAP['address'] = 'address'
DEBIAN_ATTR_TO_SALT_ATTR_MAP['hwaddress'] = 'hwaddress'
IPV4_VALID_PROTO = ['bootp', 'dhcp', 'static', 'manual', 'loopback', 'ppp']
IPV4_ATTR_MAP = {
'proto': __within(IPV4_VALID_PROTO, dtype=six.text_type),
# ipv4 static & manual
'address': __ipv4_quad,
'addresses': __anything,
'netmask': __ipv4_netmask,
'broadcast': __ipv4_quad,
'metric': __int,
'gateway': __ipv4_quad, # supports a colon-delimited list
'pointopoint': __ipv4_quad,
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'link', 'host'], dtype=six.text_type),
# dhcp
'hostname': __anything,
'leasehours': __int,
'leasetime': __int,
'vendor': __anything,
'client': __anything,
# bootp
'bootfile': __anything,
'server': __ipv4_quad,
'hwaddr': __mac,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'dstaddr': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# bond
'slaves': __anything,
# ppp
'provider': __anything,
'unit': __int,
'options': __anything,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
#
'network': __anything, # i don't know what this is
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
IPV6_VALID_PROTO = ['auto', 'loopback', 'static', 'manual',
'dhcp', 'v4tunnel', '6to4']
IPV6_ATTR_MAP = {
'proto': __within(IPV6_VALID_PROTO),
# ipv6 static & manual
'address': __ipv6,
'addresses': __anything,
'netmask': __ipv6_netmask,
'broadcast': __ipv6,
'gateway': __ipv6, # supports a colon-delimited list
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'site', 'link', 'host'], dtype=six.text_type),
# inet6 auto
'privext': __within([0, 1, 2], dtype=int),
'dhcp': __within([0, 1], dtype=int),
# inet6 static & manual & dhcp
'media': __anything,
'accept_ra': __within([0, 1], dtype=int),
'autoconf': __within([0, 1], dtype=int),
'preferred-lifetime': __int,
'dad-attempts': __int, # 0 to disable
'dad-interval': __float,
# bond
'slaves': __anything,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
WIRELESS_ATTR_MAP = {
'wireless-essid': __anything,
'wireless-mode': __anything, # TODO
'wpa-ap-scan': __within([0, 1, 2], dtype=int), # TODO
'wpa-conf': __anything,
'wpa-driver': __anything,
'wpa-group': __anything,
'wpa-key-mgmt': __anything,
'wpa-pairwise': __anything,
'wpa-psk': __anything,
'wpa-proto': __anything, # partial(__within,
'wpa-roam': __anything,
'wpa-ssid': __anything, # TODO
}
ATTRMAPS = {
'inet': [IPV4_ATTR_MAP, WIRELESS_ATTR_MAP],
'inet6': [IPV6_ATTR_MAP, WIRELESS_ATTR_MAP]
}
def _attrmaps_contain_attr(attr):
return (
attr in WIRELESS_ATTR_MAP or
attr in IPV4_ATTR_MAP or
attr in IPV6_ATTR_MAP)
def _parse_interfaces(interface_files=None):
'''
Parse /etc/network/interfaces and return current configured interfaces
'''
if interface_files is None:
interface_files = []
# Add this later.
if os.path.exists(_DEB_NETWORK_DIR):
interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]
if os.path.isfile(_DEB_NETWORK_FILE):
interface_files.insert(0, _DEB_NETWORK_FILE)
adapters = salt.utils.odict.OrderedDict()
method = -1
for interface_file in interface_files:
with salt.utils.files.fopen(interface_file) as interfaces:
# This ensures iface_dict exists, but does not ensure we're not reading a new interface.
iface_dict = {}
for line in interfaces:
line = salt.utils.stringutils.to_unicode(line)
# Identify the clauses by the first word of each line.
# Go to the next line if the current line is a comment
# or all spaces.
if line.lstrip().startswith('#') or line.isspace():
continue
# Parse the iface clause
if line.startswith('iface'):
sline = line.split()
if len(sline) != 4:
msg = 'Interface file malformed: {0}.'
msg = msg.format(sline)
log.error(msg)
raise AttributeError(msg)
iface_name = sline[1]
addrfam = sline[2]
method = sline[3]
# Create item in dict, if not already there
if iface_name not in adapters:
adapters[iface_name] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters[iface_name]:
adapters[iface_name]['data'] = salt.utils.odict.OrderedDict()
if addrfam not in adapters[iface_name]['data']:
adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict()
iface_dict = adapters[iface_name]['data'][addrfam]
iface_dict['addrfam'] = addrfam
iface_dict['proto'] = method
iface_dict['filename'] = interface_file
# Parse the detail clauses.
elif line[0].isspace():
sline = line.split()
# conf file attr: dns-nameservers
# salt states.network attr: dns
attr, valuestr = line.rstrip().split(None, 1)
if _attrmaps_contain_attr(attr):
if '-' in attr:
attrname = attr.replace('-', '_')
else:
attrname = attr
(valid, value, errmsg) = _validate_interface_option(
attr, valuestr, addrfam)
if attrname == 'address' and 'address' in iface_dict:
if 'addresses' not in iface_dict:
iface_dict['addresses'] = []
iface_dict['addresses'].append(value)
else:
iface_dict[attrname] = value
elif attr in _REV_ETHTOOL_CONFIG_OPTS:
if 'ethtool' not in iface_dict:
iface_dict['ethtool'] = salt.utils.odict.OrderedDict()
iface_dict['ethtool'][attr] = valuestr
elif attr.startswith('bond'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bonding' not in iface_dict:
iface_dict['bonding'] = salt.utils.odict.OrderedDict()
iface_dict['bonding'][opt] = valuestr
elif attr.startswith('bridge'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bridging' not in iface_dict:
iface_dict['bridging'] = salt.utils.odict.OrderedDict()
iface_dict['bridging'][opt] = valuestr
elif attr in ['up', 'pre-up', 'post-up',
'down', 'pre-down', 'post-down']:
cmd = valuestr
cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr))
if cmd_key not in iface_dict:
iface_dict[cmd_key] = []
iface_dict[cmd_key].append(cmd)
elif line.startswith('auto'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['enabled'] = True
elif line.startswith('allow-hotplug'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['hotplug'] = True
elif line.startswith('source'):
if 'source' not in adapters:
adapters['source'] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters['source']:
adapters['source']['data'] = salt.utils.odict.OrderedDict()
adapters['source']['data']['sources'] = []
adapters['source']['data']['sources'].append(line.split()[1])
# Return a sorted list of the keys for bond, bridge and ethtool options to
# ensure a consistent order
for iface_name in adapters:
if iface_name == 'source':
continue
if 'data' not in adapters[iface_name]:
msg = 'Interface file malformed for interface: {0}.'.format(iface_name)
log.error(msg)
adapters.pop(iface_name)
continue
for opt in ['ethtool', 'bonding', 'bridging']:
for inet in ['inet', 'inet6']:
if inet in adapters[iface_name]['data']:
if opt in adapters[iface_name]['data'][inet]:
opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys())
adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys
return adapters
def _parse_ethtool_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
if 'autoneg' in opts:
if opts['autoneg'] in _CONFIG_TRUE:
config.update({'autoneg': 'on'})
elif opts['autoneg'] in _CONFIG_FALSE:
config.update({'autoneg': 'off'})
else:
_raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE)
if 'duplex' in opts:
valid = ['full', 'half']
if opts['duplex'] in valid:
config.update({'duplex': opts['duplex']})
else:
_raise_error_iface(iface, 'duplex', valid)
if 'speed' in opts:
valid = ['10', '100', '1000', '10000']
if six.text_type(opts['speed']) in valid:
config.update({'speed': opts['speed']})
else:
_raise_error_iface(iface, opts['speed'], valid)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'on'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'off'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_ethtool_pppoe_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
for opt in _DEB_CONFIG_PPPOE_OPTS:
if opt in opts:
config[opt] = opts[opt]
if 'provider' in opts and not opts['provider']:
_raise_error_iface(iface, 'provider', _CONFIG_TRUE + _CONFIG_FALSE)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('noipdefault', 'usepeerdns', 'defaultroute', 'hide-password', 'noauth', 'persist', 'noaccomp'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'True'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'False'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_settings_bond(opts, iface):
'''
Filters given options and outputs valid settings for requested
operation. If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond_def = {
# 803.ad aggregation selection logic
# 0 for stable (default)
# 1 for bandwidth
# 2 for count
'ad_select': '0',
# Max number of transmit queues (default = 16)
'tx_queues': '16',
# Link monitoring in milliseconds. Most NICs support this
'miimon': '100',
# ARP interval in milliseconds
'arp_interval': '250',
# Delay before considering link down in milliseconds (miimon * 2)
'downdelay': '200',
# lacp_rate 0: Slow - every 30 seconds
# lacp_rate 1: Fast - every 1 second
'lacp_rate': '0',
# Max bonds for this driver
'max_bonds': '1',
# Specifies the time, in milliseconds, to wait before
# enabling a slave after a link recovery has been
# detected. Only used with miimon.
'updelay': '0',
# Used with miimon.
# On: driver sends mii
# Off: ethtool sends mii
'use_carrier': 'on',
# Default. Don't change unless you know what you are doing.
'xmit_hash_policy': 'layer2',
}
if opts['mode'] in ['balance-rr', '0']:
log.info('Device: %s Bonding Mode: load balancing (round-robin)', iface)
return _parse_settings_bond_0(opts, iface, bond_def)
elif opts['mode'] in ['active-backup', '1']:
log.info('Device: %s Bonding Mode: fault-tolerance (active-backup)', iface)
return _parse_settings_bond_1(opts, iface, bond_def)
elif opts['mode'] in ['balance-xor', '2']:
log.info('Device: %s Bonding Mode: load balancing (xor)', iface)
return _parse_settings_bond_2(opts, iface, bond_def)
elif opts['mode'] in ['broadcast', '3']:
log.info('Device: %s Bonding Mode: fault-tolerance (broadcast)', iface)
return _parse_settings_bond_3(opts, iface, bond_def)
elif opts['mode'] in ['802.3ad', '4']:
log.info('Device: %s Bonding Mode: IEEE 802.3ad Dynamic link '
'aggregation', iface)
return _parse_settings_bond_4(opts, iface, bond_def)
elif opts['mode'] in ['balance-tlb', '5']:
log.info('Device: %s Bonding Mode: transmit load balancing', iface)
return _parse_settings_bond_5(opts, iface, bond_def)
elif opts['mode'] in ['balance-alb', '6']:
log.info('Device: %s Bonding Mode: adaptive load balancing', iface)
return _parse_settings_bond_6(opts, iface, bond_def)
else:
valid = [
'0', '1', '2', '3', '4', '5', '6',
'balance-rr', 'active-backup', 'balance-xor',
'broadcast', '802.3ad', 'balance-tlb', 'balance-alb'
]
_raise_error_iface(iface, 'mode', valid)
def _parse_settings_bond_0(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond0.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '0'}
# ARP targets in n.n.n.n form
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
return bond
def _parse_settings_bond_1(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '1'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
if not (__grains__['os'] == "Ubuntu" and __grains__['osrelease_info'][0] >= 16):
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_2(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond2.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '2'}
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_3(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond3.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '3'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_4(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond4.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '4'}
for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']:
if binding in opts:
if binding == 'lacp_rate':
if opts[binding] == 'fast':
opts.update({binding: '1'})
if opts[binding] == 'slow':
opts.update({binding: '0'})
valid = ['fast', '1', 'slow', '0']
else:
valid = ['integer']
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, valid)
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_5(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond5.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '5'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_settings_bond_6(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond6.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '6'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_bridge_opts(opts, iface):
'''
Filters given options and outputs valid settings for BRIDGING_OPTS
If an option has a value that is not expected, this
function will log the Interface, Setting and what was expected.
'''
config = {}
if 'ports' in opts:
if isinstance(opts['ports'], list):
opts['ports'] = ' '.join(opts['ports'])
config.update({'ports': opts['ports']})
for opt in ['ageing', 'fd', 'gcint', 'hello', 'maxage']:
if opt in opts:
try:
float(opts[opt])
config.update({opt: opts[opt]})
except ValueError:
_raise_error_iface(iface, opt, ['float'])
for opt in ['bridgeprio', 'maxwait']:
if opt in opts:
if isinstance(opts[opt], int):
config.update({opt: opts[opt]})
else:
_raise_error_iface(iface, opt, ['integer'])
if 'hw' in opts:
# match 12 hex digits with either : or - as separators between pairs
if re.match('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$',
opts['hw'].lower()):
config.update({'hw': opts['hw']})
else:
_raise_error_iface(iface, 'hw', ['valid MAC address'])
for opt in ['pathcost', 'portprio']:
if opt in opts:
try:
port, cost_or_prio = opts[opt].split()
int(cost_or_prio)
config.update({opt: '{0} {1}'.format(port, cost_or_prio)})
except ValueError:
_raise_error_iface(iface, opt, ['interface integer'])
if 'stp' in opts:
if opts['stp'] in _CONFIG_TRUE:
config.update({'stp': 'on'})
elif opts['stp'] in _CONFIG_FALSE:
config.update({'stp': 'off'})
else:
_raise_error_iface(iface, 'stp', _CONFIG_TRUE + _CONFIG_FALSE)
if 'waitport' in opts:
if isinstance(opts['waitport'], int):
config.update({'waitport': opts['waitport']})
else:
values = opts['waitport'].split()
waitport_time = values.pop(0)
if waitport_time.isdigit() and values:
config.update({
'waitport': '{0} {1}'.format(
waitport_time, ' '.join(values)
)
})
else:
_raise_error_iface(iface, opt, ['integer [interfaces]'])
return config
def _parse_settings_eth(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['inet'] = salt.utils.odict.OrderedDict()
iface_data['inet6'] = salt.utils.odict.OrderedDict()
if enabled:
adapters[iface]['enabled'] = True
if opts.get('hotplug', False):
adapters[iface]['hotplug'] = True
if opts.get('enable_ipv6', None) and opts.get('iface_type', '') == 'vlan':
iface_data['inet6']['vlan_raw_device'] = (
re.sub(r'\.\d*', '', iface))
for addrfam in ['inet', 'inet6']:
if iface_type not in ['bridge']:
tmp_ethtool = _parse_ethtool_opts(opts, iface)
if tmp_ethtool:
ethtool = {}
for item in tmp_ethtool:
ethtool[_ETHTOOL_CONFIG_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['ethtool'] = ethtool
# return a list of sorted keys to ensure consistent order
iface_data[addrfam]['ethtool_keys'] = sorted(ethtool)
if iface_type == 'bridge':
bridging = _parse_bridge_opts(opts, iface)
if bridging:
iface_data[addrfam]['bridging'] = bridging
iface_data[addrfam]['bridging_keys'] = sorted(bridging)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'bond':
bonding = _parse_settings_bond(opts, iface)
if bonding:
iface_data[addrfam]['bonding'] = bonding
iface_data[addrfam]['bonding']['slaves'] = opts['slaves']
iface_data[addrfam]['bonding_keys'] = sorted(bonding)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'slave':
adapters[iface]['master'] = opts['master']
opts['proto'] = 'manual'
iface_data[addrfam]['master'] = adapters[iface]['master']
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'vlan':
iface_data[addrfam]['vlan_raw_device'] = re.sub(r'\.\d*', '', iface)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'pppoe':
tmp_ethtool = _parse_ethtool_pppoe_opts(opts, iface)
if tmp_ethtool:
for item in tmp_ethtool:
adapters[iface]['data'][addrfam][_DEB_CONFIG_PPPOE_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['addrfam'] = addrfam
opts.pop('mode', None)
for opt, val in opts.items():
inet = None
if opt.startswith('ipv4'):
opt = opt[4:]
inet = 'inet'
iface_data['inet']['addrfam'] = 'inet'
elif opt.startswith('ipv6'):
iface_data['inet6']['addrfam'] = 'inet6'
opt = opt[4:]
inet = 'inet6'
elif opt in ['ipaddr', 'address', 'ipaddresses', 'addresses', 'gateway', 'proto']:
iface_data['inet']['addrfam'] = 'inet'
inet = 'inet'
_opt = SALT_ATTR_TO_DEBIAN_ATTR_MAP.get(opt, opt)
_debopt = _opt.replace('-', '_')
for addrfam in ['inet', 'inet6']:
(valid, value, errmsg) = _validate_interface_option(_opt, val, addrfam=addrfam)
if not valid:
continue
if inet is None and _debopt not in iface_data[addrfam]:
iface_data[addrfam][_debopt] = value
elif inet == addrfam:
iface_data[addrfam][_debopt] = value
for opt in ['up_cmds', 'pre_up_cmds', 'post_up_cmds',
'down_cmds', 'pre_down_cmds', 'post_down_cmds']:
if opt in opts:
iface_data['inet'][opt] = opts[opt]
iface_data['inet6'][opt] = opts[opt]
# Remove incomplete/disabled inet blocks
for (addrfam, opt) in [('inet', 'enable_ipv4'), ('inet6', 'enable_ipv6')]:
if opts.get(opt, None) is False:
iface_data.pop(addrfam)
elif iface_data[addrfam].get('addrfam', '') != addrfam:
iface_data.pop(addrfam)
return adapters
def _parse_settings_source(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['sources'] = [opts['source']]
return adapters
def _parse_network_settings(opts, current):
'''
Filters given options and outputs valid settings for
the global network settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
current = dict((k.lower(), v) for (k, v) in six.iteritems(current))
result = {}
valid = _CONFIG_TRUE + _CONFIG_FALSE
if 'enabled' not in opts:
try:
opts['networking'] = current['networking']
_log_default_network('networking', current['networking'])
except ValueError:
_raise_error_network('networking', valid)
else:
opts['networking'] = opts['enabled']
if opts['networking'] in valid:
if opts['networking'] in _CONFIG_TRUE:
result['networking'] = 'yes'
elif opts['networking'] in _CONFIG_FALSE:
result['networking'] = 'no'
else:
_raise_error_network('networking', valid)
if 'hostname' not in opts:
try:
opts['hostname'] = current['hostname']
_log_default_network('hostname', current['hostname'])
except ValueError:
_raise_error_network('hostname', ['server1.example.com'])
if opts['hostname']:
result['hostname'] = opts['hostname']
else:
_raise_error_network('hostname', ['server1.example.com'])
if 'search' in opts:
result['search'] = opts['search']
return result
def _parse_routes(iface, opts):
'''
Filters given options and outputs valid settings for
the route settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
result = {}
if 'routes' not in opts:
_raise_error_routes(iface, 'routes', 'List of routes')
for opt in opts:
result[opt] = opts[opt]
return result
def _write_file(iface, data, folder, pattern):
'''
Writes a file to disk
'''
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
return filename
def _write_file_routes(iface, data, folder, pattern):
'''
Writes a file to disk
'''
# ifup / ifdown is executing given folder via run-parts.
# according to run-parts man-page, only filenames with this pattern are
# executed: (^[a-zA-Z0-9_-]+$)
# In order to make the routes file work for vlan interfaces
# (default would have been in example /etc/network/if-up.d/route-bond0.12)
# these dots in the iface name need to be replaced by underscores, so it
# can be executed by run-parts
iface = iface.replace('.', '_')
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
__salt__['file.set_mode'](filename, '0755')
return filename
def _write_file_network(data, filename, create=False):
'''
Writes a file to disk
If file does not exist, only create if create
argument is True
'''
if not os.path.exists(filename) and not create:
msg = '{0} cannot be written. {0} does not exist\
and create is set to False'
msg = msg.format(filename)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
def _read_temp(data):
'''
Return what would be written to disk
'''
tout = StringIO()
tout.write(data)
tout.seek(0)
output = tout.readlines()
tout.close()
return output
def _read_temp_ifaces(iface, data):
'''
Return what would be written to disk for interfaces
'''
try:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': data})
# Return as an array so the difflib works
return [item + '\n' for item in ifcfg.split('\n')]
def _write_file_ifaces(iface, data, **settings):
'''
Writes a file to disk
'''
try:
eth_template = JINJA.get_template('debian_eth.jinja')
source_template = JINJA.get_template('debian_source.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
# Read /etc/network/interfaces into a dict
adapters = _parse_interfaces()
# Apply supplied settings over on-disk settings
adapters[iface] = data
ifcfg = ''
for adapter in adapters:
if 'type' in adapters[adapter] and adapters[adapter]['type'] == 'source':
tmp = source_template.render({'name': adapter, 'data': adapters[adapter]})
else:
tmp = eth_template.render({'name': adapter, 'data': adapters[adapter]})
ifcfg = ifcfg + tmp
if adapter == iface:
saved_ifcfg = tmp
_SEPARATE_FILE = False
if 'filename' in settings:
if not settings['filename'].startswith('/'):
filename = '{0}/{1}'.format(_DEB_NETWORK_DIR, settings['filename'])
else:
filename = settings['filename']
_SEPARATE_FILE = True
else:
if 'filename' in adapters[adapter]['data']:
filename = adapters[adapter]['data']
else:
filename = _DEB_NETWORK_FILE
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
if _SEPARATE_FILE:
fout.write(salt.utils.stringutils.to_str(saved_ifcfg))
else:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return saved_ifcfg.split('\n')
def _write_file_ppp_ifaces(iface, data):
'''
Writes a file to disk
'''
try:
template = JINJA.get_template('debian_ppp_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_ppp_eth.jinja')
return ''
adapters = _parse_interfaces()
adapters[iface] = data
ifcfg = ''
tmp = template.render({'data': adapters[iface]})
ifcfg = tmp + ifcfg
filename = _DEB_PPP_DIR + '/' + adapters[iface]['data']['inet']['provider']
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.fopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return filename
def build_bond(iface, **settings):
'''
Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb
'''
deb_major = __grains__['osrelease'][:1]
opts = _parse_settings_bond(settings, iface)
try:
template = JINJA.get_template('conf.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template conf.jinja')
return ''
data = template.render({'name': iface, 'bonding': opts})
if 'test' in settings and settings['test']:
return _read_temp(data)
_write_file(iface, data, _DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
if deb_major == '5':
for line_type in ('alias', 'options'):
cmd = ['sed', '-i', '-e', r'/^{0}\s{1}.*/d'.format(line_type, iface),
'/etc/modprobe.conf']
__salt__['cmd.run'](cmd, python_shell=False)
__salt__['file.append']('/etc/modprobe.conf', path)
# Load kernel module
__salt__['kmod.load']('bonding')
# install ifenslave-2.6
__salt__['pkg.install']('ifenslave-2.6')
return _read_file(path)
def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'vlan':
settings['vlan'] = 'yes'
__salt__['pkg.install']('vlan')
elif iface_type == 'pppoe':
settings['pppoe'] = 'yes'
if not __salt__['pkg.version']('ppp'):
inst = __salt__['pkg.install']('ppp')
elif iface_type == 'bond':
if 'slaves' not in settings:
msg = 'slaves is a required setting for bond interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'bridge':
if 'ports' not in settings:
msg = (
'ports is a required setting for bridge interfaces on Debian '
'or Ubuntu based systems'
)
log.error(msg)
raise AttributeError(msg)
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'pppoe']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
if iface_type in ['source']:
opts = _parse_settings_source(settings, iface_type, enabled, iface)
if 'test' in settings and settings['test']:
return _read_temp_ifaces(iface, opts[iface])
ifcfg = _write_file_ifaces(iface, opts[iface], **settings)
if iface_type == 'pppoe':
_write_file_ppp_ifaces(iface, opts[iface])
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg]
def build_routes(iface, **settings):
'''
Add route scripts for a network interface using up commands.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
'''
opts = _parse_routes(iface, settings)
try:
template = JINJA.get_template('route_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template route_eth.jinja')
return ''
add_routecfg = template.render(route_type='add',
routes=opts['routes'],
iface=iface)
del_routecfg = template.render(route_type='del',
routes=opts['routes'],
iface=iface)
if 'test' in settings and settings['test']:
return _read_temp(add_routecfg + del_routecfg)
filename = _write_file_routes(iface,
add_routecfg,
_DEB_NETWORK_UP_DIR,
'route-{0}')
results = _read_file(filename)
filename = _write_file_routes(iface,
del_routecfg,
_DEB_NETWORK_DOWN_DIR,
'route-{0}')
results += _read_file(filename)
return results
def down(iface, iface_type):
'''
Shutdown a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.down eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought down.
if iface_type not in ['slave', 'source']:
return __salt__['cmd.run'](['ifdown', iface])
return None
def get_bond(iface):
'''
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
'''
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
return _read_file(path)
def get_interface(iface):
'''
Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
adapters = _parse_interfaces()
if iface in adapters:
try:
if iface == 'source':
template = JINJA.get_template('debian_source.jinja')
else:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': adapters[iface]})
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg.split('\n')]
else:
return []
def up(iface, iface_type): # pylint: disable=C0103
'''
Start up a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.up eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought up.
if iface_type not in ('slave', 'source'):
return __salt__['cmd.run'](['ifup', iface])
return None
def get_network_settings():
'''
Return the contents of the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_network_settings
'''
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
settings = {}
if __salt__['service.available']('networking'):
if __salt__['service.status']('networking'):
settings['networking'] = "yes"
else:
settings['networking'] = "no"
else:
settings['networking'] = "no"
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
settings['hostname'] = hostname
settings['domainname'] = domainname
settings['searchdomain'] = searchdomain
else:
settings = _parse_current_network_settings()
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(settings)
return _read_temp(network)
def get_routes(iface):
'''
Return the routes for the interface
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0
'''
filename = os.path.join(_DEB_NETWORK_UP_DIR, 'route-{0}'.format(iface))
results = _read_file(filename)
filename = os.path.join(_DEB_NETWORK_DOWN_DIR, 'route-{0}'.format(iface))
results += _read_file(filename)
return results
def apply_network_settings(**settings):
'''
Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings
'''
if 'require_reboot' not in settings:
settings['require_reboot'] = False
if 'apply_hostname' not in settings:
settings['apply_hostname'] = False
hostname_res = True
if settings['apply_hostname'] in _CONFIG_TRUE:
if 'hostname' in settings:
hostname_res = __salt__['network.mod_hostname'](settings['hostname'])
else:
log.warning(
'The network state sls is trying to apply hostname '
'changes but no hostname is defined.'
)
hostname_res = False
res = True
if settings['require_reboot'] in _CONFIG_TRUE:
log.warning(
'The network state sls is requiring a reboot of the system to '
'properly apply network configuration.'
)
res = True
else:
stop = __salt__['service.stop']('networking')
time.sleep(2)
res = stop and __salt__['service.start']('networking')
return hostname_res and res
def build_network_settings(**settings):
'''
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
'''
changes = []
# Read current configuration and store default values
current_network_settings = _parse_current_network_settings()
# Build settings
opts = _parse_network_settings(settings, current_network_settings)
# Ubuntu has moved away from /etc/default/networking
# beginning with the 12.04 release so we disable or enable
# the networking related services on boot
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
if opts['networking'] == 'yes':
service_cmd = 'service.enable'
else:
service_cmd = 'service.disable'
if __salt__['service.available']('NetworkManager'):
__salt__[service_cmd]('NetworkManager')
if __salt__['service.available']('networking'):
__salt__[service_cmd]('networking')
else:
try:
template = JINJA.get_template('network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template network.jinja')
return ''
network = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(network)
# Write settings
_write_file_network(network, _DEB_NETWORKING_FILE, True)
# Get hostname and domain from opts
sline = opts['hostname'].split('.', 1)
opts['hostname'] = sline[0]
current_domainname = current_network_settings['domainname']
current_searchdomain = current_network_settings['searchdomain']
new_domain = False
if len(sline) > 1:
new_domainname = sline[1]
if new_domainname != current_domainname:
domainname = new_domainname
opts['domainname'] = new_domainname
new_domain = True
else:
domainname = current_domainname
opts['domainname'] = domainname
else:
domainname = current_domainname
opts['domainname'] = domainname
new_search = False
if 'search' in opts:
new_searchdomain = opts['search']
if new_searchdomain != current_searchdomain:
searchdomain = new_searchdomain
opts['searchdomain'] = new_searchdomain
new_search = True
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
# If the domain changes, then we should write the resolv.conf file.
if new_domain or new_search:
# Look for existing domain line and update if necessary
resolve = _parse_resolve()
domain_prog = re.compile(r'domain\s+')
search_prog = re.compile(r'search\s+')
new_contents = []
for item in _read_file(_DEB_RESOLV_FILE):
if domain_prog.match(item):
item = 'domain {0}'.format(domainname)
elif search_prog.match(item):
item = 'search {0}'.format(searchdomain)
new_contents.append(item)
# A domain line didn't exist so we'll add one in
# with the new domainname
if 'domain' not in resolve:
new_contents.insert(0, 'domain {0}' . format(domainname))
# A search line didn't exist so we'll add one in
# with the new search domain
if 'search' not in resolve:
new_contents.insert('domain' in resolve, 'search {0}'.format(searchdomain))
new_resolv = '\n'.join(new_contents)
# Write /etc/resolv.conf
if not ('test' in settings and settings['test']):
_write_file_network(new_resolv, _DEB_RESOLV_FILE)
# used for returning the results back
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(opts)
changes.extend(_read_temp(network))
return changes
|
saltstack/salt
|
salt/modules/debian_ip.py
|
_parse_interfaces
|
python
|
def _parse_interfaces(interface_files=None):
'''
Parse /etc/network/interfaces and return current configured interfaces
'''
if interface_files is None:
interface_files = []
# Add this later.
if os.path.exists(_DEB_NETWORK_DIR):
interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]
if os.path.isfile(_DEB_NETWORK_FILE):
interface_files.insert(0, _DEB_NETWORK_FILE)
adapters = salt.utils.odict.OrderedDict()
method = -1
for interface_file in interface_files:
with salt.utils.files.fopen(interface_file) as interfaces:
# This ensures iface_dict exists, but does not ensure we're not reading a new interface.
iface_dict = {}
for line in interfaces:
line = salt.utils.stringutils.to_unicode(line)
# Identify the clauses by the first word of each line.
# Go to the next line if the current line is a comment
# or all spaces.
if line.lstrip().startswith('#') or line.isspace():
continue
# Parse the iface clause
if line.startswith('iface'):
sline = line.split()
if len(sline) != 4:
msg = 'Interface file malformed: {0}.'
msg = msg.format(sline)
log.error(msg)
raise AttributeError(msg)
iface_name = sline[1]
addrfam = sline[2]
method = sline[3]
# Create item in dict, if not already there
if iface_name not in adapters:
adapters[iface_name] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters[iface_name]:
adapters[iface_name]['data'] = salt.utils.odict.OrderedDict()
if addrfam not in adapters[iface_name]['data']:
adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict()
iface_dict = adapters[iface_name]['data'][addrfam]
iface_dict['addrfam'] = addrfam
iface_dict['proto'] = method
iface_dict['filename'] = interface_file
# Parse the detail clauses.
elif line[0].isspace():
sline = line.split()
# conf file attr: dns-nameservers
# salt states.network attr: dns
attr, valuestr = line.rstrip().split(None, 1)
if _attrmaps_contain_attr(attr):
if '-' in attr:
attrname = attr.replace('-', '_')
else:
attrname = attr
(valid, value, errmsg) = _validate_interface_option(
attr, valuestr, addrfam)
if attrname == 'address' and 'address' in iface_dict:
if 'addresses' not in iface_dict:
iface_dict['addresses'] = []
iface_dict['addresses'].append(value)
else:
iface_dict[attrname] = value
elif attr in _REV_ETHTOOL_CONFIG_OPTS:
if 'ethtool' not in iface_dict:
iface_dict['ethtool'] = salt.utils.odict.OrderedDict()
iface_dict['ethtool'][attr] = valuestr
elif attr.startswith('bond'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bonding' not in iface_dict:
iface_dict['bonding'] = salt.utils.odict.OrderedDict()
iface_dict['bonding'][opt] = valuestr
elif attr.startswith('bridge'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bridging' not in iface_dict:
iface_dict['bridging'] = salt.utils.odict.OrderedDict()
iface_dict['bridging'][opt] = valuestr
elif attr in ['up', 'pre-up', 'post-up',
'down', 'pre-down', 'post-down']:
cmd = valuestr
cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr))
if cmd_key not in iface_dict:
iface_dict[cmd_key] = []
iface_dict[cmd_key].append(cmd)
elif line.startswith('auto'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['enabled'] = True
elif line.startswith('allow-hotplug'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['hotplug'] = True
elif line.startswith('source'):
if 'source' not in adapters:
adapters['source'] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters['source']:
adapters['source']['data'] = salt.utils.odict.OrderedDict()
adapters['source']['data']['sources'] = []
adapters['source']['data']['sources'].append(line.split()[1])
# Return a sorted list of the keys for bond, bridge and ethtool options to
# ensure a consistent order
for iface_name in adapters:
if iface_name == 'source':
continue
if 'data' not in adapters[iface_name]:
msg = 'Interface file malformed for interface: {0}.'.format(iface_name)
log.error(msg)
adapters.pop(iface_name)
continue
for opt in ['ethtool', 'bonding', 'bridging']:
for inet in ['inet', 'inet6']:
if inet in adapters[iface_name]['data']:
if opt in adapters[iface_name]['data'][inet]:
opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys())
adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys
return adapters
|
Parse /etc/network/interfaces and return current configured interfaces
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_ip.py#L548-L692
|
[
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n",
"def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n",
"def pop(self, key, default=__marker):\n '''od.pop(k[,d]) -> v, remove specified key and return the corresponding value.\n If key is not found, d is returned if given, otherwise KeyError is raised.\n\n '''\n if key in self:\n result = self[key]\n del self[key]\n return result\n if default is self.__marker:\n raise KeyError(key)\n return default\n"
] |
# -*- coding: utf-8 -*-
'''
The networking module for Debian-based distros
References:
* http://www.debian.org/doc/manuals/debian-reference/ch05.en.html
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import functools
import logging
import os.path
import os
import re
import time
# Import third party libs
import jinja2
import jinja2.exceptions
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error,no-name-in-module
# Import salt libs
import salt.utils.dns
import salt.utils.files
import salt.utils.odict
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.validate.net
# Set up logging
log = logging.getLogger(__name__)
# Set up template environment
JINJA = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'debian_ip')
)
)
# Define the module's virtual name
__virtualname__ = 'ip'
def __virtual__():
'''
Confine this module to Debian-based distros
'''
if __grains__['os_family'] == 'Debian':
return __virtualname__
return (False, 'The debian_ip module could not be loaded: '
'unsupported OS family')
_ETHTOOL_CONFIG_OPTS = {
'speed': 'link-speed',
'duplex': 'link-duplex',
'autoneg': 'ethernet-autoneg',
'ethernet-port': 'ethernet-port',
'wol': 'ethernet-wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'rx': 'offload-rx',
'tx': 'offload-tx',
'sg': 'offload-sg',
'tso': 'offload-tso',
'ufo': 'offload-ufo',
'gso': 'offload-gso',
'gro': 'offload-gro',
'lro': 'offload-lro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_REV_ETHTOOL_CONFIG_OPTS = {
'link-speed': 'speed',
'link-duplex': 'duplex',
'ethernet-autoneg': 'autoneg',
'ethernet-port': 'ethernet-port',
'ethernet-wol': 'wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'offload-rx': 'rx',
'offload-tx': 'tx',
'offload-sg': 'sg',
'offload-tso': 'tso',
'offload-ufo': 'ufo',
'offload-gso': 'gso',
'offload-lro': 'lro',
'offload-gro': 'gro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_DEB_CONFIG_PPPOE_OPTS = {
'user': 'user',
'password': 'password',
'provider': 'provider',
'pppoe_iface': 'pppoe_iface',
'noipdefault': 'noipdefault',
'usepeerdns': 'usepeerdns',
'defaultroute': 'defaultroute',
'holdoff': 'holdoff',
'maxfail': 'maxfail',
'hide-password': 'hide-password',
'lcp-echo-interval': 'lcp-echo-interval',
'lcp-echo-failure': 'lcp-echo-failure',
'connect': 'connect',
'noauth': 'noauth',
'persist': 'persist',
'mtu': 'mtu',
'noaccomp': 'noaccomp',
'linkname': 'linkname',
}
_DEB_ROUTES_FILE = '/etc/network/routes'
_DEB_NETWORK_FILE = '/etc/network/interfaces'
_DEB_NETWORK_DIR = '/etc/network/interfaces.d/'
_DEB_NETWORK_UP_DIR = '/etc/network/if-up.d/'
_DEB_NETWORK_DOWN_DIR = '/etc/network/if-down.d/'
_DEB_NETWORK_CONF_FILES = '/etc/modprobe.d/'
_DEB_NETWORKING_FILE = '/etc/default/networking'
_DEB_HOSTNAME_FILE = '/etc/hostname'
_DEB_RESOLV_FILE = '/etc/resolv.conf'
_DEB_PPP_DIR = '/etc/ppp/peers/'
_CONFIG_TRUE = ['yes', 'on', 'true', '1', True]
_CONFIG_FALSE = ['no', 'off', 'false', '0', False]
_IFACE_TYPES = [
'eth', 'bond', 'alias', 'clone',
'ipsec', 'dialup', 'bridge', 'slave',
'vlan', 'pppoe', 'source',
]
def _error_msg_iface(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, '|'.join(str(e) for e in expected))
def _error_msg_routes(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, expected)
def _log_default_iface(iface, opt, value):
log.info(
'Using default option -- Interface: %s Option: %s Value: %s',
iface, opt, value
)
def _error_msg_network(option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]'
return msg.format(option, '|'.join(str(e) for e in expected))
def _log_default_network(opt, value):
log.info('Using existing setting -- Setting: %s Value: %s', opt, value)
def _raise_error_iface(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_iface(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_network(option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_network(option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_routes(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_routes(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _read_file(path):
'''
Reads and returns the contents of a text file
'''
try:
with salt.utils.files.flopen(path, 'rb') as contents:
return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]
except (OSError, IOError):
return ''
def _parse_resolve():
'''
Parse /etc/resolv.conf
'''
return salt.utils.dns.parse_resolv(_DEB_RESOLV_FILE)
def _parse_domainname():
'''
Parse /etc/resolv.conf and return domainname
'''
return _parse_resolve().get('domain', '')
def _parse_searchdomain():
'''
Parse /etc/resolv.conf and return searchdomain
'''
return _parse_resolve().get('search', '')
def _parse_hostname():
'''
Parse /etc/hostname and return hostname
'''
contents = _read_file(_DEB_HOSTNAME_FILE)
if contents:
return contents[0].split('\n')[0]
else:
return ''
def _parse_current_network_settings():
'''
Parse /etc/default/networking and return current configuration
'''
opts = salt.utils.odict.OrderedDict()
opts['networking'] = ''
if os.path.isfile(_DEB_NETWORKING_FILE):
with salt.utils.files.fopen(_DEB_NETWORKING_FILE) as contents:
for line in contents:
salt.utils.stringutils.to_unicode(line)
if line.startswith('#'):
continue
elif line.startswith('CONFIGURE_INTERFACES'):
opts['networking'] = line.split('=', 1)[1].strip()
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
opts['hostname'] = hostname
opts['domainname'] = domainname
opts['searchdomain'] = searchdomain
return opts
# def __validator_func(value):
# return (valid: True/False, (transformed) value, error message)
def __ipv4_quad(value):
'''validate an IPv4 address'''
return (salt.utils.validate.net.ipv4_addr(value), value,
'dotted IPv4 address')
def __ipv6(value):
'''validate an IPv6 address'''
return (salt.utils.validate.net.ipv6_addr(value), value,
'IPv6 address')
def __mac(value):
'''validate a mac address'''
return (salt.utils.validate.net.mac(value), value,
'MAC address')
def __anything(value):
return (True, value, None)
def __int(value):
'''validate an integer'''
valid, _value = False, value
try:
_value = int(value)
valid = True
except ValueError:
pass
return (valid, _value, 'integer')
def __float(value):
'''validate a float'''
valid, _value = False, value
try:
_value = float(value)
valid = True
except ValueError:
pass
return (valid, _value, 'float')
def __ipv4_netmask(value):
'''validate an IPv4 dotted quad or integer CIDR netmask'''
valid, errmsg = False, 'dotted quad or integer CIDR (0->32)'
valid, value, _ = __int(value)
if not (valid and 0 <= value <= 32):
valid = salt.utils.validate.net.netmask(value)
return (valid, value, errmsg)
def __ipv6_netmask(value):
'''validate an IPv6 integer netmask'''
valid, errmsg = False, 'IPv6 netmask (0->128)'
valid, value, _ = __int(value)
valid = (valid and 0 <= value <= 128)
return (valid, value, errmsg)
def __within2(value, within=None, errmsg=None, dtype=None):
'''validate that a value is in ``within`` and optionally a ``dtype``'''
valid, _value = False, value
if dtype:
try:
_value = dtype(value) # TODO: this is a bit loose when dtype is a class
valid = _value in within
except ValueError:
pass
else:
valid = _value in within
if errmsg is None:
if dtype:
typename = getattr(dtype, '__name__',
hasattr(dtype, '__class__')
and getattr(dtype.__class__, 'name', dtype))
errmsg = '{0} within \'{1}\''.format(typename, within)
else:
errmsg = 'within \'{0}\''.format(within)
return (valid, _value, errmsg)
def __within(within=None, errmsg=None, dtype=None):
return functools.partial(__within2, within=within,
errmsg=errmsg, dtype=dtype)
def __space_delimited_list(value):
'''validate that a value contains one or more space-delimited values'''
if isinstance(value, six.string_types):
value = value.strip().split()
if hasattr(value, '__iter__') and value != []:
return (True, value, 'space-delimited string')
else:
return (False, value, '{0} is not a valid space-delimited value.\n'.format(value))
SALT_ATTR_TO_DEBIAN_ATTR_MAP = {
'dns': 'dns-nameservers',
'search': 'dns-search',
'hwaddr': 'hwaddress', # TODO: this limits bootp functionality
'ipaddr': 'address',
'ipaddrs': 'addresses',
}
DEBIAN_ATTR_TO_SALT_ATTR_MAP = dict(
(v, k) for (k, v) in six.iteritems(SALT_ATTR_TO_DEBIAN_ATTR_MAP))
# TODO
DEBIAN_ATTR_TO_SALT_ATTR_MAP['address'] = 'address'
DEBIAN_ATTR_TO_SALT_ATTR_MAP['hwaddress'] = 'hwaddress'
IPV4_VALID_PROTO = ['bootp', 'dhcp', 'static', 'manual', 'loopback', 'ppp']
IPV4_ATTR_MAP = {
'proto': __within(IPV4_VALID_PROTO, dtype=six.text_type),
# ipv4 static & manual
'address': __ipv4_quad,
'addresses': __anything,
'netmask': __ipv4_netmask,
'broadcast': __ipv4_quad,
'metric': __int,
'gateway': __ipv4_quad, # supports a colon-delimited list
'pointopoint': __ipv4_quad,
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'link', 'host'], dtype=six.text_type),
# dhcp
'hostname': __anything,
'leasehours': __int,
'leasetime': __int,
'vendor': __anything,
'client': __anything,
# bootp
'bootfile': __anything,
'server': __ipv4_quad,
'hwaddr': __mac,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'dstaddr': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# bond
'slaves': __anything,
# ppp
'provider': __anything,
'unit': __int,
'options': __anything,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
#
'network': __anything, # i don't know what this is
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
IPV6_VALID_PROTO = ['auto', 'loopback', 'static', 'manual',
'dhcp', 'v4tunnel', '6to4']
IPV6_ATTR_MAP = {
'proto': __within(IPV6_VALID_PROTO),
# ipv6 static & manual
'address': __ipv6,
'addresses': __anything,
'netmask': __ipv6_netmask,
'broadcast': __ipv6,
'gateway': __ipv6, # supports a colon-delimited list
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'site', 'link', 'host'], dtype=six.text_type),
# inet6 auto
'privext': __within([0, 1, 2], dtype=int),
'dhcp': __within([0, 1], dtype=int),
# inet6 static & manual & dhcp
'media': __anything,
'accept_ra': __within([0, 1], dtype=int),
'autoconf': __within([0, 1], dtype=int),
'preferred-lifetime': __int,
'dad-attempts': __int, # 0 to disable
'dad-interval': __float,
# bond
'slaves': __anything,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
WIRELESS_ATTR_MAP = {
'wireless-essid': __anything,
'wireless-mode': __anything, # TODO
'wpa-ap-scan': __within([0, 1, 2], dtype=int), # TODO
'wpa-conf': __anything,
'wpa-driver': __anything,
'wpa-group': __anything,
'wpa-key-mgmt': __anything,
'wpa-pairwise': __anything,
'wpa-psk': __anything,
'wpa-proto': __anything, # partial(__within,
'wpa-roam': __anything,
'wpa-ssid': __anything, # TODO
}
ATTRMAPS = {
'inet': [IPV4_ATTR_MAP, WIRELESS_ATTR_MAP],
'inet6': [IPV6_ATTR_MAP, WIRELESS_ATTR_MAP]
}
def _validate_interface_option(attr, value, addrfam='inet'):
'''lookup the validation function for a [addrfam][attr] and
return the results
:param attr: attribute name
:param value: raw setting value
:param addrfam: address family (inet, inet6,
'''
valid, _value, errmsg = False, value, 'Unknown validator'
attrmaps = ATTRMAPS.get(addrfam, [])
for attrmap in attrmaps:
if attr in attrmap:
validate_func = attrmap[attr]
(valid, _value, errmsg) = validate_func(value)
break
return (valid, _value, errmsg)
def _attrmaps_contain_attr(attr):
return (
attr in WIRELESS_ATTR_MAP or
attr in IPV4_ATTR_MAP or
attr in IPV6_ATTR_MAP)
def _parse_ethtool_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
if 'autoneg' in opts:
if opts['autoneg'] in _CONFIG_TRUE:
config.update({'autoneg': 'on'})
elif opts['autoneg'] in _CONFIG_FALSE:
config.update({'autoneg': 'off'})
else:
_raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE)
if 'duplex' in opts:
valid = ['full', 'half']
if opts['duplex'] in valid:
config.update({'duplex': opts['duplex']})
else:
_raise_error_iface(iface, 'duplex', valid)
if 'speed' in opts:
valid = ['10', '100', '1000', '10000']
if six.text_type(opts['speed']) in valid:
config.update({'speed': opts['speed']})
else:
_raise_error_iface(iface, opts['speed'], valid)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'on'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'off'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_ethtool_pppoe_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
for opt in _DEB_CONFIG_PPPOE_OPTS:
if opt in opts:
config[opt] = opts[opt]
if 'provider' in opts and not opts['provider']:
_raise_error_iface(iface, 'provider', _CONFIG_TRUE + _CONFIG_FALSE)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('noipdefault', 'usepeerdns', 'defaultroute', 'hide-password', 'noauth', 'persist', 'noaccomp'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'True'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'False'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_settings_bond(opts, iface):
'''
Filters given options and outputs valid settings for requested
operation. If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond_def = {
# 803.ad aggregation selection logic
# 0 for stable (default)
# 1 for bandwidth
# 2 for count
'ad_select': '0',
# Max number of transmit queues (default = 16)
'tx_queues': '16',
# Link monitoring in milliseconds. Most NICs support this
'miimon': '100',
# ARP interval in milliseconds
'arp_interval': '250',
# Delay before considering link down in milliseconds (miimon * 2)
'downdelay': '200',
# lacp_rate 0: Slow - every 30 seconds
# lacp_rate 1: Fast - every 1 second
'lacp_rate': '0',
# Max bonds for this driver
'max_bonds': '1',
# Specifies the time, in milliseconds, to wait before
# enabling a slave after a link recovery has been
# detected. Only used with miimon.
'updelay': '0',
# Used with miimon.
# On: driver sends mii
# Off: ethtool sends mii
'use_carrier': 'on',
# Default. Don't change unless you know what you are doing.
'xmit_hash_policy': 'layer2',
}
if opts['mode'] in ['balance-rr', '0']:
log.info('Device: %s Bonding Mode: load balancing (round-robin)', iface)
return _parse_settings_bond_0(opts, iface, bond_def)
elif opts['mode'] in ['active-backup', '1']:
log.info('Device: %s Bonding Mode: fault-tolerance (active-backup)', iface)
return _parse_settings_bond_1(opts, iface, bond_def)
elif opts['mode'] in ['balance-xor', '2']:
log.info('Device: %s Bonding Mode: load balancing (xor)', iface)
return _parse_settings_bond_2(opts, iface, bond_def)
elif opts['mode'] in ['broadcast', '3']:
log.info('Device: %s Bonding Mode: fault-tolerance (broadcast)', iface)
return _parse_settings_bond_3(opts, iface, bond_def)
elif opts['mode'] in ['802.3ad', '4']:
log.info('Device: %s Bonding Mode: IEEE 802.3ad Dynamic link '
'aggregation', iface)
return _parse_settings_bond_4(opts, iface, bond_def)
elif opts['mode'] in ['balance-tlb', '5']:
log.info('Device: %s Bonding Mode: transmit load balancing', iface)
return _parse_settings_bond_5(opts, iface, bond_def)
elif opts['mode'] in ['balance-alb', '6']:
log.info('Device: %s Bonding Mode: adaptive load balancing', iface)
return _parse_settings_bond_6(opts, iface, bond_def)
else:
valid = [
'0', '1', '2', '3', '4', '5', '6',
'balance-rr', 'active-backup', 'balance-xor',
'broadcast', '802.3ad', 'balance-tlb', 'balance-alb'
]
_raise_error_iface(iface, 'mode', valid)
def _parse_settings_bond_0(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond0.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '0'}
# ARP targets in n.n.n.n form
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
return bond
def _parse_settings_bond_1(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '1'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
if not (__grains__['os'] == "Ubuntu" and __grains__['osrelease_info'][0] >= 16):
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_2(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond2.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '2'}
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_3(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond3.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '3'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_4(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond4.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '4'}
for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']:
if binding in opts:
if binding == 'lacp_rate':
if opts[binding] == 'fast':
opts.update({binding: '1'})
if opts[binding] == 'slow':
opts.update({binding: '0'})
valid = ['fast', '1', 'slow', '0']
else:
valid = ['integer']
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, valid)
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_5(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond5.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '5'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_settings_bond_6(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond6.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '6'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_bridge_opts(opts, iface):
'''
Filters given options and outputs valid settings for BRIDGING_OPTS
If an option has a value that is not expected, this
function will log the Interface, Setting and what was expected.
'''
config = {}
if 'ports' in opts:
if isinstance(opts['ports'], list):
opts['ports'] = ' '.join(opts['ports'])
config.update({'ports': opts['ports']})
for opt in ['ageing', 'fd', 'gcint', 'hello', 'maxage']:
if opt in opts:
try:
float(opts[opt])
config.update({opt: opts[opt]})
except ValueError:
_raise_error_iface(iface, opt, ['float'])
for opt in ['bridgeprio', 'maxwait']:
if opt in opts:
if isinstance(opts[opt], int):
config.update({opt: opts[opt]})
else:
_raise_error_iface(iface, opt, ['integer'])
if 'hw' in opts:
# match 12 hex digits with either : or - as separators between pairs
if re.match('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$',
opts['hw'].lower()):
config.update({'hw': opts['hw']})
else:
_raise_error_iface(iface, 'hw', ['valid MAC address'])
for opt in ['pathcost', 'portprio']:
if opt in opts:
try:
port, cost_or_prio = opts[opt].split()
int(cost_or_prio)
config.update({opt: '{0} {1}'.format(port, cost_or_prio)})
except ValueError:
_raise_error_iface(iface, opt, ['interface integer'])
if 'stp' in opts:
if opts['stp'] in _CONFIG_TRUE:
config.update({'stp': 'on'})
elif opts['stp'] in _CONFIG_FALSE:
config.update({'stp': 'off'})
else:
_raise_error_iface(iface, 'stp', _CONFIG_TRUE + _CONFIG_FALSE)
if 'waitport' in opts:
if isinstance(opts['waitport'], int):
config.update({'waitport': opts['waitport']})
else:
values = opts['waitport'].split()
waitport_time = values.pop(0)
if waitport_time.isdigit() and values:
config.update({
'waitport': '{0} {1}'.format(
waitport_time, ' '.join(values)
)
})
else:
_raise_error_iface(iface, opt, ['integer [interfaces]'])
return config
def _parse_settings_eth(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['inet'] = salt.utils.odict.OrderedDict()
iface_data['inet6'] = salt.utils.odict.OrderedDict()
if enabled:
adapters[iface]['enabled'] = True
if opts.get('hotplug', False):
adapters[iface]['hotplug'] = True
if opts.get('enable_ipv6', None) and opts.get('iface_type', '') == 'vlan':
iface_data['inet6']['vlan_raw_device'] = (
re.sub(r'\.\d*', '', iface))
for addrfam in ['inet', 'inet6']:
if iface_type not in ['bridge']:
tmp_ethtool = _parse_ethtool_opts(opts, iface)
if tmp_ethtool:
ethtool = {}
for item in tmp_ethtool:
ethtool[_ETHTOOL_CONFIG_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['ethtool'] = ethtool
# return a list of sorted keys to ensure consistent order
iface_data[addrfam]['ethtool_keys'] = sorted(ethtool)
if iface_type == 'bridge':
bridging = _parse_bridge_opts(opts, iface)
if bridging:
iface_data[addrfam]['bridging'] = bridging
iface_data[addrfam]['bridging_keys'] = sorted(bridging)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'bond':
bonding = _parse_settings_bond(opts, iface)
if bonding:
iface_data[addrfam]['bonding'] = bonding
iface_data[addrfam]['bonding']['slaves'] = opts['slaves']
iface_data[addrfam]['bonding_keys'] = sorted(bonding)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'slave':
adapters[iface]['master'] = opts['master']
opts['proto'] = 'manual'
iface_data[addrfam]['master'] = adapters[iface]['master']
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'vlan':
iface_data[addrfam]['vlan_raw_device'] = re.sub(r'\.\d*', '', iface)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'pppoe':
tmp_ethtool = _parse_ethtool_pppoe_opts(opts, iface)
if tmp_ethtool:
for item in tmp_ethtool:
adapters[iface]['data'][addrfam][_DEB_CONFIG_PPPOE_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['addrfam'] = addrfam
opts.pop('mode', None)
for opt, val in opts.items():
inet = None
if opt.startswith('ipv4'):
opt = opt[4:]
inet = 'inet'
iface_data['inet']['addrfam'] = 'inet'
elif opt.startswith('ipv6'):
iface_data['inet6']['addrfam'] = 'inet6'
opt = opt[4:]
inet = 'inet6'
elif opt in ['ipaddr', 'address', 'ipaddresses', 'addresses', 'gateway', 'proto']:
iface_data['inet']['addrfam'] = 'inet'
inet = 'inet'
_opt = SALT_ATTR_TO_DEBIAN_ATTR_MAP.get(opt, opt)
_debopt = _opt.replace('-', '_')
for addrfam in ['inet', 'inet6']:
(valid, value, errmsg) = _validate_interface_option(_opt, val, addrfam=addrfam)
if not valid:
continue
if inet is None and _debopt not in iface_data[addrfam]:
iface_data[addrfam][_debopt] = value
elif inet == addrfam:
iface_data[addrfam][_debopt] = value
for opt in ['up_cmds', 'pre_up_cmds', 'post_up_cmds',
'down_cmds', 'pre_down_cmds', 'post_down_cmds']:
if opt in opts:
iface_data['inet'][opt] = opts[opt]
iface_data['inet6'][opt] = opts[opt]
# Remove incomplete/disabled inet blocks
for (addrfam, opt) in [('inet', 'enable_ipv4'), ('inet6', 'enable_ipv6')]:
if opts.get(opt, None) is False:
iface_data.pop(addrfam)
elif iface_data[addrfam].get('addrfam', '') != addrfam:
iface_data.pop(addrfam)
return adapters
def _parse_settings_source(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['sources'] = [opts['source']]
return adapters
def _parse_network_settings(opts, current):
'''
Filters given options and outputs valid settings for
the global network settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
current = dict((k.lower(), v) for (k, v) in six.iteritems(current))
result = {}
valid = _CONFIG_TRUE + _CONFIG_FALSE
if 'enabled' not in opts:
try:
opts['networking'] = current['networking']
_log_default_network('networking', current['networking'])
except ValueError:
_raise_error_network('networking', valid)
else:
opts['networking'] = opts['enabled']
if opts['networking'] in valid:
if opts['networking'] in _CONFIG_TRUE:
result['networking'] = 'yes'
elif opts['networking'] in _CONFIG_FALSE:
result['networking'] = 'no'
else:
_raise_error_network('networking', valid)
if 'hostname' not in opts:
try:
opts['hostname'] = current['hostname']
_log_default_network('hostname', current['hostname'])
except ValueError:
_raise_error_network('hostname', ['server1.example.com'])
if opts['hostname']:
result['hostname'] = opts['hostname']
else:
_raise_error_network('hostname', ['server1.example.com'])
if 'search' in opts:
result['search'] = opts['search']
return result
def _parse_routes(iface, opts):
'''
Filters given options and outputs valid settings for
the route settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
result = {}
if 'routes' not in opts:
_raise_error_routes(iface, 'routes', 'List of routes')
for opt in opts:
result[opt] = opts[opt]
return result
def _write_file(iface, data, folder, pattern):
'''
Writes a file to disk
'''
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
return filename
def _write_file_routes(iface, data, folder, pattern):
'''
Writes a file to disk
'''
# ifup / ifdown is executing given folder via run-parts.
# according to run-parts man-page, only filenames with this pattern are
# executed: (^[a-zA-Z0-9_-]+$)
# In order to make the routes file work for vlan interfaces
# (default would have been in example /etc/network/if-up.d/route-bond0.12)
# these dots in the iface name need to be replaced by underscores, so it
# can be executed by run-parts
iface = iface.replace('.', '_')
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
__salt__['file.set_mode'](filename, '0755')
return filename
def _write_file_network(data, filename, create=False):
'''
Writes a file to disk
If file does not exist, only create if create
argument is True
'''
if not os.path.exists(filename) and not create:
msg = '{0} cannot be written. {0} does not exist\
and create is set to False'
msg = msg.format(filename)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
def _read_temp(data):
'''
Return what would be written to disk
'''
tout = StringIO()
tout.write(data)
tout.seek(0)
output = tout.readlines()
tout.close()
return output
def _read_temp_ifaces(iface, data):
'''
Return what would be written to disk for interfaces
'''
try:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': data})
# Return as an array so the difflib works
return [item + '\n' for item in ifcfg.split('\n')]
def _write_file_ifaces(iface, data, **settings):
'''
Writes a file to disk
'''
try:
eth_template = JINJA.get_template('debian_eth.jinja')
source_template = JINJA.get_template('debian_source.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
# Read /etc/network/interfaces into a dict
adapters = _parse_interfaces()
# Apply supplied settings over on-disk settings
adapters[iface] = data
ifcfg = ''
for adapter in adapters:
if 'type' in adapters[adapter] and adapters[adapter]['type'] == 'source':
tmp = source_template.render({'name': adapter, 'data': adapters[adapter]})
else:
tmp = eth_template.render({'name': adapter, 'data': adapters[adapter]})
ifcfg = ifcfg + tmp
if adapter == iface:
saved_ifcfg = tmp
_SEPARATE_FILE = False
if 'filename' in settings:
if not settings['filename'].startswith('/'):
filename = '{0}/{1}'.format(_DEB_NETWORK_DIR, settings['filename'])
else:
filename = settings['filename']
_SEPARATE_FILE = True
else:
if 'filename' in adapters[adapter]['data']:
filename = adapters[adapter]['data']
else:
filename = _DEB_NETWORK_FILE
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
if _SEPARATE_FILE:
fout.write(salt.utils.stringutils.to_str(saved_ifcfg))
else:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return saved_ifcfg.split('\n')
def _write_file_ppp_ifaces(iface, data):
'''
Writes a file to disk
'''
try:
template = JINJA.get_template('debian_ppp_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_ppp_eth.jinja')
return ''
adapters = _parse_interfaces()
adapters[iface] = data
ifcfg = ''
tmp = template.render({'data': adapters[iface]})
ifcfg = tmp + ifcfg
filename = _DEB_PPP_DIR + '/' + adapters[iface]['data']['inet']['provider']
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.fopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return filename
def build_bond(iface, **settings):
'''
Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb
'''
deb_major = __grains__['osrelease'][:1]
opts = _parse_settings_bond(settings, iface)
try:
template = JINJA.get_template('conf.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template conf.jinja')
return ''
data = template.render({'name': iface, 'bonding': opts})
if 'test' in settings and settings['test']:
return _read_temp(data)
_write_file(iface, data, _DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
if deb_major == '5':
for line_type in ('alias', 'options'):
cmd = ['sed', '-i', '-e', r'/^{0}\s{1}.*/d'.format(line_type, iface),
'/etc/modprobe.conf']
__salt__['cmd.run'](cmd, python_shell=False)
__salt__['file.append']('/etc/modprobe.conf', path)
# Load kernel module
__salt__['kmod.load']('bonding')
# install ifenslave-2.6
__salt__['pkg.install']('ifenslave-2.6')
return _read_file(path)
def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'vlan':
settings['vlan'] = 'yes'
__salt__['pkg.install']('vlan')
elif iface_type == 'pppoe':
settings['pppoe'] = 'yes'
if not __salt__['pkg.version']('ppp'):
inst = __salt__['pkg.install']('ppp')
elif iface_type == 'bond':
if 'slaves' not in settings:
msg = 'slaves is a required setting for bond interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'bridge':
if 'ports' not in settings:
msg = (
'ports is a required setting for bridge interfaces on Debian '
'or Ubuntu based systems'
)
log.error(msg)
raise AttributeError(msg)
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'pppoe']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
if iface_type in ['source']:
opts = _parse_settings_source(settings, iface_type, enabled, iface)
if 'test' in settings and settings['test']:
return _read_temp_ifaces(iface, opts[iface])
ifcfg = _write_file_ifaces(iface, opts[iface], **settings)
if iface_type == 'pppoe':
_write_file_ppp_ifaces(iface, opts[iface])
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg]
def build_routes(iface, **settings):
'''
Add route scripts for a network interface using up commands.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
'''
opts = _parse_routes(iface, settings)
try:
template = JINJA.get_template('route_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template route_eth.jinja')
return ''
add_routecfg = template.render(route_type='add',
routes=opts['routes'],
iface=iface)
del_routecfg = template.render(route_type='del',
routes=opts['routes'],
iface=iface)
if 'test' in settings and settings['test']:
return _read_temp(add_routecfg + del_routecfg)
filename = _write_file_routes(iface,
add_routecfg,
_DEB_NETWORK_UP_DIR,
'route-{0}')
results = _read_file(filename)
filename = _write_file_routes(iface,
del_routecfg,
_DEB_NETWORK_DOWN_DIR,
'route-{0}')
results += _read_file(filename)
return results
def down(iface, iface_type):
'''
Shutdown a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.down eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought down.
if iface_type not in ['slave', 'source']:
return __salt__['cmd.run'](['ifdown', iface])
return None
def get_bond(iface):
'''
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
'''
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
return _read_file(path)
def get_interface(iface):
'''
Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
adapters = _parse_interfaces()
if iface in adapters:
try:
if iface == 'source':
template = JINJA.get_template('debian_source.jinja')
else:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': adapters[iface]})
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg.split('\n')]
else:
return []
def up(iface, iface_type): # pylint: disable=C0103
'''
Start up a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.up eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought up.
if iface_type not in ('slave', 'source'):
return __salt__['cmd.run'](['ifup', iface])
return None
def get_network_settings():
'''
Return the contents of the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_network_settings
'''
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
settings = {}
if __salt__['service.available']('networking'):
if __salt__['service.status']('networking'):
settings['networking'] = "yes"
else:
settings['networking'] = "no"
else:
settings['networking'] = "no"
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
settings['hostname'] = hostname
settings['domainname'] = domainname
settings['searchdomain'] = searchdomain
else:
settings = _parse_current_network_settings()
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(settings)
return _read_temp(network)
def get_routes(iface):
'''
Return the routes for the interface
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0
'''
filename = os.path.join(_DEB_NETWORK_UP_DIR, 'route-{0}'.format(iface))
results = _read_file(filename)
filename = os.path.join(_DEB_NETWORK_DOWN_DIR, 'route-{0}'.format(iface))
results += _read_file(filename)
return results
def apply_network_settings(**settings):
'''
Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings
'''
if 'require_reboot' not in settings:
settings['require_reboot'] = False
if 'apply_hostname' not in settings:
settings['apply_hostname'] = False
hostname_res = True
if settings['apply_hostname'] in _CONFIG_TRUE:
if 'hostname' in settings:
hostname_res = __salt__['network.mod_hostname'](settings['hostname'])
else:
log.warning(
'The network state sls is trying to apply hostname '
'changes but no hostname is defined.'
)
hostname_res = False
res = True
if settings['require_reboot'] in _CONFIG_TRUE:
log.warning(
'The network state sls is requiring a reboot of the system to '
'properly apply network configuration.'
)
res = True
else:
stop = __salt__['service.stop']('networking')
time.sleep(2)
res = stop and __salt__['service.start']('networking')
return hostname_res and res
def build_network_settings(**settings):
'''
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
'''
changes = []
# Read current configuration and store default values
current_network_settings = _parse_current_network_settings()
# Build settings
opts = _parse_network_settings(settings, current_network_settings)
# Ubuntu has moved away from /etc/default/networking
# beginning with the 12.04 release so we disable or enable
# the networking related services on boot
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
if opts['networking'] == 'yes':
service_cmd = 'service.enable'
else:
service_cmd = 'service.disable'
if __salt__['service.available']('NetworkManager'):
__salt__[service_cmd]('NetworkManager')
if __salt__['service.available']('networking'):
__salt__[service_cmd]('networking')
else:
try:
template = JINJA.get_template('network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template network.jinja')
return ''
network = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(network)
# Write settings
_write_file_network(network, _DEB_NETWORKING_FILE, True)
# Get hostname and domain from opts
sline = opts['hostname'].split('.', 1)
opts['hostname'] = sline[0]
current_domainname = current_network_settings['domainname']
current_searchdomain = current_network_settings['searchdomain']
new_domain = False
if len(sline) > 1:
new_domainname = sline[1]
if new_domainname != current_domainname:
domainname = new_domainname
opts['domainname'] = new_domainname
new_domain = True
else:
domainname = current_domainname
opts['domainname'] = domainname
else:
domainname = current_domainname
opts['domainname'] = domainname
new_search = False
if 'search' in opts:
new_searchdomain = opts['search']
if new_searchdomain != current_searchdomain:
searchdomain = new_searchdomain
opts['searchdomain'] = new_searchdomain
new_search = True
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
# If the domain changes, then we should write the resolv.conf file.
if new_domain or new_search:
# Look for existing domain line and update if necessary
resolve = _parse_resolve()
domain_prog = re.compile(r'domain\s+')
search_prog = re.compile(r'search\s+')
new_contents = []
for item in _read_file(_DEB_RESOLV_FILE):
if domain_prog.match(item):
item = 'domain {0}'.format(domainname)
elif search_prog.match(item):
item = 'search {0}'.format(searchdomain)
new_contents.append(item)
# A domain line didn't exist so we'll add one in
# with the new domainname
if 'domain' not in resolve:
new_contents.insert(0, 'domain {0}' . format(domainname))
# A search line didn't exist so we'll add one in
# with the new search domain
if 'search' not in resolve:
new_contents.insert('domain' in resolve, 'search {0}'.format(searchdomain))
new_resolv = '\n'.join(new_contents)
# Write /etc/resolv.conf
if not ('test' in settings and settings['test']):
_write_file_network(new_resolv, _DEB_RESOLV_FILE)
# used for returning the results back
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(opts)
changes.extend(_read_temp(network))
return changes
|
saltstack/salt
|
salt/modules/debian_ip.py
|
_parse_ethtool_opts
|
python
|
def _parse_ethtool_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
if 'autoneg' in opts:
if opts['autoneg'] in _CONFIG_TRUE:
config.update({'autoneg': 'on'})
elif opts['autoneg'] in _CONFIG_FALSE:
config.update({'autoneg': 'off'})
else:
_raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE)
if 'duplex' in opts:
valid = ['full', 'half']
if opts['duplex'] in valid:
config.update({'duplex': opts['duplex']})
else:
_raise_error_iface(iface, 'duplex', valid)
if 'speed' in opts:
valid = ['10', '100', '1000', '10000']
if six.text_type(opts['speed']) in valid:
config.update({'speed': opts['speed']})
else:
_raise_error_iface(iface, opts['speed'], valid)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'on'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'off'})
else:
_raise_error_iface(iface, option, valid)
return config
|
Filters given options and outputs valid settings for ETHTOOLS_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_ip.py#L695-L736
| null |
# -*- coding: utf-8 -*-
'''
The networking module for Debian-based distros
References:
* http://www.debian.org/doc/manuals/debian-reference/ch05.en.html
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import functools
import logging
import os.path
import os
import re
import time
# Import third party libs
import jinja2
import jinja2.exceptions
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error,no-name-in-module
# Import salt libs
import salt.utils.dns
import salt.utils.files
import salt.utils.odict
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.validate.net
# Set up logging
log = logging.getLogger(__name__)
# Set up template environment
JINJA = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'debian_ip')
)
)
# Define the module's virtual name
__virtualname__ = 'ip'
def __virtual__():
'''
Confine this module to Debian-based distros
'''
if __grains__['os_family'] == 'Debian':
return __virtualname__
return (False, 'The debian_ip module could not be loaded: '
'unsupported OS family')
_ETHTOOL_CONFIG_OPTS = {
'speed': 'link-speed',
'duplex': 'link-duplex',
'autoneg': 'ethernet-autoneg',
'ethernet-port': 'ethernet-port',
'wol': 'ethernet-wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'rx': 'offload-rx',
'tx': 'offload-tx',
'sg': 'offload-sg',
'tso': 'offload-tso',
'ufo': 'offload-ufo',
'gso': 'offload-gso',
'gro': 'offload-gro',
'lro': 'offload-lro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_REV_ETHTOOL_CONFIG_OPTS = {
'link-speed': 'speed',
'link-duplex': 'duplex',
'ethernet-autoneg': 'autoneg',
'ethernet-port': 'ethernet-port',
'ethernet-wol': 'wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'offload-rx': 'rx',
'offload-tx': 'tx',
'offload-sg': 'sg',
'offload-tso': 'tso',
'offload-ufo': 'ufo',
'offload-gso': 'gso',
'offload-lro': 'lro',
'offload-gro': 'gro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_DEB_CONFIG_PPPOE_OPTS = {
'user': 'user',
'password': 'password',
'provider': 'provider',
'pppoe_iface': 'pppoe_iface',
'noipdefault': 'noipdefault',
'usepeerdns': 'usepeerdns',
'defaultroute': 'defaultroute',
'holdoff': 'holdoff',
'maxfail': 'maxfail',
'hide-password': 'hide-password',
'lcp-echo-interval': 'lcp-echo-interval',
'lcp-echo-failure': 'lcp-echo-failure',
'connect': 'connect',
'noauth': 'noauth',
'persist': 'persist',
'mtu': 'mtu',
'noaccomp': 'noaccomp',
'linkname': 'linkname',
}
_DEB_ROUTES_FILE = '/etc/network/routes'
_DEB_NETWORK_FILE = '/etc/network/interfaces'
_DEB_NETWORK_DIR = '/etc/network/interfaces.d/'
_DEB_NETWORK_UP_DIR = '/etc/network/if-up.d/'
_DEB_NETWORK_DOWN_DIR = '/etc/network/if-down.d/'
_DEB_NETWORK_CONF_FILES = '/etc/modprobe.d/'
_DEB_NETWORKING_FILE = '/etc/default/networking'
_DEB_HOSTNAME_FILE = '/etc/hostname'
_DEB_RESOLV_FILE = '/etc/resolv.conf'
_DEB_PPP_DIR = '/etc/ppp/peers/'
_CONFIG_TRUE = ['yes', 'on', 'true', '1', True]
_CONFIG_FALSE = ['no', 'off', 'false', '0', False]
_IFACE_TYPES = [
'eth', 'bond', 'alias', 'clone',
'ipsec', 'dialup', 'bridge', 'slave',
'vlan', 'pppoe', 'source',
]
def _error_msg_iface(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, '|'.join(str(e) for e in expected))
def _error_msg_routes(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, expected)
def _log_default_iface(iface, opt, value):
log.info(
'Using default option -- Interface: %s Option: %s Value: %s',
iface, opt, value
)
def _error_msg_network(option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]'
return msg.format(option, '|'.join(str(e) for e in expected))
def _log_default_network(opt, value):
log.info('Using existing setting -- Setting: %s Value: %s', opt, value)
def _raise_error_iface(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_iface(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_network(option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_network(option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_routes(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_routes(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _read_file(path):
'''
Reads and returns the contents of a text file
'''
try:
with salt.utils.files.flopen(path, 'rb') as contents:
return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]
except (OSError, IOError):
return ''
def _parse_resolve():
'''
Parse /etc/resolv.conf
'''
return salt.utils.dns.parse_resolv(_DEB_RESOLV_FILE)
def _parse_domainname():
'''
Parse /etc/resolv.conf and return domainname
'''
return _parse_resolve().get('domain', '')
def _parse_searchdomain():
'''
Parse /etc/resolv.conf and return searchdomain
'''
return _parse_resolve().get('search', '')
def _parse_hostname():
'''
Parse /etc/hostname and return hostname
'''
contents = _read_file(_DEB_HOSTNAME_FILE)
if contents:
return contents[0].split('\n')[0]
else:
return ''
def _parse_current_network_settings():
'''
Parse /etc/default/networking and return current configuration
'''
opts = salt.utils.odict.OrderedDict()
opts['networking'] = ''
if os.path.isfile(_DEB_NETWORKING_FILE):
with salt.utils.files.fopen(_DEB_NETWORKING_FILE) as contents:
for line in contents:
salt.utils.stringutils.to_unicode(line)
if line.startswith('#'):
continue
elif line.startswith('CONFIGURE_INTERFACES'):
opts['networking'] = line.split('=', 1)[1].strip()
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
opts['hostname'] = hostname
opts['domainname'] = domainname
opts['searchdomain'] = searchdomain
return opts
# def __validator_func(value):
# return (valid: True/False, (transformed) value, error message)
def __ipv4_quad(value):
'''validate an IPv4 address'''
return (salt.utils.validate.net.ipv4_addr(value), value,
'dotted IPv4 address')
def __ipv6(value):
'''validate an IPv6 address'''
return (salt.utils.validate.net.ipv6_addr(value), value,
'IPv6 address')
def __mac(value):
'''validate a mac address'''
return (salt.utils.validate.net.mac(value), value,
'MAC address')
def __anything(value):
return (True, value, None)
def __int(value):
'''validate an integer'''
valid, _value = False, value
try:
_value = int(value)
valid = True
except ValueError:
pass
return (valid, _value, 'integer')
def __float(value):
'''validate a float'''
valid, _value = False, value
try:
_value = float(value)
valid = True
except ValueError:
pass
return (valid, _value, 'float')
def __ipv4_netmask(value):
'''validate an IPv4 dotted quad or integer CIDR netmask'''
valid, errmsg = False, 'dotted quad or integer CIDR (0->32)'
valid, value, _ = __int(value)
if not (valid and 0 <= value <= 32):
valid = salt.utils.validate.net.netmask(value)
return (valid, value, errmsg)
def __ipv6_netmask(value):
'''validate an IPv6 integer netmask'''
valid, errmsg = False, 'IPv6 netmask (0->128)'
valid, value, _ = __int(value)
valid = (valid and 0 <= value <= 128)
return (valid, value, errmsg)
def __within2(value, within=None, errmsg=None, dtype=None):
'''validate that a value is in ``within`` and optionally a ``dtype``'''
valid, _value = False, value
if dtype:
try:
_value = dtype(value) # TODO: this is a bit loose when dtype is a class
valid = _value in within
except ValueError:
pass
else:
valid = _value in within
if errmsg is None:
if dtype:
typename = getattr(dtype, '__name__',
hasattr(dtype, '__class__')
and getattr(dtype.__class__, 'name', dtype))
errmsg = '{0} within \'{1}\''.format(typename, within)
else:
errmsg = 'within \'{0}\''.format(within)
return (valid, _value, errmsg)
def __within(within=None, errmsg=None, dtype=None):
return functools.partial(__within2, within=within,
errmsg=errmsg, dtype=dtype)
def __space_delimited_list(value):
'''validate that a value contains one or more space-delimited values'''
if isinstance(value, six.string_types):
value = value.strip().split()
if hasattr(value, '__iter__') and value != []:
return (True, value, 'space-delimited string')
else:
return (False, value, '{0} is not a valid space-delimited value.\n'.format(value))
SALT_ATTR_TO_DEBIAN_ATTR_MAP = {
'dns': 'dns-nameservers',
'search': 'dns-search',
'hwaddr': 'hwaddress', # TODO: this limits bootp functionality
'ipaddr': 'address',
'ipaddrs': 'addresses',
}
DEBIAN_ATTR_TO_SALT_ATTR_MAP = dict(
(v, k) for (k, v) in six.iteritems(SALT_ATTR_TO_DEBIAN_ATTR_MAP))
# TODO
DEBIAN_ATTR_TO_SALT_ATTR_MAP['address'] = 'address'
DEBIAN_ATTR_TO_SALT_ATTR_MAP['hwaddress'] = 'hwaddress'
IPV4_VALID_PROTO = ['bootp', 'dhcp', 'static', 'manual', 'loopback', 'ppp']
IPV4_ATTR_MAP = {
'proto': __within(IPV4_VALID_PROTO, dtype=six.text_type),
# ipv4 static & manual
'address': __ipv4_quad,
'addresses': __anything,
'netmask': __ipv4_netmask,
'broadcast': __ipv4_quad,
'metric': __int,
'gateway': __ipv4_quad, # supports a colon-delimited list
'pointopoint': __ipv4_quad,
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'link', 'host'], dtype=six.text_type),
# dhcp
'hostname': __anything,
'leasehours': __int,
'leasetime': __int,
'vendor': __anything,
'client': __anything,
# bootp
'bootfile': __anything,
'server': __ipv4_quad,
'hwaddr': __mac,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'dstaddr': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# bond
'slaves': __anything,
# ppp
'provider': __anything,
'unit': __int,
'options': __anything,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
#
'network': __anything, # i don't know what this is
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
IPV6_VALID_PROTO = ['auto', 'loopback', 'static', 'manual',
'dhcp', 'v4tunnel', '6to4']
IPV6_ATTR_MAP = {
'proto': __within(IPV6_VALID_PROTO),
# ipv6 static & manual
'address': __ipv6,
'addresses': __anything,
'netmask': __ipv6_netmask,
'broadcast': __ipv6,
'gateway': __ipv6, # supports a colon-delimited list
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'site', 'link', 'host'], dtype=six.text_type),
# inet6 auto
'privext': __within([0, 1, 2], dtype=int),
'dhcp': __within([0, 1], dtype=int),
# inet6 static & manual & dhcp
'media': __anything,
'accept_ra': __within([0, 1], dtype=int),
'autoconf': __within([0, 1], dtype=int),
'preferred-lifetime': __int,
'dad-attempts': __int, # 0 to disable
'dad-interval': __float,
# bond
'slaves': __anything,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
WIRELESS_ATTR_MAP = {
'wireless-essid': __anything,
'wireless-mode': __anything, # TODO
'wpa-ap-scan': __within([0, 1, 2], dtype=int), # TODO
'wpa-conf': __anything,
'wpa-driver': __anything,
'wpa-group': __anything,
'wpa-key-mgmt': __anything,
'wpa-pairwise': __anything,
'wpa-psk': __anything,
'wpa-proto': __anything, # partial(__within,
'wpa-roam': __anything,
'wpa-ssid': __anything, # TODO
}
ATTRMAPS = {
'inet': [IPV4_ATTR_MAP, WIRELESS_ATTR_MAP],
'inet6': [IPV6_ATTR_MAP, WIRELESS_ATTR_MAP]
}
def _validate_interface_option(attr, value, addrfam='inet'):
'''lookup the validation function for a [addrfam][attr] and
return the results
:param attr: attribute name
:param value: raw setting value
:param addrfam: address family (inet, inet6,
'''
valid, _value, errmsg = False, value, 'Unknown validator'
attrmaps = ATTRMAPS.get(addrfam, [])
for attrmap in attrmaps:
if attr in attrmap:
validate_func = attrmap[attr]
(valid, _value, errmsg) = validate_func(value)
break
return (valid, _value, errmsg)
def _attrmaps_contain_attr(attr):
return (
attr in WIRELESS_ATTR_MAP or
attr in IPV4_ATTR_MAP or
attr in IPV6_ATTR_MAP)
def _parse_interfaces(interface_files=None):
'''
Parse /etc/network/interfaces and return current configured interfaces
'''
if interface_files is None:
interface_files = []
# Add this later.
if os.path.exists(_DEB_NETWORK_DIR):
interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]
if os.path.isfile(_DEB_NETWORK_FILE):
interface_files.insert(0, _DEB_NETWORK_FILE)
adapters = salt.utils.odict.OrderedDict()
method = -1
for interface_file in interface_files:
with salt.utils.files.fopen(interface_file) as interfaces:
# This ensures iface_dict exists, but does not ensure we're not reading a new interface.
iface_dict = {}
for line in interfaces:
line = salt.utils.stringutils.to_unicode(line)
# Identify the clauses by the first word of each line.
# Go to the next line if the current line is a comment
# or all spaces.
if line.lstrip().startswith('#') or line.isspace():
continue
# Parse the iface clause
if line.startswith('iface'):
sline = line.split()
if len(sline) != 4:
msg = 'Interface file malformed: {0}.'
msg = msg.format(sline)
log.error(msg)
raise AttributeError(msg)
iface_name = sline[1]
addrfam = sline[2]
method = sline[3]
# Create item in dict, if not already there
if iface_name not in adapters:
adapters[iface_name] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters[iface_name]:
adapters[iface_name]['data'] = salt.utils.odict.OrderedDict()
if addrfam not in adapters[iface_name]['data']:
adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict()
iface_dict = adapters[iface_name]['data'][addrfam]
iface_dict['addrfam'] = addrfam
iface_dict['proto'] = method
iface_dict['filename'] = interface_file
# Parse the detail clauses.
elif line[0].isspace():
sline = line.split()
# conf file attr: dns-nameservers
# salt states.network attr: dns
attr, valuestr = line.rstrip().split(None, 1)
if _attrmaps_contain_attr(attr):
if '-' in attr:
attrname = attr.replace('-', '_')
else:
attrname = attr
(valid, value, errmsg) = _validate_interface_option(
attr, valuestr, addrfam)
if attrname == 'address' and 'address' in iface_dict:
if 'addresses' not in iface_dict:
iface_dict['addresses'] = []
iface_dict['addresses'].append(value)
else:
iface_dict[attrname] = value
elif attr in _REV_ETHTOOL_CONFIG_OPTS:
if 'ethtool' not in iface_dict:
iface_dict['ethtool'] = salt.utils.odict.OrderedDict()
iface_dict['ethtool'][attr] = valuestr
elif attr.startswith('bond'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bonding' not in iface_dict:
iface_dict['bonding'] = salt.utils.odict.OrderedDict()
iface_dict['bonding'][opt] = valuestr
elif attr.startswith('bridge'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bridging' not in iface_dict:
iface_dict['bridging'] = salt.utils.odict.OrderedDict()
iface_dict['bridging'][opt] = valuestr
elif attr in ['up', 'pre-up', 'post-up',
'down', 'pre-down', 'post-down']:
cmd = valuestr
cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr))
if cmd_key not in iface_dict:
iface_dict[cmd_key] = []
iface_dict[cmd_key].append(cmd)
elif line.startswith('auto'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['enabled'] = True
elif line.startswith('allow-hotplug'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['hotplug'] = True
elif line.startswith('source'):
if 'source' not in adapters:
adapters['source'] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters['source']:
adapters['source']['data'] = salt.utils.odict.OrderedDict()
adapters['source']['data']['sources'] = []
adapters['source']['data']['sources'].append(line.split()[1])
# Return a sorted list of the keys for bond, bridge and ethtool options to
# ensure a consistent order
for iface_name in adapters:
if iface_name == 'source':
continue
if 'data' not in adapters[iface_name]:
msg = 'Interface file malformed for interface: {0}.'.format(iface_name)
log.error(msg)
adapters.pop(iface_name)
continue
for opt in ['ethtool', 'bonding', 'bridging']:
for inet in ['inet', 'inet6']:
if inet in adapters[iface_name]['data']:
if opt in adapters[iface_name]['data'][inet]:
opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys())
adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys
return adapters
def _parse_ethtool_pppoe_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
for opt in _DEB_CONFIG_PPPOE_OPTS:
if opt in opts:
config[opt] = opts[opt]
if 'provider' in opts and not opts['provider']:
_raise_error_iface(iface, 'provider', _CONFIG_TRUE + _CONFIG_FALSE)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('noipdefault', 'usepeerdns', 'defaultroute', 'hide-password', 'noauth', 'persist', 'noaccomp'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'True'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'False'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_settings_bond(opts, iface):
'''
Filters given options and outputs valid settings for requested
operation. If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond_def = {
# 803.ad aggregation selection logic
# 0 for stable (default)
# 1 for bandwidth
# 2 for count
'ad_select': '0',
# Max number of transmit queues (default = 16)
'tx_queues': '16',
# Link monitoring in milliseconds. Most NICs support this
'miimon': '100',
# ARP interval in milliseconds
'arp_interval': '250',
# Delay before considering link down in milliseconds (miimon * 2)
'downdelay': '200',
# lacp_rate 0: Slow - every 30 seconds
# lacp_rate 1: Fast - every 1 second
'lacp_rate': '0',
# Max bonds for this driver
'max_bonds': '1',
# Specifies the time, in milliseconds, to wait before
# enabling a slave after a link recovery has been
# detected. Only used with miimon.
'updelay': '0',
# Used with miimon.
# On: driver sends mii
# Off: ethtool sends mii
'use_carrier': 'on',
# Default. Don't change unless you know what you are doing.
'xmit_hash_policy': 'layer2',
}
if opts['mode'] in ['balance-rr', '0']:
log.info('Device: %s Bonding Mode: load balancing (round-robin)', iface)
return _parse_settings_bond_0(opts, iface, bond_def)
elif opts['mode'] in ['active-backup', '1']:
log.info('Device: %s Bonding Mode: fault-tolerance (active-backup)', iface)
return _parse_settings_bond_1(opts, iface, bond_def)
elif opts['mode'] in ['balance-xor', '2']:
log.info('Device: %s Bonding Mode: load balancing (xor)', iface)
return _parse_settings_bond_2(opts, iface, bond_def)
elif opts['mode'] in ['broadcast', '3']:
log.info('Device: %s Bonding Mode: fault-tolerance (broadcast)', iface)
return _parse_settings_bond_3(opts, iface, bond_def)
elif opts['mode'] in ['802.3ad', '4']:
log.info('Device: %s Bonding Mode: IEEE 802.3ad Dynamic link '
'aggregation', iface)
return _parse_settings_bond_4(opts, iface, bond_def)
elif opts['mode'] in ['balance-tlb', '5']:
log.info('Device: %s Bonding Mode: transmit load balancing', iface)
return _parse_settings_bond_5(opts, iface, bond_def)
elif opts['mode'] in ['balance-alb', '6']:
log.info('Device: %s Bonding Mode: adaptive load balancing', iface)
return _parse_settings_bond_6(opts, iface, bond_def)
else:
valid = [
'0', '1', '2', '3', '4', '5', '6',
'balance-rr', 'active-backup', 'balance-xor',
'broadcast', '802.3ad', 'balance-tlb', 'balance-alb'
]
_raise_error_iface(iface, 'mode', valid)
def _parse_settings_bond_0(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond0.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '0'}
# ARP targets in n.n.n.n form
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
return bond
def _parse_settings_bond_1(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '1'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
if not (__grains__['os'] == "Ubuntu" and __grains__['osrelease_info'][0] >= 16):
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_2(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond2.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '2'}
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_3(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond3.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '3'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_4(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond4.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '4'}
for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']:
if binding in opts:
if binding == 'lacp_rate':
if opts[binding] == 'fast':
opts.update({binding: '1'})
if opts[binding] == 'slow':
opts.update({binding: '0'})
valid = ['fast', '1', 'slow', '0']
else:
valid = ['integer']
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, valid)
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_5(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond5.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '5'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_settings_bond_6(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond6.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '6'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_bridge_opts(opts, iface):
'''
Filters given options and outputs valid settings for BRIDGING_OPTS
If an option has a value that is not expected, this
function will log the Interface, Setting and what was expected.
'''
config = {}
if 'ports' in opts:
if isinstance(opts['ports'], list):
opts['ports'] = ' '.join(opts['ports'])
config.update({'ports': opts['ports']})
for opt in ['ageing', 'fd', 'gcint', 'hello', 'maxage']:
if opt in opts:
try:
float(opts[opt])
config.update({opt: opts[opt]})
except ValueError:
_raise_error_iface(iface, opt, ['float'])
for opt in ['bridgeprio', 'maxwait']:
if opt in opts:
if isinstance(opts[opt], int):
config.update({opt: opts[opt]})
else:
_raise_error_iface(iface, opt, ['integer'])
if 'hw' in opts:
# match 12 hex digits with either : or - as separators between pairs
if re.match('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$',
opts['hw'].lower()):
config.update({'hw': opts['hw']})
else:
_raise_error_iface(iface, 'hw', ['valid MAC address'])
for opt in ['pathcost', 'portprio']:
if opt in opts:
try:
port, cost_or_prio = opts[opt].split()
int(cost_or_prio)
config.update({opt: '{0} {1}'.format(port, cost_or_prio)})
except ValueError:
_raise_error_iface(iface, opt, ['interface integer'])
if 'stp' in opts:
if opts['stp'] in _CONFIG_TRUE:
config.update({'stp': 'on'})
elif opts['stp'] in _CONFIG_FALSE:
config.update({'stp': 'off'})
else:
_raise_error_iface(iface, 'stp', _CONFIG_TRUE + _CONFIG_FALSE)
if 'waitport' in opts:
if isinstance(opts['waitport'], int):
config.update({'waitport': opts['waitport']})
else:
values = opts['waitport'].split()
waitport_time = values.pop(0)
if waitport_time.isdigit() and values:
config.update({
'waitport': '{0} {1}'.format(
waitport_time, ' '.join(values)
)
})
else:
_raise_error_iface(iface, opt, ['integer [interfaces]'])
return config
def _parse_settings_eth(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['inet'] = salt.utils.odict.OrderedDict()
iface_data['inet6'] = salt.utils.odict.OrderedDict()
if enabled:
adapters[iface]['enabled'] = True
if opts.get('hotplug', False):
adapters[iface]['hotplug'] = True
if opts.get('enable_ipv6', None) and opts.get('iface_type', '') == 'vlan':
iface_data['inet6']['vlan_raw_device'] = (
re.sub(r'\.\d*', '', iface))
for addrfam in ['inet', 'inet6']:
if iface_type not in ['bridge']:
tmp_ethtool = _parse_ethtool_opts(opts, iface)
if tmp_ethtool:
ethtool = {}
for item in tmp_ethtool:
ethtool[_ETHTOOL_CONFIG_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['ethtool'] = ethtool
# return a list of sorted keys to ensure consistent order
iface_data[addrfam]['ethtool_keys'] = sorted(ethtool)
if iface_type == 'bridge':
bridging = _parse_bridge_opts(opts, iface)
if bridging:
iface_data[addrfam]['bridging'] = bridging
iface_data[addrfam]['bridging_keys'] = sorted(bridging)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'bond':
bonding = _parse_settings_bond(opts, iface)
if bonding:
iface_data[addrfam]['bonding'] = bonding
iface_data[addrfam]['bonding']['slaves'] = opts['slaves']
iface_data[addrfam]['bonding_keys'] = sorted(bonding)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'slave':
adapters[iface]['master'] = opts['master']
opts['proto'] = 'manual'
iface_data[addrfam]['master'] = adapters[iface]['master']
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'vlan':
iface_data[addrfam]['vlan_raw_device'] = re.sub(r'\.\d*', '', iface)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'pppoe':
tmp_ethtool = _parse_ethtool_pppoe_opts(opts, iface)
if tmp_ethtool:
for item in tmp_ethtool:
adapters[iface]['data'][addrfam][_DEB_CONFIG_PPPOE_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['addrfam'] = addrfam
opts.pop('mode', None)
for opt, val in opts.items():
inet = None
if opt.startswith('ipv4'):
opt = opt[4:]
inet = 'inet'
iface_data['inet']['addrfam'] = 'inet'
elif opt.startswith('ipv6'):
iface_data['inet6']['addrfam'] = 'inet6'
opt = opt[4:]
inet = 'inet6'
elif opt in ['ipaddr', 'address', 'ipaddresses', 'addresses', 'gateway', 'proto']:
iface_data['inet']['addrfam'] = 'inet'
inet = 'inet'
_opt = SALT_ATTR_TO_DEBIAN_ATTR_MAP.get(opt, opt)
_debopt = _opt.replace('-', '_')
for addrfam in ['inet', 'inet6']:
(valid, value, errmsg) = _validate_interface_option(_opt, val, addrfam=addrfam)
if not valid:
continue
if inet is None and _debopt not in iface_data[addrfam]:
iface_data[addrfam][_debopt] = value
elif inet == addrfam:
iface_data[addrfam][_debopt] = value
for opt in ['up_cmds', 'pre_up_cmds', 'post_up_cmds',
'down_cmds', 'pre_down_cmds', 'post_down_cmds']:
if opt in opts:
iface_data['inet'][opt] = opts[opt]
iface_data['inet6'][opt] = opts[opt]
# Remove incomplete/disabled inet blocks
for (addrfam, opt) in [('inet', 'enable_ipv4'), ('inet6', 'enable_ipv6')]:
if opts.get(opt, None) is False:
iface_data.pop(addrfam)
elif iface_data[addrfam].get('addrfam', '') != addrfam:
iface_data.pop(addrfam)
return adapters
def _parse_settings_source(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['sources'] = [opts['source']]
return adapters
def _parse_network_settings(opts, current):
'''
Filters given options and outputs valid settings for
the global network settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
current = dict((k.lower(), v) for (k, v) in six.iteritems(current))
result = {}
valid = _CONFIG_TRUE + _CONFIG_FALSE
if 'enabled' not in opts:
try:
opts['networking'] = current['networking']
_log_default_network('networking', current['networking'])
except ValueError:
_raise_error_network('networking', valid)
else:
opts['networking'] = opts['enabled']
if opts['networking'] in valid:
if opts['networking'] in _CONFIG_TRUE:
result['networking'] = 'yes'
elif opts['networking'] in _CONFIG_FALSE:
result['networking'] = 'no'
else:
_raise_error_network('networking', valid)
if 'hostname' not in opts:
try:
opts['hostname'] = current['hostname']
_log_default_network('hostname', current['hostname'])
except ValueError:
_raise_error_network('hostname', ['server1.example.com'])
if opts['hostname']:
result['hostname'] = opts['hostname']
else:
_raise_error_network('hostname', ['server1.example.com'])
if 'search' in opts:
result['search'] = opts['search']
return result
def _parse_routes(iface, opts):
'''
Filters given options and outputs valid settings for
the route settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
result = {}
if 'routes' not in opts:
_raise_error_routes(iface, 'routes', 'List of routes')
for opt in opts:
result[opt] = opts[opt]
return result
def _write_file(iface, data, folder, pattern):
'''
Writes a file to disk
'''
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
return filename
def _write_file_routes(iface, data, folder, pattern):
'''
Writes a file to disk
'''
# ifup / ifdown is executing given folder via run-parts.
# according to run-parts man-page, only filenames with this pattern are
# executed: (^[a-zA-Z0-9_-]+$)
# In order to make the routes file work for vlan interfaces
# (default would have been in example /etc/network/if-up.d/route-bond0.12)
# these dots in the iface name need to be replaced by underscores, so it
# can be executed by run-parts
iface = iface.replace('.', '_')
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
__salt__['file.set_mode'](filename, '0755')
return filename
def _write_file_network(data, filename, create=False):
'''
Writes a file to disk
If file does not exist, only create if create
argument is True
'''
if not os.path.exists(filename) and not create:
msg = '{0} cannot be written. {0} does not exist\
and create is set to False'
msg = msg.format(filename)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
def _read_temp(data):
'''
Return what would be written to disk
'''
tout = StringIO()
tout.write(data)
tout.seek(0)
output = tout.readlines()
tout.close()
return output
def _read_temp_ifaces(iface, data):
'''
Return what would be written to disk for interfaces
'''
try:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': data})
# Return as an array so the difflib works
return [item + '\n' for item in ifcfg.split('\n')]
def _write_file_ifaces(iface, data, **settings):
'''
Writes a file to disk
'''
try:
eth_template = JINJA.get_template('debian_eth.jinja')
source_template = JINJA.get_template('debian_source.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
# Read /etc/network/interfaces into a dict
adapters = _parse_interfaces()
# Apply supplied settings over on-disk settings
adapters[iface] = data
ifcfg = ''
for adapter in adapters:
if 'type' in adapters[adapter] and adapters[adapter]['type'] == 'source':
tmp = source_template.render({'name': adapter, 'data': adapters[adapter]})
else:
tmp = eth_template.render({'name': adapter, 'data': adapters[adapter]})
ifcfg = ifcfg + tmp
if adapter == iface:
saved_ifcfg = tmp
_SEPARATE_FILE = False
if 'filename' in settings:
if not settings['filename'].startswith('/'):
filename = '{0}/{1}'.format(_DEB_NETWORK_DIR, settings['filename'])
else:
filename = settings['filename']
_SEPARATE_FILE = True
else:
if 'filename' in adapters[adapter]['data']:
filename = adapters[adapter]['data']
else:
filename = _DEB_NETWORK_FILE
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
if _SEPARATE_FILE:
fout.write(salt.utils.stringutils.to_str(saved_ifcfg))
else:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return saved_ifcfg.split('\n')
def _write_file_ppp_ifaces(iface, data):
'''
Writes a file to disk
'''
try:
template = JINJA.get_template('debian_ppp_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_ppp_eth.jinja')
return ''
adapters = _parse_interfaces()
adapters[iface] = data
ifcfg = ''
tmp = template.render({'data': adapters[iface]})
ifcfg = tmp + ifcfg
filename = _DEB_PPP_DIR + '/' + adapters[iface]['data']['inet']['provider']
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.fopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return filename
def build_bond(iface, **settings):
'''
Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb
'''
deb_major = __grains__['osrelease'][:1]
opts = _parse_settings_bond(settings, iface)
try:
template = JINJA.get_template('conf.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template conf.jinja')
return ''
data = template.render({'name': iface, 'bonding': opts})
if 'test' in settings and settings['test']:
return _read_temp(data)
_write_file(iface, data, _DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
if deb_major == '5':
for line_type in ('alias', 'options'):
cmd = ['sed', '-i', '-e', r'/^{0}\s{1}.*/d'.format(line_type, iface),
'/etc/modprobe.conf']
__salt__['cmd.run'](cmd, python_shell=False)
__salt__['file.append']('/etc/modprobe.conf', path)
# Load kernel module
__salt__['kmod.load']('bonding')
# install ifenslave-2.6
__salt__['pkg.install']('ifenslave-2.6')
return _read_file(path)
def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'vlan':
settings['vlan'] = 'yes'
__salt__['pkg.install']('vlan')
elif iface_type == 'pppoe':
settings['pppoe'] = 'yes'
if not __salt__['pkg.version']('ppp'):
inst = __salt__['pkg.install']('ppp')
elif iface_type == 'bond':
if 'slaves' not in settings:
msg = 'slaves is a required setting for bond interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'bridge':
if 'ports' not in settings:
msg = (
'ports is a required setting for bridge interfaces on Debian '
'or Ubuntu based systems'
)
log.error(msg)
raise AttributeError(msg)
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'pppoe']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
if iface_type in ['source']:
opts = _parse_settings_source(settings, iface_type, enabled, iface)
if 'test' in settings and settings['test']:
return _read_temp_ifaces(iface, opts[iface])
ifcfg = _write_file_ifaces(iface, opts[iface], **settings)
if iface_type == 'pppoe':
_write_file_ppp_ifaces(iface, opts[iface])
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg]
def build_routes(iface, **settings):
'''
Add route scripts for a network interface using up commands.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
'''
opts = _parse_routes(iface, settings)
try:
template = JINJA.get_template('route_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template route_eth.jinja')
return ''
add_routecfg = template.render(route_type='add',
routes=opts['routes'],
iface=iface)
del_routecfg = template.render(route_type='del',
routes=opts['routes'],
iface=iface)
if 'test' in settings and settings['test']:
return _read_temp(add_routecfg + del_routecfg)
filename = _write_file_routes(iface,
add_routecfg,
_DEB_NETWORK_UP_DIR,
'route-{0}')
results = _read_file(filename)
filename = _write_file_routes(iface,
del_routecfg,
_DEB_NETWORK_DOWN_DIR,
'route-{0}')
results += _read_file(filename)
return results
def down(iface, iface_type):
'''
Shutdown a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.down eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought down.
if iface_type not in ['slave', 'source']:
return __salt__['cmd.run'](['ifdown', iface])
return None
def get_bond(iface):
'''
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
'''
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
return _read_file(path)
def get_interface(iface):
'''
Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
adapters = _parse_interfaces()
if iface in adapters:
try:
if iface == 'source':
template = JINJA.get_template('debian_source.jinja')
else:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': adapters[iface]})
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg.split('\n')]
else:
return []
def up(iface, iface_type): # pylint: disable=C0103
'''
Start up a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.up eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought up.
if iface_type not in ('slave', 'source'):
return __salt__['cmd.run'](['ifup', iface])
return None
def get_network_settings():
'''
Return the contents of the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_network_settings
'''
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
settings = {}
if __salt__['service.available']('networking'):
if __salt__['service.status']('networking'):
settings['networking'] = "yes"
else:
settings['networking'] = "no"
else:
settings['networking'] = "no"
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
settings['hostname'] = hostname
settings['domainname'] = domainname
settings['searchdomain'] = searchdomain
else:
settings = _parse_current_network_settings()
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(settings)
return _read_temp(network)
def get_routes(iface):
'''
Return the routes for the interface
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0
'''
filename = os.path.join(_DEB_NETWORK_UP_DIR, 'route-{0}'.format(iface))
results = _read_file(filename)
filename = os.path.join(_DEB_NETWORK_DOWN_DIR, 'route-{0}'.format(iface))
results += _read_file(filename)
return results
def apply_network_settings(**settings):
'''
Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings
'''
if 'require_reboot' not in settings:
settings['require_reboot'] = False
if 'apply_hostname' not in settings:
settings['apply_hostname'] = False
hostname_res = True
if settings['apply_hostname'] in _CONFIG_TRUE:
if 'hostname' in settings:
hostname_res = __salt__['network.mod_hostname'](settings['hostname'])
else:
log.warning(
'The network state sls is trying to apply hostname '
'changes but no hostname is defined.'
)
hostname_res = False
res = True
if settings['require_reboot'] in _CONFIG_TRUE:
log.warning(
'The network state sls is requiring a reboot of the system to '
'properly apply network configuration.'
)
res = True
else:
stop = __salt__['service.stop']('networking')
time.sleep(2)
res = stop and __salt__['service.start']('networking')
return hostname_res and res
def build_network_settings(**settings):
'''
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
'''
changes = []
# Read current configuration and store default values
current_network_settings = _parse_current_network_settings()
# Build settings
opts = _parse_network_settings(settings, current_network_settings)
# Ubuntu has moved away from /etc/default/networking
# beginning with the 12.04 release so we disable or enable
# the networking related services on boot
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
if opts['networking'] == 'yes':
service_cmd = 'service.enable'
else:
service_cmd = 'service.disable'
if __salt__['service.available']('NetworkManager'):
__salt__[service_cmd]('NetworkManager')
if __salt__['service.available']('networking'):
__salt__[service_cmd]('networking')
else:
try:
template = JINJA.get_template('network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template network.jinja')
return ''
network = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(network)
# Write settings
_write_file_network(network, _DEB_NETWORKING_FILE, True)
# Get hostname and domain from opts
sline = opts['hostname'].split('.', 1)
opts['hostname'] = sline[0]
current_domainname = current_network_settings['domainname']
current_searchdomain = current_network_settings['searchdomain']
new_domain = False
if len(sline) > 1:
new_domainname = sline[1]
if new_domainname != current_domainname:
domainname = new_domainname
opts['domainname'] = new_domainname
new_domain = True
else:
domainname = current_domainname
opts['domainname'] = domainname
else:
domainname = current_domainname
opts['domainname'] = domainname
new_search = False
if 'search' in opts:
new_searchdomain = opts['search']
if new_searchdomain != current_searchdomain:
searchdomain = new_searchdomain
opts['searchdomain'] = new_searchdomain
new_search = True
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
# If the domain changes, then we should write the resolv.conf file.
if new_domain or new_search:
# Look for existing domain line and update if necessary
resolve = _parse_resolve()
domain_prog = re.compile(r'domain\s+')
search_prog = re.compile(r'search\s+')
new_contents = []
for item in _read_file(_DEB_RESOLV_FILE):
if domain_prog.match(item):
item = 'domain {0}'.format(domainname)
elif search_prog.match(item):
item = 'search {0}'.format(searchdomain)
new_contents.append(item)
# A domain line didn't exist so we'll add one in
# with the new domainname
if 'domain' not in resolve:
new_contents.insert(0, 'domain {0}' . format(domainname))
# A search line didn't exist so we'll add one in
# with the new search domain
if 'search' not in resolve:
new_contents.insert('domain' in resolve, 'search {0}'.format(searchdomain))
new_resolv = '\n'.join(new_contents)
# Write /etc/resolv.conf
if not ('test' in settings and settings['test']):
_write_file_network(new_resolv, _DEB_RESOLV_FILE)
# used for returning the results back
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(opts)
changes.extend(_read_temp(network))
return changes
|
saltstack/salt
|
salt/modules/debian_ip.py
|
_parse_ethtool_pppoe_opts
|
python
|
def _parse_ethtool_pppoe_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
for opt in _DEB_CONFIG_PPPOE_OPTS:
if opt in opts:
config[opt] = opts[opt]
if 'provider' in opts and not opts['provider']:
_raise_error_iface(iface, 'provider', _CONFIG_TRUE + _CONFIG_FALSE)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('noipdefault', 'usepeerdns', 'defaultroute', 'hide-password', 'noauth', 'persist', 'noaccomp'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'True'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'False'})
else:
_raise_error_iface(iface, option, valid)
return config
|
Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_ip.py#L739-L765
| null |
# -*- coding: utf-8 -*-
'''
The networking module for Debian-based distros
References:
* http://www.debian.org/doc/manuals/debian-reference/ch05.en.html
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import functools
import logging
import os.path
import os
import re
import time
# Import third party libs
import jinja2
import jinja2.exceptions
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error,no-name-in-module
# Import salt libs
import salt.utils.dns
import salt.utils.files
import salt.utils.odict
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.validate.net
# Set up logging
log = logging.getLogger(__name__)
# Set up template environment
JINJA = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'debian_ip')
)
)
# Define the module's virtual name
__virtualname__ = 'ip'
def __virtual__():
'''
Confine this module to Debian-based distros
'''
if __grains__['os_family'] == 'Debian':
return __virtualname__
return (False, 'The debian_ip module could not be loaded: '
'unsupported OS family')
_ETHTOOL_CONFIG_OPTS = {
'speed': 'link-speed',
'duplex': 'link-duplex',
'autoneg': 'ethernet-autoneg',
'ethernet-port': 'ethernet-port',
'wol': 'ethernet-wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'rx': 'offload-rx',
'tx': 'offload-tx',
'sg': 'offload-sg',
'tso': 'offload-tso',
'ufo': 'offload-ufo',
'gso': 'offload-gso',
'gro': 'offload-gro',
'lro': 'offload-lro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_REV_ETHTOOL_CONFIG_OPTS = {
'link-speed': 'speed',
'link-duplex': 'duplex',
'ethernet-autoneg': 'autoneg',
'ethernet-port': 'ethernet-port',
'ethernet-wol': 'wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'offload-rx': 'rx',
'offload-tx': 'tx',
'offload-sg': 'sg',
'offload-tso': 'tso',
'offload-ufo': 'ufo',
'offload-gso': 'gso',
'offload-lro': 'lro',
'offload-gro': 'gro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_DEB_CONFIG_PPPOE_OPTS = {
'user': 'user',
'password': 'password',
'provider': 'provider',
'pppoe_iface': 'pppoe_iface',
'noipdefault': 'noipdefault',
'usepeerdns': 'usepeerdns',
'defaultroute': 'defaultroute',
'holdoff': 'holdoff',
'maxfail': 'maxfail',
'hide-password': 'hide-password',
'lcp-echo-interval': 'lcp-echo-interval',
'lcp-echo-failure': 'lcp-echo-failure',
'connect': 'connect',
'noauth': 'noauth',
'persist': 'persist',
'mtu': 'mtu',
'noaccomp': 'noaccomp',
'linkname': 'linkname',
}
_DEB_ROUTES_FILE = '/etc/network/routes'
_DEB_NETWORK_FILE = '/etc/network/interfaces'
_DEB_NETWORK_DIR = '/etc/network/interfaces.d/'
_DEB_NETWORK_UP_DIR = '/etc/network/if-up.d/'
_DEB_NETWORK_DOWN_DIR = '/etc/network/if-down.d/'
_DEB_NETWORK_CONF_FILES = '/etc/modprobe.d/'
_DEB_NETWORKING_FILE = '/etc/default/networking'
_DEB_HOSTNAME_FILE = '/etc/hostname'
_DEB_RESOLV_FILE = '/etc/resolv.conf'
_DEB_PPP_DIR = '/etc/ppp/peers/'
_CONFIG_TRUE = ['yes', 'on', 'true', '1', True]
_CONFIG_FALSE = ['no', 'off', 'false', '0', False]
_IFACE_TYPES = [
'eth', 'bond', 'alias', 'clone',
'ipsec', 'dialup', 'bridge', 'slave',
'vlan', 'pppoe', 'source',
]
def _error_msg_iface(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, '|'.join(str(e) for e in expected))
def _error_msg_routes(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, expected)
def _log_default_iface(iface, opt, value):
log.info(
'Using default option -- Interface: %s Option: %s Value: %s',
iface, opt, value
)
def _error_msg_network(option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]'
return msg.format(option, '|'.join(str(e) for e in expected))
def _log_default_network(opt, value):
log.info('Using existing setting -- Setting: %s Value: %s', opt, value)
def _raise_error_iface(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_iface(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_network(option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_network(option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_routes(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_routes(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _read_file(path):
'''
Reads and returns the contents of a text file
'''
try:
with salt.utils.files.flopen(path, 'rb') as contents:
return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]
except (OSError, IOError):
return ''
def _parse_resolve():
'''
Parse /etc/resolv.conf
'''
return salt.utils.dns.parse_resolv(_DEB_RESOLV_FILE)
def _parse_domainname():
'''
Parse /etc/resolv.conf and return domainname
'''
return _parse_resolve().get('domain', '')
def _parse_searchdomain():
'''
Parse /etc/resolv.conf and return searchdomain
'''
return _parse_resolve().get('search', '')
def _parse_hostname():
'''
Parse /etc/hostname and return hostname
'''
contents = _read_file(_DEB_HOSTNAME_FILE)
if contents:
return contents[0].split('\n')[0]
else:
return ''
def _parse_current_network_settings():
'''
Parse /etc/default/networking and return current configuration
'''
opts = salt.utils.odict.OrderedDict()
opts['networking'] = ''
if os.path.isfile(_DEB_NETWORKING_FILE):
with salt.utils.files.fopen(_DEB_NETWORKING_FILE) as contents:
for line in contents:
salt.utils.stringutils.to_unicode(line)
if line.startswith('#'):
continue
elif line.startswith('CONFIGURE_INTERFACES'):
opts['networking'] = line.split('=', 1)[1].strip()
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
opts['hostname'] = hostname
opts['domainname'] = domainname
opts['searchdomain'] = searchdomain
return opts
# def __validator_func(value):
# return (valid: True/False, (transformed) value, error message)
def __ipv4_quad(value):
'''validate an IPv4 address'''
return (salt.utils.validate.net.ipv4_addr(value), value,
'dotted IPv4 address')
def __ipv6(value):
'''validate an IPv6 address'''
return (salt.utils.validate.net.ipv6_addr(value), value,
'IPv6 address')
def __mac(value):
'''validate a mac address'''
return (salt.utils.validate.net.mac(value), value,
'MAC address')
def __anything(value):
return (True, value, None)
def __int(value):
'''validate an integer'''
valid, _value = False, value
try:
_value = int(value)
valid = True
except ValueError:
pass
return (valid, _value, 'integer')
def __float(value):
'''validate a float'''
valid, _value = False, value
try:
_value = float(value)
valid = True
except ValueError:
pass
return (valid, _value, 'float')
def __ipv4_netmask(value):
'''validate an IPv4 dotted quad or integer CIDR netmask'''
valid, errmsg = False, 'dotted quad or integer CIDR (0->32)'
valid, value, _ = __int(value)
if not (valid and 0 <= value <= 32):
valid = salt.utils.validate.net.netmask(value)
return (valid, value, errmsg)
def __ipv6_netmask(value):
'''validate an IPv6 integer netmask'''
valid, errmsg = False, 'IPv6 netmask (0->128)'
valid, value, _ = __int(value)
valid = (valid and 0 <= value <= 128)
return (valid, value, errmsg)
def __within2(value, within=None, errmsg=None, dtype=None):
'''validate that a value is in ``within`` and optionally a ``dtype``'''
valid, _value = False, value
if dtype:
try:
_value = dtype(value) # TODO: this is a bit loose when dtype is a class
valid = _value in within
except ValueError:
pass
else:
valid = _value in within
if errmsg is None:
if dtype:
typename = getattr(dtype, '__name__',
hasattr(dtype, '__class__')
and getattr(dtype.__class__, 'name', dtype))
errmsg = '{0} within \'{1}\''.format(typename, within)
else:
errmsg = 'within \'{0}\''.format(within)
return (valid, _value, errmsg)
def __within(within=None, errmsg=None, dtype=None):
return functools.partial(__within2, within=within,
errmsg=errmsg, dtype=dtype)
def __space_delimited_list(value):
'''validate that a value contains one or more space-delimited values'''
if isinstance(value, six.string_types):
value = value.strip().split()
if hasattr(value, '__iter__') and value != []:
return (True, value, 'space-delimited string')
else:
return (False, value, '{0} is not a valid space-delimited value.\n'.format(value))
SALT_ATTR_TO_DEBIAN_ATTR_MAP = {
'dns': 'dns-nameservers',
'search': 'dns-search',
'hwaddr': 'hwaddress', # TODO: this limits bootp functionality
'ipaddr': 'address',
'ipaddrs': 'addresses',
}
DEBIAN_ATTR_TO_SALT_ATTR_MAP = dict(
(v, k) for (k, v) in six.iteritems(SALT_ATTR_TO_DEBIAN_ATTR_MAP))
# TODO
DEBIAN_ATTR_TO_SALT_ATTR_MAP['address'] = 'address'
DEBIAN_ATTR_TO_SALT_ATTR_MAP['hwaddress'] = 'hwaddress'
IPV4_VALID_PROTO = ['bootp', 'dhcp', 'static', 'manual', 'loopback', 'ppp']
IPV4_ATTR_MAP = {
'proto': __within(IPV4_VALID_PROTO, dtype=six.text_type),
# ipv4 static & manual
'address': __ipv4_quad,
'addresses': __anything,
'netmask': __ipv4_netmask,
'broadcast': __ipv4_quad,
'metric': __int,
'gateway': __ipv4_quad, # supports a colon-delimited list
'pointopoint': __ipv4_quad,
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'link', 'host'], dtype=six.text_type),
# dhcp
'hostname': __anything,
'leasehours': __int,
'leasetime': __int,
'vendor': __anything,
'client': __anything,
# bootp
'bootfile': __anything,
'server': __ipv4_quad,
'hwaddr': __mac,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'dstaddr': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# bond
'slaves': __anything,
# ppp
'provider': __anything,
'unit': __int,
'options': __anything,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
#
'network': __anything, # i don't know what this is
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
IPV6_VALID_PROTO = ['auto', 'loopback', 'static', 'manual',
'dhcp', 'v4tunnel', '6to4']
IPV6_ATTR_MAP = {
'proto': __within(IPV6_VALID_PROTO),
# ipv6 static & manual
'address': __ipv6,
'addresses': __anything,
'netmask': __ipv6_netmask,
'broadcast': __ipv6,
'gateway': __ipv6, # supports a colon-delimited list
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'site', 'link', 'host'], dtype=six.text_type),
# inet6 auto
'privext': __within([0, 1, 2], dtype=int),
'dhcp': __within([0, 1], dtype=int),
# inet6 static & manual & dhcp
'media': __anything,
'accept_ra': __within([0, 1], dtype=int),
'autoconf': __within([0, 1], dtype=int),
'preferred-lifetime': __int,
'dad-attempts': __int, # 0 to disable
'dad-interval': __float,
# bond
'slaves': __anything,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
WIRELESS_ATTR_MAP = {
'wireless-essid': __anything,
'wireless-mode': __anything, # TODO
'wpa-ap-scan': __within([0, 1, 2], dtype=int), # TODO
'wpa-conf': __anything,
'wpa-driver': __anything,
'wpa-group': __anything,
'wpa-key-mgmt': __anything,
'wpa-pairwise': __anything,
'wpa-psk': __anything,
'wpa-proto': __anything, # partial(__within,
'wpa-roam': __anything,
'wpa-ssid': __anything, # TODO
}
ATTRMAPS = {
'inet': [IPV4_ATTR_MAP, WIRELESS_ATTR_MAP],
'inet6': [IPV6_ATTR_MAP, WIRELESS_ATTR_MAP]
}
def _validate_interface_option(attr, value, addrfam='inet'):
'''lookup the validation function for a [addrfam][attr] and
return the results
:param attr: attribute name
:param value: raw setting value
:param addrfam: address family (inet, inet6,
'''
valid, _value, errmsg = False, value, 'Unknown validator'
attrmaps = ATTRMAPS.get(addrfam, [])
for attrmap in attrmaps:
if attr in attrmap:
validate_func = attrmap[attr]
(valid, _value, errmsg) = validate_func(value)
break
return (valid, _value, errmsg)
def _attrmaps_contain_attr(attr):
return (
attr in WIRELESS_ATTR_MAP or
attr in IPV4_ATTR_MAP or
attr in IPV6_ATTR_MAP)
def _parse_interfaces(interface_files=None):
'''
Parse /etc/network/interfaces and return current configured interfaces
'''
if interface_files is None:
interface_files = []
# Add this later.
if os.path.exists(_DEB_NETWORK_DIR):
interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]
if os.path.isfile(_DEB_NETWORK_FILE):
interface_files.insert(0, _DEB_NETWORK_FILE)
adapters = salt.utils.odict.OrderedDict()
method = -1
for interface_file in interface_files:
with salt.utils.files.fopen(interface_file) as interfaces:
# This ensures iface_dict exists, but does not ensure we're not reading a new interface.
iface_dict = {}
for line in interfaces:
line = salt.utils.stringutils.to_unicode(line)
# Identify the clauses by the first word of each line.
# Go to the next line if the current line is a comment
# or all spaces.
if line.lstrip().startswith('#') or line.isspace():
continue
# Parse the iface clause
if line.startswith('iface'):
sline = line.split()
if len(sline) != 4:
msg = 'Interface file malformed: {0}.'
msg = msg.format(sline)
log.error(msg)
raise AttributeError(msg)
iface_name = sline[1]
addrfam = sline[2]
method = sline[3]
# Create item in dict, if not already there
if iface_name not in adapters:
adapters[iface_name] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters[iface_name]:
adapters[iface_name]['data'] = salt.utils.odict.OrderedDict()
if addrfam not in adapters[iface_name]['data']:
adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict()
iface_dict = adapters[iface_name]['data'][addrfam]
iface_dict['addrfam'] = addrfam
iface_dict['proto'] = method
iface_dict['filename'] = interface_file
# Parse the detail clauses.
elif line[0].isspace():
sline = line.split()
# conf file attr: dns-nameservers
# salt states.network attr: dns
attr, valuestr = line.rstrip().split(None, 1)
if _attrmaps_contain_attr(attr):
if '-' in attr:
attrname = attr.replace('-', '_')
else:
attrname = attr
(valid, value, errmsg) = _validate_interface_option(
attr, valuestr, addrfam)
if attrname == 'address' and 'address' in iface_dict:
if 'addresses' not in iface_dict:
iface_dict['addresses'] = []
iface_dict['addresses'].append(value)
else:
iface_dict[attrname] = value
elif attr in _REV_ETHTOOL_CONFIG_OPTS:
if 'ethtool' not in iface_dict:
iface_dict['ethtool'] = salt.utils.odict.OrderedDict()
iface_dict['ethtool'][attr] = valuestr
elif attr.startswith('bond'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bonding' not in iface_dict:
iface_dict['bonding'] = salt.utils.odict.OrderedDict()
iface_dict['bonding'][opt] = valuestr
elif attr.startswith('bridge'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bridging' not in iface_dict:
iface_dict['bridging'] = salt.utils.odict.OrderedDict()
iface_dict['bridging'][opt] = valuestr
elif attr in ['up', 'pre-up', 'post-up',
'down', 'pre-down', 'post-down']:
cmd = valuestr
cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr))
if cmd_key not in iface_dict:
iface_dict[cmd_key] = []
iface_dict[cmd_key].append(cmd)
elif line.startswith('auto'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['enabled'] = True
elif line.startswith('allow-hotplug'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['hotplug'] = True
elif line.startswith('source'):
if 'source' not in adapters:
adapters['source'] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters['source']:
adapters['source']['data'] = salt.utils.odict.OrderedDict()
adapters['source']['data']['sources'] = []
adapters['source']['data']['sources'].append(line.split()[1])
# Return a sorted list of the keys for bond, bridge and ethtool options to
# ensure a consistent order
for iface_name in adapters:
if iface_name == 'source':
continue
if 'data' not in adapters[iface_name]:
msg = 'Interface file malformed for interface: {0}.'.format(iface_name)
log.error(msg)
adapters.pop(iface_name)
continue
for opt in ['ethtool', 'bonding', 'bridging']:
for inet in ['inet', 'inet6']:
if inet in adapters[iface_name]['data']:
if opt in adapters[iface_name]['data'][inet]:
opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys())
adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys
return adapters
def _parse_ethtool_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
if 'autoneg' in opts:
if opts['autoneg'] in _CONFIG_TRUE:
config.update({'autoneg': 'on'})
elif opts['autoneg'] in _CONFIG_FALSE:
config.update({'autoneg': 'off'})
else:
_raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE)
if 'duplex' in opts:
valid = ['full', 'half']
if opts['duplex'] in valid:
config.update({'duplex': opts['duplex']})
else:
_raise_error_iface(iface, 'duplex', valid)
if 'speed' in opts:
valid = ['10', '100', '1000', '10000']
if six.text_type(opts['speed']) in valid:
config.update({'speed': opts['speed']})
else:
_raise_error_iface(iface, opts['speed'], valid)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'on'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'off'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_settings_bond(opts, iface):
'''
Filters given options and outputs valid settings for requested
operation. If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond_def = {
# 803.ad aggregation selection logic
# 0 for stable (default)
# 1 for bandwidth
# 2 for count
'ad_select': '0',
# Max number of transmit queues (default = 16)
'tx_queues': '16',
# Link monitoring in milliseconds. Most NICs support this
'miimon': '100',
# ARP interval in milliseconds
'arp_interval': '250',
# Delay before considering link down in milliseconds (miimon * 2)
'downdelay': '200',
# lacp_rate 0: Slow - every 30 seconds
# lacp_rate 1: Fast - every 1 second
'lacp_rate': '0',
# Max bonds for this driver
'max_bonds': '1',
# Specifies the time, in milliseconds, to wait before
# enabling a slave after a link recovery has been
# detected. Only used with miimon.
'updelay': '0',
# Used with miimon.
# On: driver sends mii
# Off: ethtool sends mii
'use_carrier': 'on',
# Default. Don't change unless you know what you are doing.
'xmit_hash_policy': 'layer2',
}
if opts['mode'] in ['balance-rr', '0']:
log.info('Device: %s Bonding Mode: load balancing (round-robin)', iface)
return _parse_settings_bond_0(opts, iface, bond_def)
elif opts['mode'] in ['active-backup', '1']:
log.info('Device: %s Bonding Mode: fault-tolerance (active-backup)', iface)
return _parse_settings_bond_1(opts, iface, bond_def)
elif opts['mode'] in ['balance-xor', '2']:
log.info('Device: %s Bonding Mode: load balancing (xor)', iface)
return _parse_settings_bond_2(opts, iface, bond_def)
elif opts['mode'] in ['broadcast', '3']:
log.info('Device: %s Bonding Mode: fault-tolerance (broadcast)', iface)
return _parse_settings_bond_3(opts, iface, bond_def)
elif opts['mode'] in ['802.3ad', '4']:
log.info('Device: %s Bonding Mode: IEEE 802.3ad Dynamic link '
'aggregation', iface)
return _parse_settings_bond_4(opts, iface, bond_def)
elif opts['mode'] in ['balance-tlb', '5']:
log.info('Device: %s Bonding Mode: transmit load balancing', iface)
return _parse_settings_bond_5(opts, iface, bond_def)
elif opts['mode'] in ['balance-alb', '6']:
log.info('Device: %s Bonding Mode: adaptive load balancing', iface)
return _parse_settings_bond_6(opts, iface, bond_def)
else:
valid = [
'0', '1', '2', '3', '4', '5', '6',
'balance-rr', 'active-backup', 'balance-xor',
'broadcast', '802.3ad', 'balance-tlb', 'balance-alb'
]
_raise_error_iface(iface, 'mode', valid)
def _parse_settings_bond_0(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond0.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '0'}
# ARP targets in n.n.n.n form
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
return bond
def _parse_settings_bond_1(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '1'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
if not (__grains__['os'] == "Ubuntu" and __grains__['osrelease_info'][0] >= 16):
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_2(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond2.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '2'}
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_3(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond3.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '3'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_4(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond4.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '4'}
for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']:
if binding in opts:
if binding == 'lacp_rate':
if opts[binding] == 'fast':
opts.update({binding: '1'})
if opts[binding] == 'slow':
opts.update({binding: '0'})
valid = ['fast', '1', 'slow', '0']
else:
valid = ['integer']
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, valid)
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_5(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond5.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '5'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_settings_bond_6(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond6.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '6'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_bridge_opts(opts, iface):
'''
Filters given options and outputs valid settings for BRIDGING_OPTS
If an option has a value that is not expected, this
function will log the Interface, Setting and what was expected.
'''
config = {}
if 'ports' in opts:
if isinstance(opts['ports'], list):
opts['ports'] = ' '.join(opts['ports'])
config.update({'ports': opts['ports']})
for opt in ['ageing', 'fd', 'gcint', 'hello', 'maxage']:
if opt in opts:
try:
float(opts[opt])
config.update({opt: opts[opt]})
except ValueError:
_raise_error_iface(iface, opt, ['float'])
for opt in ['bridgeprio', 'maxwait']:
if opt in opts:
if isinstance(opts[opt], int):
config.update({opt: opts[opt]})
else:
_raise_error_iface(iface, opt, ['integer'])
if 'hw' in opts:
# match 12 hex digits with either : or - as separators between pairs
if re.match('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$',
opts['hw'].lower()):
config.update({'hw': opts['hw']})
else:
_raise_error_iface(iface, 'hw', ['valid MAC address'])
for opt in ['pathcost', 'portprio']:
if opt in opts:
try:
port, cost_or_prio = opts[opt].split()
int(cost_or_prio)
config.update({opt: '{0} {1}'.format(port, cost_or_prio)})
except ValueError:
_raise_error_iface(iface, opt, ['interface integer'])
if 'stp' in opts:
if opts['stp'] in _CONFIG_TRUE:
config.update({'stp': 'on'})
elif opts['stp'] in _CONFIG_FALSE:
config.update({'stp': 'off'})
else:
_raise_error_iface(iface, 'stp', _CONFIG_TRUE + _CONFIG_FALSE)
if 'waitport' in opts:
if isinstance(opts['waitport'], int):
config.update({'waitport': opts['waitport']})
else:
values = opts['waitport'].split()
waitport_time = values.pop(0)
if waitport_time.isdigit() and values:
config.update({
'waitport': '{0} {1}'.format(
waitport_time, ' '.join(values)
)
})
else:
_raise_error_iface(iface, opt, ['integer [interfaces]'])
return config
def _parse_settings_eth(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['inet'] = salt.utils.odict.OrderedDict()
iface_data['inet6'] = salt.utils.odict.OrderedDict()
if enabled:
adapters[iface]['enabled'] = True
if opts.get('hotplug', False):
adapters[iface]['hotplug'] = True
if opts.get('enable_ipv6', None) and opts.get('iface_type', '') == 'vlan':
iface_data['inet6']['vlan_raw_device'] = (
re.sub(r'\.\d*', '', iface))
for addrfam in ['inet', 'inet6']:
if iface_type not in ['bridge']:
tmp_ethtool = _parse_ethtool_opts(opts, iface)
if tmp_ethtool:
ethtool = {}
for item in tmp_ethtool:
ethtool[_ETHTOOL_CONFIG_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['ethtool'] = ethtool
# return a list of sorted keys to ensure consistent order
iface_data[addrfam]['ethtool_keys'] = sorted(ethtool)
if iface_type == 'bridge':
bridging = _parse_bridge_opts(opts, iface)
if bridging:
iface_data[addrfam]['bridging'] = bridging
iface_data[addrfam]['bridging_keys'] = sorted(bridging)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'bond':
bonding = _parse_settings_bond(opts, iface)
if bonding:
iface_data[addrfam]['bonding'] = bonding
iface_data[addrfam]['bonding']['slaves'] = opts['slaves']
iface_data[addrfam]['bonding_keys'] = sorted(bonding)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'slave':
adapters[iface]['master'] = opts['master']
opts['proto'] = 'manual'
iface_data[addrfam]['master'] = adapters[iface]['master']
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'vlan':
iface_data[addrfam]['vlan_raw_device'] = re.sub(r'\.\d*', '', iface)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'pppoe':
tmp_ethtool = _parse_ethtool_pppoe_opts(opts, iface)
if tmp_ethtool:
for item in tmp_ethtool:
adapters[iface]['data'][addrfam][_DEB_CONFIG_PPPOE_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['addrfam'] = addrfam
opts.pop('mode', None)
for opt, val in opts.items():
inet = None
if opt.startswith('ipv4'):
opt = opt[4:]
inet = 'inet'
iface_data['inet']['addrfam'] = 'inet'
elif opt.startswith('ipv6'):
iface_data['inet6']['addrfam'] = 'inet6'
opt = opt[4:]
inet = 'inet6'
elif opt in ['ipaddr', 'address', 'ipaddresses', 'addresses', 'gateway', 'proto']:
iface_data['inet']['addrfam'] = 'inet'
inet = 'inet'
_opt = SALT_ATTR_TO_DEBIAN_ATTR_MAP.get(opt, opt)
_debopt = _opt.replace('-', '_')
for addrfam in ['inet', 'inet6']:
(valid, value, errmsg) = _validate_interface_option(_opt, val, addrfam=addrfam)
if not valid:
continue
if inet is None and _debopt not in iface_data[addrfam]:
iface_data[addrfam][_debopt] = value
elif inet == addrfam:
iface_data[addrfam][_debopt] = value
for opt in ['up_cmds', 'pre_up_cmds', 'post_up_cmds',
'down_cmds', 'pre_down_cmds', 'post_down_cmds']:
if opt in opts:
iface_data['inet'][opt] = opts[opt]
iface_data['inet6'][opt] = opts[opt]
# Remove incomplete/disabled inet blocks
for (addrfam, opt) in [('inet', 'enable_ipv4'), ('inet6', 'enable_ipv6')]:
if opts.get(opt, None) is False:
iface_data.pop(addrfam)
elif iface_data[addrfam].get('addrfam', '') != addrfam:
iface_data.pop(addrfam)
return adapters
def _parse_settings_source(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['sources'] = [opts['source']]
return adapters
def _parse_network_settings(opts, current):
'''
Filters given options and outputs valid settings for
the global network settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
current = dict((k.lower(), v) for (k, v) in six.iteritems(current))
result = {}
valid = _CONFIG_TRUE + _CONFIG_FALSE
if 'enabled' not in opts:
try:
opts['networking'] = current['networking']
_log_default_network('networking', current['networking'])
except ValueError:
_raise_error_network('networking', valid)
else:
opts['networking'] = opts['enabled']
if opts['networking'] in valid:
if opts['networking'] in _CONFIG_TRUE:
result['networking'] = 'yes'
elif opts['networking'] in _CONFIG_FALSE:
result['networking'] = 'no'
else:
_raise_error_network('networking', valid)
if 'hostname' not in opts:
try:
opts['hostname'] = current['hostname']
_log_default_network('hostname', current['hostname'])
except ValueError:
_raise_error_network('hostname', ['server1.example.com'])
if opts['hostname']:
result['hostname'] = opts['hostname']
else:
_raise_error_network('hostname', ['server1.example.com'])
if 'search' in opts:
result['search'] = opts['search']
return result
def _parse_routes(iface, opts):
'''
Filters given options and outputs valid settings for
the route settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
result = {}
if 'routes' not in opts:
_raise_error_routes(iface, 'routes', 'List of routes')
for opt in opts:
result[opt] = opts[opt]
return result
def _write_file(iface, data, folder, pattern):
'''
Writes a file to disk
'''
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
return filename
def _write_file_routes(iface, data, folder, pattern):
'''
Writes a file to disk
'''
# ifup / ifdown is executing given folder via run-parts.
# according to run-parts man-page, only filenames with this pattern are
# executed: (^[a-zA-Z0-9_-]+$)
# In order to make the routes file work for vlan interfaces
# (default would have been in example /etc/network/if-up.d/route-bond0.12)
# these dots in the iface name need to be replaced by underscores, so it
# can be executed by run-parts
iface = iface.replace('.', '_')
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
__salt__['file.set_mode'](filename, '0755')
return filename
def _write_file_network(data, filename, create=False):
'''
Writes a file to disk
If file does not exist, only create if create
argument is True
'''
if not os.path.exists(filename) and not create:
msg = '{0} cannot be written. {0} does not exist\
and create is set to False'
msg = msg.format(filename)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
def _read_temp(data):
'''
Return what would be written to disk
'''
tout = StringIO()
tout.write(data)
tout.seek(0)
output = tout.readlines()
tout.close()
return output
def _read_temp_ifaces(iface, data):
'''
Return what would be written to disk for interfaces
'''
try:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': data})
# Return as an array so the difflib works
return [item + '\n' for item in ifcfg.split('\n')]
def _write_file_ifaces(iface, data, **settings):
'''
Writes a file to disk
'''
try:
eth_template = JINJA.get_template('debian_eth.jinja')
source_template = JINJA.get_template('debian_source.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
# Read /etc/network/interfaces into a dict
adapters = _parse_interfaces()
# Apply supplied settings over on-disk settings
adapters[iface] = data
ifcfg = ''
for adapter in adapters:
if 'type' in adapters[adapter] and adapters[adapter]['type'] == 'source':
tmp = source_template.render({'name': adapter, 'data': adapters[adapter]})
else:
tmp = eth_template.render({'name': adapter, 'data': adapters[adapter]})
ifcfg = ifcfg + tmp
if adapter == iface:
saved_ifcfg = tmp
_SEPARATE_FILE = False
if 'filename' in settings:
if not settings['filename'].startswith('/'):
filename = '{0}/{1}'.format(_DEB_NETWORK_DIR, settings['filename'])
else:
filename = settings['filename']
_SEPARATE_FILE = True
else:
if 'filename' in adapters[adapter]['data']:
filename = adapters[adapter]['data']
else:
filename = _DEB_NETWORK_FILE
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
if _SEPARATE_FILE:
fout.write(salt.utils.stringutils.to_str(saved_ifcfg))
else:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return saved_ifcfg.split('\n')
def _write_file_ppp_ifaces(iface, data):
'''
Writes a file to disk
'''
try:
template = JINJA.get_template('debian_ppp_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_ppp_eth.jinja')
return ''
adapters = _parse_interfaces()
adapters[iface] = data
ifcfg = ''
tmp = template.render({'data': adapters[iface]})
ifcfg = tmp + ifcfg
filename = _DEB_PPP_DIR + '/' + adapters[iface]['data']['inet']['provider']
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.fopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return filename
def build_bond(iface, **settings):
'''
Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb
'''
deb_major = __grains__['osrelease'][:1]
opts = _parse_settings_bond(settings, iface)
try:
template = JINJA.get_template('conf.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template conf.jinja')
return ''
data = template.render({'name': iface, 'bonding': opts})
if 'test' in settings and settings['test']:
return _read_temp(data)
_write_file(iface, data, _DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
if deb_major == '5':
for line_type in ('alias', 'options'):
cmd = ['sed', '-i', '-e', r'/^{0}\s{1}.*/d'.format(line_type, iface),
'/etc/modprobe.conf']
__salt__['cmd.run'](cmd, python_shell=False)
__salt__['file.append']('/etc/modprobe.conf', path)
# Load kernel module
__salt__['kmod.load']('bonding')
# install ifenslave-2.6
__salt__['pkg.install']('ifenslave-2.6')
return _read_file(path)
def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'vlan':
settings['vlan'] = 'yes'
__salt__['pkg.install']('vlan')
elif iface_type == 'pppoe':
settings['pppoe'] = 'yes'
if not __salt__['pkg.version']('ppp'):
inst = __salt__['pkg.install']('ppp')
elif iface_type == 'bond':
if 'slaves' not in settings:
msg = 'slaves is a required setting for bond interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'bridge':
if 'ports' not in settings:
msg = (
'ports is a required setting for bridge interfaces on Debian '
'or Ubuntu based systems'
)
log.error(msg)
raise AttributeError(msg)
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'pppoe']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
if iface_type in ['source']:
opts = _parse_settings_source(settings, iface_type, enabled, iface)
if 'test' in settings and settings['test']:
return _read_temp_ifaces(iface, opts[iface])
ifcfg = _write_file_ifaces(iface, opts[iface], **settings)
if iface_type == 'pppoe':
_write_file_ppp_ifaces(iface, opts[iface])
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg]
def build_routes(iface, **settings):
'''
Add route scripts for a network interface using up commands.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
'''
opts = _parse_routes(iface, settings)
try:
template = JINJA.get_template('route_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template route_eth.jinja')
return ''
add_routecfg = template.render(route_type='add',
routes=opts['routes'],
iface=iface)
del_routecfg = template.render(route_type='del',
routes=opts['routes'],
iface=iface)
if 'test' in settings and settings['test']:
return _read_temp(add_routecfg + del_routecfg)
filename = _write_file_routes(iface,
add_routecfg,
_DEB_NETWORK_UP_DIR,
'route-{0}')
results = _read_file(filename)
filename = _write_file_routes(iface,
del_routecfg,
_DEB_NETWORK_DOWN_DIR,
'route-{0}')
results += _read_file(filename)
return results
def down(iface, iface_type):
'''
Shutdown a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.down eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought down.
if iface_type not in ['slave', 'source']:
return __salt__['cmd.run'](['ifdown', iface])
return None
def get_bond(iface):
'''
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
'''
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
return _read_file(path)
def get_interface(iface):
'''
Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
adapters = _parse_interfaces()
if iface in adapters:
try:
if iface == 'source':
template = JINJA.get_template('debian_source.jinja')
else:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': adapters[iface]})
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg.split('\n')]
else:
return []
def up(iface, iface_type): # pylint: disable=C0103
'''
Start up a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.up eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought up.
if iface_type not in ('slave', 'source'):
return __salt__['cmd.run'](['ifup', iface])
return None
def get_network_settings():
'''
Return the contents of the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_network_settings
'''
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
settings = {}
if __salt__['service.available']('networking'):
if __salt__['service.status']('networking'):
settings['networking'] = "yes"
else:
settings['networking'] = "no"
else:
settings['networking'] = "no"
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
settings['hostname'] = hostname
settings['domainname'] = domainname
settings['searchdomain'] = searchdomain
else:
settings = _parse_current_network_settings()
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(settings)
return _read_temp(network)
def get_routes(iface):
'''
Return the routes for the interface
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0
'''
filename = os.path.join(_DEB_NETWORK_UP_DIR, 'route-{0}'.format(iface))
results = _read_file(filename)
filename = os.path.join(_DEB_NETWORK_DOWN_DIR, 'route-{0}'.format(iface))
results += _read_file(filename)
return results
def apply_network_settings(**settings):
'''
Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings
'''
if 'require_reboot' not in settings:
settings['require_reboot'] = False
if 'apply_hostname' not in settings:
settings['apply_hostname'] = False
hostname_res = True
if settings['apply_hostname'] in _CONFIG_TRUE:
if 'hostname' in settings:
hostname_res = __salt__['network.mod_hostname'](settings['hostname'])
else:
log.warning(
'The network state sls is trying to apply hostname '
'changes but no hostname is defined.'
)
hostname_res = False
res = True
if settings['require_reboot'] in _CONFIG_TRUE:
log.warning(
'The network state sls is requiring a reboot of the system to '
'properly apply network configuration.'
)
res = True
else:
stop = __salt__['service.stop']('networking')
time.sleep(2)
res = stop and __salt__['service.start']('networking')
return hostname_res and res
def build_network_settings(**settings):
'''
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
'''
changes = []
# Read current configuration and store default values
current_network_settings = _parse_current_network_settings()
# Build settings
opts = _parse_network_settings(settings, current_network_settings)
# Ubuntu has moved away from /etc/default/networking
# beginning with the 12.04 release so we disable or enable
# the networking related services on boot
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
if opts['networking'] == 'yes':
service_cmd = 'service.enable'
else:
service_cmd = 'service.disable'
if __salt__['service.available']('NetworkManager'):
__salt__[service_cmd]('NetworkManager')
if __salt__['service.available']('networking'):
__salt__[service_cmd]('networking')
else:
try:
template = JINJA.get_template('network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template network.jinja')
return ''
network = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(network)
# Write settings
_write_file_network(network, _DEB_NETWORKING_FILE, True)
# Get hostname and domain from opts
sline = opts['hostname'].split('.', 1)
opts['hostname'] = sline[0]
current_domainname = current_network_settings['domainname']
current_searchdomain = current_network_settings['searchdomain']
new_domain = False
if len(sline) > 1:
new_domainname = sline[1]
if new_domainname != current_domainname:
domainname = new_domainname
opts['domainname'] = new_domainname
new_domain = True
else:
domainname = current_domainname
opts['domainname'] = domainname
else:
domainname = current_domainname
opts['domainname'] = domainname
new_search = False
if 'search' in opts:
new_searchdomain = opts['search']
if new_searchdomain != current_searchdomain:
searchdomain = new_searchdomain
opts['searchdomain'] = new_searchdomain
new_search = True
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
# If the domain changes, then we should write the resolv.conf file.
if new_domain or new_search:
# Look for existing domain line and update if necessary
resolve = _parse_resolve()
domain_prog = re.compile(r'domain\s+')
search_prog = re.compile(r'search\s+')
new_contents = []
for item in _read_file(_DEB_RESOLV_FILE):
if domain_prog.match(item):
item = 'domain {0}'.format(domainname)
elif search_prog.match(item):
item = 'search {0}'.format(searchdomain)
new_contents.append(item)
# A domain line didn't exist so we'll add one in
# with the new domainname
if 'domain' not in resolve:
new_contents.insert(0, 'domain {0}' . format(domainname))
# A search line didn't exist so we'll add one in
# with the new search domain
if 'search' not in resolve:
new_contents.insert('domain' in resolve, 'search {0}'.format(searchdomain))
new_resolv = '\n'.join(new_contents)
# Write /etc/resolv.conf
if not ('test' in settings and settings['test']):
_write_file_network(new_resolv, _DEB_RESOLV_FILE)
# used for returning the results back
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(opts)
changes.extend(_read_temp(network))
return changes
|
saltstack/salt
|
salt/modules/debian_ip.py
|
_parse_settings_bond
|
python
|
def _parse_settings_bond(opts, iface):
'''
Filters given options and outputs valid settings for requested
operation. If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond_def = {
# 803.ad aggregation selection logic
# 0 for stable (default)
# 1 for bandwidth
# 2 for count
'ad_select': '0',
# Max number of transmit queues (default = 16)
'tx_queues': '16',
# Link monitoring in milliseconds. Most NICs support this
'miimon': '100',
# ARP interval in milliseconds
'arp_interval': '250',
# Delay before considering link down in milliseconds (miimon * 2)
'downdelay': '200',
# lacp_rate 0: Slow - every 30 seconds
# lacp_rate 1: Fast - every 1 second
'lacp_rate': '0',
# Max bonds for this driver
'max_bonds': '1',
# Specifies the time, in milliseconds, to wait before
# enabling a slave after a link recovery has been
# detected. Only used with miimon.
'updelay': '0',
# Used with miimon.
# On: driver sends mii
# Off: ethtool sends mii
'use_carrier': 'on',
# Default. Don't change unless you know what you are doing.
'xmit_hash_policy': 'layer2',
}
if opts['mode'] in ['balance-rr', '0']:
log.info('Device: %s Bonding Mode: load balancing (round-robin)', iface)
return _parse_settings_bond_0(opts, iface, bond_def)
elif opts['mode'] in ['active-backup', '1']:
log.info('Device: %s Bonding Mode: fault-tolerance (active-backup)', iface)
return _parse_settings_bond_1(opts, iface, bond_def)
elif opts['mode'] in ['balance-xor', '2']:
log.info('Device: %s Bonding Mode: load balancing (xor)', iface)
return _parse_settings_bond_2(opts, iface, bond_def)
elif opts['mode'] in ['broadcast', '3']:
log.info('Device: %s Bonding Mode: fault-tolerance (broadcast)', iface)
return _parse_settings_bond_3(opts, iface, bond_def)
elif opts['mode'] in ['802.3ad', '4']:
log.info('Device: %s Bonding Mode: IEEE 802.3ad Dynamic link '
'aggregation', iface)
return _parse_settings_bond_4(opts, iface, bond_def)
elif opts['mode'] in ['balance-tlb', '5']:
log.info('Device: %s Bonding Mode: transmit load balancing', iface)
return _parse_settings_bond_5(opts, iface, bond_def)
elif opts['mode'] in ['balance-alb', '6']:
log.info('Device: %s Bonding Mode: adaptive load balancing', iface)
return _parse_settings_bond_6(opts, iface, bond_def)
else:
valid = [
'0', '1', '2', '3', '4', '5', '6',
'balance-rr', 'active-backup', 'balance-xor',
'broadcast', '802.3ad', 'balance-tlb', 'balance-alb'
]
_raise_error_iface(iface, 'mode', valid)
|
Filters given options and outputs valid settings for requested
operation. If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_ip.py#L768-L835
|
[
"def _raise_error_iface(iface, option, expected):\n '''\n Log and raise an error with a logical formatted message.\n '''\n msg = _error_msg_iface(iface, option, expected)\n log.error(msg)\n raise AttributeError(msg)\n",
"def _parse_settings_bond_0(opts, iface, bond_def):\n '''\n Filters given options and outputs valid settings for bond0.\n If an option has a value that is not expected, this\n function will log what the Interface, Setting and what it was\n expecting.\n '''\n bond = {'mode': '0'}\n\n # ARP targets in n.n.n.n form\n valid = ['list of ips (up to 16)']\n if 'arp_ip_target' in opts:\n if isinstance(opts['arp_ip_target'], list):\n if 1 <= len(opts['arp_ip_target']) <= 16:\n bond.update({'arp_ip_target': ''})\n for ip in opts['arp_ip_target']: # pylint: disable=C0103\n if bond['arp_ip_target']:\n bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip\n else:\n bond['arp_ip_target'] = ip\n else:\n _raise_error_iface(iface, 'arp_ip_target', valid)\n else:\n _raise_error_iface(iface, 'arp_ip_target', valid)\n else:\n _raise_error_iface(iface, 'arp_ip_target', valid)\n\n if 'arp_interval' in opts:\n try:\n int(opts['arp_interval'])\n bond.update({'arp_interval': opts['arp_interval']})\n except ValueError:\n _raise_error_iface(iface, 'arp_interval', ['integer'])\n else:\n _log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])\n bond.update({'arp_interval': bond_def['arp_interval']})\n\n return bond\n",
"def _parse_settings_bond_1(opts, iface, bond_def):\n\n '''\n Filters given options and outputs valid settings for bond1.\n If an option has a value that is not expected, this\n function will log what the Interface, Setting and what it was\n expecting.\n '''\n bond = {'mode': '1'}\n\n for binding in ['miimon', 'downdelay', 'updelay']:\n if binding in opts:\n try:\n int(opts[binding])\n bond.update({binding: opts[binding]})\n except ValueError:\n _raise_error_iface(iface, binding, ['integer'])\n else:\n _log_default_iface(iface, binding, bond_def[binding])\n bond.update({binding: bond_def[binding]})\n\n if 'primary' in opts:\n bond.update({'primary': opts['primary']})\n\n if not (__grains__['os'] == \"Ubuntu\" and __grains__['osrelease_info'][0] >= 16):\n if 'use_carrier' in opts:\n if opts['use_carrier'] in _CONFIG_TRUE:\n bond.update({'use_carrier': '1'})\n elif opts['use_carrier'] in _CONFIG_FALSE:\n bond.update({'use_carrier': '0'})\n else:\n valid = _CONFIG_TRUE + _CONFIG_FALSE\n _raise_error_iface(iface, 'use_carrier', valid)\n else:\n _log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])\n bond.update({'use_carrier': bond_def['use_carrier']})\n\n return bond\n",
"def _parse_settings_bond_2(opts, iface, bond_def):\n '''\n Filters given options and outputs valid settings for bond2.\n If an option has a value that is not expected, this\n function will log what the Interface, Setting and what it was\n expecting.\n '''\n\n bond = {'mode': '2'}\n\n valid = ['list of ips (up to 16)']\n if 'arp_ip_target' in opts:\n if isinstance(opts['arp_ip_target'], list):\n if 1 <= len(opts['arp_ip_target']) <= 16:\n bond.update({'arp_ip_target': ''})\n for ip in opts['arp_ip_target']: # pylint: disable=C0103\n if bond['arp_ip_target']:\n bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip\n else:\n bond['arp_ip_target'] = ip\n else:\n _raise_error_iface(iface, 'arp_ip_target', valid)\n else:\n _raise_error_iface(iface, 'arp_ip_target', valid)\n else:\n _raise_error_iface(iface, 'arp_ip_target', valid)\n\n if 'arp_interval' in opts:\n try:\n int(opts['arp_interval'])\n bond.update({'arp_interval': opts['arp_interval']})\n except ValueError:\n _raise_error_iface(iface, 'arp_interval', ['integer'])\n else:\n _log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])\n bond.update({'arp_interval': bond_def['arp_interval']})\n\n if 'hashing-algorithm' in opts:\n valid = ['layer2', 'layer2+3', 'layer3+4']\n if opts['hashing-algorithm'] in valid:\n bond.update({'xmit_hash_policy': opts['hashing-algorithm']})\n else:\n _raise_error_iface(iface, 'hashing-algorithm', valid)\n\n return bond\n",
"def _parse_settings_bond_3(opts, iface, bond_def):\n\n '''\n Filters given options and outputs valid settings for bond3.\n If an option has a value that is not expected, this\n function will log what the Interface, Setting and what it was\n expecting.\n '''\n bond = {'mode': '3'}\n\n for binding in ['miimon', 'downdelay', 'updelay']:\n if binding in opts:\n try:\n int(opts[binding])\n bond.update({binding: opts[binding]})\n except ValueError:\n _raise_error_iface(iface, binding, ['integer'])\n else:\n _log_default_iface(iface, binding, bond_def[binding])\n bond.update({binding: bond_def[binding]})\n\n if 'use_carrier' in opts:\n if opts['use_carrier'] in _CONFIG_TRUE:\n bond.update({'use_carrier': '1'})\n elif opts['use_carrier'] in _CONFIG_FALSE:\n bond.update({'use_carrier': '0'})\n else:\n valid = _CONFIG_TRUE + _CONFIG_FALSE\n _raise_error_iface(iface, 'use_carrier', valid)\n else:\n _log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])\n bond.update({'use_carrier': bond_def['use_carrier']})\n\n return bond\n",
"def _parse_settings_bond_4(opts, iface, bond_def):\n '''\n Filters given options and outputs valid settings for bond4.\n If an option has a value that is not expected, this\n function will log what the Interface, Setting and what it was\n expecting.\n '''\n\n bond = {'mode': '4'}\n\n for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']:\n if binding in opts:\n if binding == 'lacp_rate':\n if opts[binding] == 'fast':\n opts.update({binding: '1'})\n if opts[binding] == 'slow':\n opts.update({binding: '0'})\n valid = ['fast', '1', 'slow', '0']\n else:\n valid = ['integer']\n try:\n int(opts[binding])\n bond.update({binding: opts[binding]})\n except ValueError:\n _raise_error_iface(iface, binding, valid)\n else:\n _log_default_iface(iface, binding, bond_def[binding])\n bond.update({binding: bond_def[binding]})\n\n if 'use_carrier' in opts:\n if opts['use_carrier'] in _CONFIG_TRUE:\n bond.update({'use_carrier': '1'})\n elif opts['use_carrier'] in _CONFIG_FALSE:\n bond.update({'use_carrier': '0'})\n else:\n valid = _CONFIG_TRUE + _CONFIG_FALSE\n _raise_error_iface(iface, 'use_carrier', valid)\n else:\n _log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])\n bond.update({'use_carrier': bond_def['use_carrier']})\n\n if 'hashing-algorithm' in opts:\n valid = ['layer2', 'layer2+3', 'layer3+4']\n if opts['hashing-algorithm'] in valid:\n bond.update({'xmit_hash_policy': opts['hashing-algorithm']})\n else:\n _raise_error_iface(iface, 'hashing-algorithm', valid)\n\n return bond\n",
"def _parse_settings_bond_5(opts, iface, bond_def):\n\n '''\n Filters given options and outputs valid settings for bond5.\n If an option has a value that is not expected, this\n function will log what the Interface, Setting and what it was\n expecting.\n '''\n bond = {'mode': '5'}\n\n for binding in ['miimon', 'downdelay', 'updelay']:\n if binding in opts:\n try:\n int(opts[binding])\n bond.update({binding: opts[binding]})\n except ValueError:\n _raise_error_iface(iface, binding, ['integer'])\n else:\n _log_default_iface(iface, binding, bond_def[binding])\n bond.update({binding: bond_def[binding]})\n\n if 'use_carrier' in opts:\n if opts['use_carrier'] in _CONFIG_TRUE:\n bond.update({'use_carrier': '1'})\n elif opts['use_carrier'] in _CONFIG_FALSE:\n bond.update({'use_carrier': '0'})\n else:\n valid = _CONFIG_TRUE + _CONFIG_FALSE\n _raise_error_iface(iface, 'use_carrier', valid)\n else:\n _log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])\n bond.update({'use_carrier': bond_def['use_carrier']})\n\n if 'primary' in opts:\n bond.update({'primary': opts['primary']})\n\n return bond\n",
"def _parse_settings_bond_6(opts, iface, bond_def):\n\n '''\n Filters given options and outputs valid settings for bond6.\n If an option has a value that is not expected, this\n function will log what the Interface, Setting and what it was\n expecting.\n '''\n bond = {'mode': '6'}\n\n for binding in ['miimon', 'downdelay', 'updelay']:\n if binding in opts:\n try:\n int(opts[binding])\n bond.update({binding: opts[binding]})\n except ValueError:\n _raise_error_iface(iface, binding, ['integer'])\n else:\n _log_default_iface(iface, binding, bond_def[binding])\n bond.update({binding: bond_def[binding]})\n\n if 'use_carrier' in opts:\n if opts['use_carrier'] in _CONFIG_TRUE:\n bond.update({'use_carrier': '1'})\n elif opts['use_carrier'] in _CONFIG_FALSE:\n bond.update({'use_carrier': '0'})\n else:\n valid = _CONFIG_TRUE + _CONFIG_FALSE\n _raise_error_iface(iface, 'use_carrier', valid)\n else:\n _log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])\n bond.update({'use_carrier': bond_def['use_carrier']})\n\n if 'primary' in opts:\n bond.update({'primary': opts['primary']})\n\n return bond\n"
] |
# -*- coding: utf-8 -*-
'''
The networking module for Debian-based distros
References:
* http://www.debian.org/doc/manuals/debian-reference/ch05.en.html
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import functools
import logging
import os.path
import os
import re
import time
# Import third party libs
import jinja2
import jinja2.exceptions
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error,no-name-in-module
# Import salt libs
import salt.utils.dns
import salt.utils.files
import salt.utils.odict
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.validate.net
# Set up logging
log = logging.getLogger(__name__)
# Set up template environment
JINJA = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'debian_ip')
)
)
# Define the module's virtual name
__virtualname__ = 'ip'
def __virtual__():
'''
Confine this module to Debian-based distros
'''
if __grains__['os_family'] == 'Debian':
return __virtualname__
return (False, 'The debian_ip module could not be loaded: '
'unsupported OS family')
_ETHTOOL_CONFIG_OPTS = {
'speed': 'link-speed',
'duplex': 'link-duplex',
'autoneg': 'ethernet-autoneg',
'ethernet-port': 'ethernet-port',
'wol': 'ethernet-wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'rx': 'offload-rx',
'tx': 'offload-tx',
'sg': 'offload-sg',
'tso': 'offload-tso',
'ufo': 'offload-ufo',
'gso': 'offload-gso',
'gro': 'offload-gro',
'lro': 'offload-lro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_REV_ETHTOOL_CONFIG_OPTS = {
'link-speed': 'speed',
'link-duplex': 'duplex',
'ethernet-autoneg': 'autoneg',
'ethernet-port': 'ethernet-port',
'ethernet-wol': 'wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'offload-rx': 'rx',
'offload-tx': 'tx',
'offload-sg': 'sg',
'offload-tso': 'tso',
'offload-ufo': 'ufo',
'offload-gso': 'gso',
'offload-lro': 'lro',
'offload-gro': 'gro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_DEB_CONFIG_PPPOE_OPTS = {
'user': 'user',
'password': 'password',
'provider': 'provider',
'pppoe_iface': 'pppoe_iface',
'noipdefault': 'noipdefault',
'usepeerdns': 'usepeerdns',
'defaultroute': 'defaultroute',
'holdoff': 'holdoff',
'maxfail': 'maxfail',
'hide-password': 'hide-password',
'lcp-echo-interval': 'lcp-echo-interval',
'lcp-echo-failure': 'lcp-echo-failure',
'connect': 'connect',
'noauth': 'noauth',
'persist': 'persist',
'mtu': 'mtu',
'noaccomp': 'noaccomp',
'linkname': 'linkname',
}
_DEB_ROUTES_FILE = '/etc/network/routes'
_DEB_NETWORK_FILE = '/etc/network/interfaces'
_DEB_NETWORK_DIR = '/etc/network/interfaces.d/'
_DEB_NETWORK_UP_DIR = '/etc/network/if-up.d/'
_DEB_NETWORK_DOWN_DIR = '/etc/network/if-down.d/'
_DEB_NETWORK_CONF_FILES = '/etc/modprobe.d/'
_DEB_NETWORKING_FILE = '/etc/default/networking'
_DEB_HOSTNAME_FILE = '/etc/hostname'
_DEB_RESOLV_FILE = '/etc/resolv.conf'
_DEB_PPP_DIR = '/etc/ppp/peers/'
_CONFIG_TRUE = ['yes', 'on', 'true', '1', True]
_CONFIG_FALSE = ['no', 'off', 'false', '0', False]
_IFACE_TYPES = [
'eth', 'bond', 'alias', 'clone',
'ipsec', 'dialup', 'bridge', 'slave',
'vlan', 'pppoe', 'source',
]
def _error_msg_iface(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, '|'.join(str(e) for e in expected))
def _error_msg_routes(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, expected)
def _log_default_iface(iface, opt, value):
log.info(
'Using default option -- Interface: %s Option: %s Value: %s',
iface, opt, value
)
def _error_msg_network(option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]'
return msg.format(option, '|'.join(str(e) for e in expected))
def _log_default_network(opt, value):
log.info('Using existing setting -- Setting: %s Value: %s', opt, value)
def _raise_error_iface(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_iface(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_network(option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_network(option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_routes(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_routes(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _read_file(path):
'''
Reads and returns the contents of a text file
'''
try:
with salt.utils.files.flopen(path, 'rb') as contents:
return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]
except (OSError, IOError):
return ''
def _parse_resolve():
'''
Parse /etc/resolv.conf
'''
return salt.utils.dns.parse_resolv(_DEB_RESOLV_FILE)
def _parse_domainname():
'''
Parse /etc/resolv.conf and return domainname
'''
return _parse_resolve().get('domain', '')
def _parse_searchdomain():
'''
Parse /etc/resolv.conf and return searchdomain
'''
return _parse_resolve().get('search', '')
def _parse_hostname():
'''
Parse /etc/hostname and return hostname
'''
contents = _read_file(_DEB_HOSTNAME_FILE)
if contents:
return contents[0].split('\n')[0]
else:
return ''
def _parse_current_network_settings():
'''
Parse /etc/default/networking and return current configuration
'''
opts = salt.utils.odict.OrderedDict()
opts['networking'] = ''
if os.path.isfile(_DEB_NETWORKING_FILE):
with salt.utils.files.fopen(_DEB_NETWORKING_FILE) as contents:
for line in contents:
salt.utils.stringutils.to_unicode(line)
if line.startswith('#'):
continue
elif line.startswith('CONFIGURE_INTERFACES'):
opts['networking'] = line.split('=', 1)[1].strip()
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
opts['hostname'] = hostname
opts['domainname'] = domainname
opts['searchdomain'] = searchdomain
return opts
# def __validator_func(value):
# return (valid: True/False, (transformed) value, error message)
def __ipv4_quad(value):
'''validate an IPv4 address'''
return (salt.utils.validate.net.ipv4_addr(value), value,
'dotted IPv4 address')
def __ipv6(value):
'''validate an IPv6 address'''
return (salt.utils.validate.net.ipv6_addr(value), value,
'IPv6 address')
def __mac(value):
'''validate a mac address'''
return (salt.utils.validate.net.mac(value), value,
'MAC address')
def __anything(value):
return (True, value, None)
def __int(value):
'''validate an integer'''
valid, _value = False, value
try:
_value = int(value)
valid = True
except ValueError:
pass
return (valid, _value, 'integer')
def __float(value):
'''validate a float'''
valid, _value = False, value
try:
_value = float(value)
valid = True
except ValueError:
pass
return (valid, _value, 'float')
def __ipv4_netmask(value):
'''validate an IPv4 dotted quad or integer CIDR netmask'''
valid, errmsg = False, 'dotted quad or integer CIDR (0->32)'
valid, value, _ = __int(value)
if not (valid and 0 <= value <= 32):
valid = salt.utils.validate.net.netmask(value)
return (valid, value, errmsg)
def __ipv6_netmask(value):
'''validate an IPv6 integer netmask'''
valid, errmsg = False, 'IPv6 netmask (0->128)'
valid, value, _ = __int(value)
valid = (valid and 0 <= value <= 128)
return (valid, value, errmsg)
def __within2(value, within=None, errmsg=None, dtype=None):
'''validate that a value is in ``within`` and optionally a ``dtype``'''
valid, _value = False, value
if dtype:
try:
_value = dtype(value) # TODO: this is a bit loose when dtype is a class
valid = _value in within
except ValueError:
pass
else:
valid = _value in within
if errmsg is None:
if dtype:
typename = getattr(dtype, '__name__',
hasattr(dtype, '__class__')
and getattr(dtype.__class__, 'name', dtype))
errmsg = '{0} within \'{1}\''.format(typename, within)
else:
errmsg = 'within \'{0}\''.format(within)
return (valid, _value, errmsg)
def __within(within=None, errmsg=None, dtype=None):
return functools.partial(__within2, within=within,
errmsg=errmsg, dtype=dtype)
def __space_delimited_list(value):
'''validate that a value contains one or more space-delimited values'''
if isinstance(value, six.string_types):
value = value.strip().split()
if hasattr(value, '__iter__') and value != []:
return (True, value, 'space-delimited string')
else:
return (False, value, '{0} is not a valid space-delimited value.\n'.format(value))
SALT_ATTR_TO_DEBIAN_ATTR_MAP = {
'dns': 'dns-nameservers',
'search': 'dns-search',
'hwaddr': 'hwaddress', # TODO: this limits bootp functionality
'ipaddr': 'address',
'ipaddrs': 'addresses',
}
DEBIAN_ATTR_TO_SALT_ATTR_MAP = dict(
(v, k) for (k, v) in six.iteritems(SALT_ATTR_TO_DEBIAN_ATTR_MAP))
# TODO
DEBIAN_ATTR_TO_SALT_ATTR_MAP['address'] = 'address'
DEBIAN_ATTR_TO_SALT_ATTR_MAP['hwaddress'] = 'hwaddress'
IPV4_VALID_PROTO = ['bootp', 'dhcp', 'static', 'manual', 'loopback', 'ppp']
IPV4_ATTR_MAP = {
'proto': __within(IPV4_VALID_PROTO, dtype=six.text_type),
# ipv4 static & manual
'address': __ipv4_quad,
'addresses': __anything,
'netmask': __ipv4_netmask,
'broadcast': __ipv4_quad,
'metric': __int,
'gateway': __ipv4_quad, # supports a colon-delimited list
'pointopoint': __ipv4_quad,
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'link', 'host'], dtype=six.text_type),
# dhcp
'hostname': __anything,
'leasehours': __int,
'leasetime': __int,
'vendor': __anything,
'client': __anything,
# bootp
'bootfile': __anything,
'server': __ipv4_quad,
'hwaddr': __mac,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'dstaddr': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# bond
'slaves': __anything,
# ppp
'provider': __anything,
'unit': __int,
'options': __anything,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
#
'network': __anything, # i don't know what this is
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
IPV6_VALID_PROTO = ['auto', 'loopback', 'static', 'manual',
'dhcp', 'v4tunnel', '6to4']
IPV6_ATTR_MAP = {
'proto': __within(IPV6_VALID_PROTO),
# ipv6 static & manual
'address': __ipv6,
'addresses': __anything,
'netmask': __ipv6_netmask,
'broadcast': __ipv6,
'gateway': __ipv6, # supports a colon-delimited list
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'site', 'link', 'host'], dtype=six.text_type),
# inet6 auto
'privext': __within([0, 1, 2], dtype=int),
'dhcp': __within([0, 1], dtype=int),
# inet6 static & manual & dhcp
'media': __anything,
'accept_ra': __within([0, 1], dtype=int),
'autoconf': __within([0, 1], dtype=int),
'preferred-lifetime': __int,
'dad-attempts': __int, # 0 to disable
'dad-interval': __float,
# bond
'slaves': __anything,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
WIRELESS_ATTR_MAP = {
'wireless-essid': __anything,
'wireless-mode': __anything, # TODO
'wpa-ap-scan': __within([0, 1, 2], dtype=int), # TODO
'wpa-conf': __anything,
'wpa-driver': __anything,
'wpa-group': __anything,
'wpa-key-mgmt': __anything,
'wpa-pairwise': __anything,
'wpa-psk': __anything,
'wpa-proto': __anything, # partial(__within,
'wpa-roam': __anything,
'wpa-ssid': __anything, # TODO
}
ATTRMAPS = {
'inet': [IPV4_ATTR_MAP, WIRELESS_ATTR_MAP],
'inet6': [IPV6_ATTR_MAP, WIRELESS_ATTR_MAP]
}
def _validate_interface_option(attr, value, addrfam='inet'):
'''lookup the validation function for a [addrfam][attr] and
return the results
:param attr: attribute name
:param value: raw setting value
:param addrfam: address family (inet, inet6,
'''
valid, _value, errmsg = False, value, 'Unknown validator'
attrmaps = ATTRMAPS.get(addrfam, [])
for attrmap in attrmaps:
if attr in attrmap:
validate_func = attrmap[attr]
(valid, _value, errmsg) = validate_func(value)
break
return (valid, _value, errmsg)
def _attrmaps_contain_attr(attr):
return (
attr in WIRELESS_ATTR_MAP or
attr in IPV4_ATTR_MAP or
attr in IPV6_ATTR_MAP)
def _parse_interfaces(interface_files=None):
'''
Parse /etc/network/interfaces and return current configured interfaces
'''
if interface_files is None:
interface_files = []
# Add this later.
if os.path.exists(_DEB_NETWORK_DIR):
interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]
if os.path.isfile(_DEB_NETWORK_FILE):
interface_files.insert(0, _DEB_NETWORK_FILE)
adapters = salt.utils.odict.OrderedDict()
method = -1
for interface_file in interface_files:
with salt.utils.files.fopen(interface_file) as interfaces:
# This ensures iface_dict exists, but does not ensure we're not reading a new interface.
iface_dict = {}
for line in interfaces:
line = salt.utils.stringutils.to_unicode(line)
# Identify the clauses by the first word of each line.
# Go to the next line if the current line is a comment
# or all spaces.
if line.lstrip().startswith('#') or line.isspace():
continue
# Parse the iface clause
if line.startswith('iface'):
sline = line.split()
if len(sline) != 4:
msg = 'Interface file malformed: {0}.'
msg = msg.format(sline)
log.error(msg)
raise AttributeError(msg)
iface_name = sline[1]
addrfam = sline[2]
method = sline[3]
# Create item in dict, if not already there
if iface_name not in adapters:
adapters[iface_name] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters[iface_name]:
adapters[iface_name]['data'] = salt.utils.odict.OrderedDict()
if addrfam not in adapters[iface_name]['data']:
adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict()
iface_dict = adapters[iface_name]['data'][addrfam]
iface_dict['addrfam'] = addrfam
iface_dict['proto'] = method
iface_dict['filename'] = interface_file
# Parse the detail clauses.
elif line[0].isspace():
sline = line.split()
# conf file attr: dns-nameservers
# salt states.network attr: dns
attr, valuestr = line.rstrip().split(None, 1)
if _attrmaps_contain_attr(attr):
if '-' in attr:
attrname = attr.replace('-', '_')
else:
attrname = attr
(valid, value, errmsg) = _validate_interface_option(
attr, valuestr, addrfam)
if attrname == 'address' and 'address' in iface_dict:
if 'addresses' not in iface_dict:
iface_dict['addresses'] = []
iface_dict['addresses'].append(value)
else:
iface_dict[attrname] = value
elif attr in _REV_ETHTOOL_CONFIG_OPTS:
if 'ethtool' not in iface_dict:
iface_dict['ethtool'] = salt.utils.odict.OrderedDict()
iface_dict['ethtool'][attr] = valuestr
elif attr.startswith('bond'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bonding' not in iface_dict:
iface_dict['bonding'] = salt.utils.odict.OrderedDict()
iface_dict['bonding'][opt] = valuestr
elif attr.startswith('bridge'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bridging' not in iface_dict:
iface_dict['bridging'] = salt.utils.odict.OrderedDict()
iface_dict['bridging'][opt] = valuestr
elif attr in ['up', 'pre-up', 'post-up',
'down', 'pre-down', 'post-down']:
cmd = valuestr
cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr))
if cmd_key not in iface_dict:
iface_dict[cmd_key] = []
iface_dict[cmd_key].append(cmd)
elif line.startswith('auto'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['enabled'] = True
elif line.startswith('allow-hotplug'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['hotplug'] = True
elif line.startswith('source'):
if 'source' not in adapters:
adapters['source'] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters['source']:
adapters['source']['data'] = salt.utils.odict.OrderedDict()
adapters['source']['data']['sources'] = []
adapters['source']['data']['sources'].append(line.split()[1])
# Return a sorted list of the keys for bond, bridge and ethtool options to
# ensure a consistent order
for iface_name in adapters:
if iface_name == 'source':
continue
if 'data' not in adapters[iface_name]:
msg = 'Interface file malformed for interface: {0}.'.format(iface_name)
log.error(msg)
adapters.pop(iface_name)
continue
for opt in ['ethtool', 'bonding', 'bridging']:
for inet in ['inet', 'inet6']:
if inet in adapters[iface_name]['data']:
if opt in adapters[iface_name]['data'][inet]:
opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys())
adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys
return adapters
def _parse_ethtool_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
if 'autoneg' in opts:
if opts['autoneg'] in _CONFIG_TRUE:
config.update({'autoneg': 'on'})
elif opts['autoneg'] in _CONFIG_FALSE:
config.update({'autoneg': 'off'})
else:
_raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE)
if 'duplex' in opts:
valid = ['full', 'half']
if opts['duplex'] in valid:
config.update({'duplex': opts['duplex']})
else:
_raise_error_iface(iface, 'duplex', valid)
if 'speed' in opts:
valid = ['10', '100', '1000', '10000']
if six.text_type(opts['speed']) in valid:
config.update({'speed': opts['speed']})
else:
_raise_error_iface(iface, opts['speed'], valid)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'on'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'off'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_ethtool_pppoe_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
for opt in _DEB_CONFIG_PPPOE_OPTS:
if opt in opts:
config[opt] = opts[opt]
if 'provider' in opts and not opts['provider']:
_raise_error_iface(iface, 'provider', _CONFIG_TRUE + _CONFIG_FALSE)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('noipdefault', 'usepeerdns', 'defaultroute', 'hide-password', 'noauth', 'persist', 'noaccomp'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'True'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'False'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_settings_bond_0(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond0.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '0'}
# ARP targets in n.n.n.n form
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
return bond
def _parse_settings_bond_1(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '1'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
if not (__grains__['os'] == "Ubuntu" and __grains__['osrelease_info'][0] >= 16):
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_2(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond2.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '2'}
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_3(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond3.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '3'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_4(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond4.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '4'}
for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']:
if binding in opts:
if binding == 'lacp_rate':
if opts[binding] == 'fast':
opts.update({binding: '1'})
if opts[binding] == 'slow':
opts.update({binding: '0'})
valid = ['fast', '1', 'slow', '0']
else:
valid = ['integer']
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, valid)
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_5(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond5.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '5'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_settings_bond_6(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond6.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '6'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_bridge_opts(opts, iface):
'''
Filters given options and outputs valid settings for BRIDGING_OPTS
If an option has a value that is not expected, this
function will log the Interface, Setting and what was expected.
'''
config = {}
if 'ports' in opts:
if isinstance(opts['ports'], list):
opts['ports'] = ' '.join(opts['ports'])
config.update({'ports': opts['ports']})
for opt in ['ageing', 'fd', 'gcint', 'hello', 'maxage']:
if opt in opts:
try:
float(opts[opt])
config.update({opt: opts[opt]})
except ValueError:
_raise_error_iface(iface, opt, ['float'])
for opt in ['bridgeprio', 'maxwait']:
if opt in opts:
if isinstance(opts[opt], int):
config.update({opt: opts[opt]})
else:
_raise_error_iface(iface, opt, ['integer'])
if 'hw' in opts:
# match 12 hex digits with either : or - as separators between pairs
if re.match('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$',
opts['hw'].lower()):
config.update({'hw': opts['hw']})
else:
_raise_error_iface(iface, 'hw', ['valid MAC address'])
for opt in ['pathcost', 'portprio']:
if opt in opts:
try:
port, cost_or_prio = opts[opt].split()
int(cost_or_prio)
config.update({opt: '{0} {1}'.format(port, cost_or_prio)})
except ValueError:
_raise_error_iface(iface, opt, ['interface integer'])
if 'stp' in opts:
if opts['stp'] in _CONFIG_TRUE:
config.update({'stp': 'on'})
elif opts['stp'] in _CONFIG_FALSE:
config.update({'stp': 'off'})
else:
_raise_error_iface(iface, 'stp', _CONFIG_TRUE + _CONFIG_FALSE)
if 'waitport' in opts:
if isinstance(opts['waitport'], int):
config.update({'waitport': opts['waitport']})
else:
values = opts['waitport'].split()
waitport_time = values.pop(0)
if waitport_time.isdigit() and values:
config.update({
'waitport': '{0} {1}'.format(
waitport_time, ' '.join(values)
)
})
else:
_raise_error_iface(iface, opt, ['integer [interfaces]'])
return config
def _parse_settings_eth(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['inet'] = salt.utils.odict.OrderedDict()
iface_data['inet6'] = salt.utils.odict.OrderedDict()
if enabled:
adapters[iface]['enabled'] = True
if opts.get('hotplug', False):
adapters[iface]['hotplug'] = True
if opts.get('enable_ipv6', None) and opts.get('iface_type', '') == 'vlan':
iface_data['inet6']['vlan_raw_device'] = (
re.sub(r'\.\d*', '', iface))
for addrfam in ['inet', 'inet6']:
if iface_type not in ['bridge']:
tmp_ethtool = _parse_ethtool_opts(opts, iface)
if tmp_ethtool:
ethtool = {}
for item in tmp_ethtool:
ethtool[_ETHTOOL_CONFIG_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['ethtool'] = ethtool
# return a list of sorted keys to ensure consistent order
iface_data[addrfam]['ethtool_keys'] = sorted(ethtool)
if iface_type == 'bridge':
bridging = _parse_bridge_opts(opts, iface)
if bridging:
iface_data[addrfam]['bridging'] = bridging
iface_data[addrfam]['bridging_keys'] = sorted(bridging)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'bond':
bonding = _parse_settings_bond(opts, iface)
if bonding:
iface_data[addrfam]['bonding'] = bonding
iface_data[addrfam]['bonding']['slaves'] = opts['slaves']
iface_data[addrfam]['bonding_keys'] = sorted(bonding)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'slave':
adapters[iface]['master'] = opts['master']
opts['proto'] = 'manual'
iface_data[addrfam]['master'] = adapters[iface]['master']
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'vlan':
iface_data[addrfam]['vlan_raw_device'] = re.sub(r'\.\d*', '', iface)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'pppoe':
tmp_ethtool = _parse_ethtool_pppoe_opts(opts, iface)
if tmp_ethtool:
for item in tmp_ethtool:
adapters[iface]['data'][addrfam][_DEB_CONFIG_PPPOE_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['addrfam'] = addrfam
opts.pop('mode', None)
for opt, val in opts.items():
inet = None
if opt.startswith('ipv4'):
opt = opt[4:]
inet = 'inet'
iface_data['inet']['addrfam'] = 'inet'
elif opt.startswith('ipv6'):
iface_data['inet6']['addrfam'] = 'inet6'
opt = opt[4:]
inet = 'inet6'
elif opt in ['ipaddr', 'address', 'ipaddresses', 'addresses', 'gateway', 'proto']:
iface_data['inet']['addrfam'] = 'inet'
inet = 'inet'
_opt = SALT_ATTR_TO_DEBIAN_ATTR_MAP.get(opt, opt)
_debopt = _opt.replace('-', '_')
for addrfam in ['inet', 'inet6']:
(valid, value, errmsg) = _validate_interface_option(_opt, val, addrfam=addrfam)
if not valid:
continue
if inet is None and _debopt not in iface_data[addrfam]:
iface_data[addrfam][_debopt] = value
elif inet == addrfam:
iface_data[addrfam][_debopt] = value
for opt in ['up_cmds', 'pre_up_cmds', 'post_up_cmds',
'down_cmds', 'pre_down_cmds', 'post_down_cmds']:
if opt in opts:
iface_data['inet'][opt] = opts[opt]
iface_data['inet6'][opt] = opts[opt]
# Remove incomplete/disabled inet blocks
for (addrfam, opt) in [('inet', 'enable_ipv4'), ('inet6', 'enable_ipv6')]:
if opts.get(opt, None) is False:
iface_data.pop(addrfam)
elif iface_data[addrfam].get('addrfam', '') != addrfam:
iface_data.pop(addrfam)
return adapters
def _parse_settings_source(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['sources'] = [opts['source']]
return adapters
def _parse_network_settings(opts, current):
'''
Filters given options and outputs valid settings for
the global network settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
current = dict((k.lower(), v) for (k, v) in six.iteritems(current))
result = {}
valid = _CONFIG_TRUE + _CONFIG_FALSE
if 'enabled' not in opts:
try:
opts['networking'] = current['networking']
_log_default_network('networking', current['networking'])
except ValueError:
_raise_error_network('networking', valid)
else:
opts['networking'] = opts['enabled']
if opts['networking'] in valid:
if opts['networking'] in _CONFIG_TRUE:
result['networking'] = 'yes'
elif opts['networking'] in _CONFIG_FALSE:
result['networking'] = 'no'
else:
_raise_error_network('networking', valid)
if 'hostname' not in opts:
try:
opts['hostname'] = current['hostname']
_log_default_network('hostname', current['hostname'])
except ValueError:
_raise_error_network('hostname', ['server1.example.com'])
if opts['hostname']:
result['hostname'] = opts['hostname']
else:
_raise_error_network('hostname', ['server1.example.com'])
if 'search' in opts:
result['search'] = opts['search']
return result
def _parse_routes(iface, opts):
'''
Filters given options and outputs valid settings for
the route settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
result = {}
if 'routes' not in opts:
_raise_error_routes(iface, 'routes', 'List of routes')
for opt in opts:
result[opt] = opts[opt]
return result
def _write_file(iface, data, folder, pattern):
'''
Writes a file to disk
'''
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
return filename
def _write_file_routes(iface, data, folder, pattern):
'''
Writes a file to disk
'''
# ifup / ifdown is executing given folder via run-parts.
# according to run-parts man-page, only filenames with this pattern are
# executed: (^[a-zA-Z0-9_-]+$)
# In order to make the routes file work for vlan interfaces
# (default would have been in example /etc/network/if-up.d/route-bond0.12)
# these dots in the iface name need to be replaced by underscores, so it
# can be executed by run-parts
iface = iface.replace('.', '_')
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
__salt__['file.set_mode'](filename, '0755')
return filename
def _write_file_network(data, filename, create=False):
'''
Writes a file to disk
If file does not exist, only create if create
argument is True
'''
if not os.path.exists(filename) and not create:
msg = '{0} cannot be written. {0} does not exist\
and create is set to False'
msg = msg.format(filename)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
def _read_temp(data):
'''
Return what would be written to disk
'''
tout = StringIO()
tout.write(data)
tout.seek(0)
output = tout.readlines()
tout.close()
return output
def _read_temp_ifaces(iface, data):
'''
Return what would be written to disk for interfaces
'''
try:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': data})
# Return as an array so the difflib works
return [item + '\n' for item in ifcfg.split('\n')]
def _write_file_ifaces(iface, data, **settings):
'''
Writes a file to disk
'''
try:
eth_template = JINJA.get_template('debian_eth.jinja')
source_template = JINJA.get_template('debian_source.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
# Read /etc/network/interfaces into a dict
adapters = _parse_interfaces()
# Apply supplied settings over on-disk settings
adapters[iface] = data
ifcfg = ''
for adapter in adapters:
if 'type' in adapters[adapter] and adapters[adapter]['type'] == 'source':
tmp = source_template.render({'name': adapter, 'data': adapters[adapter]})
else:
tmp = eth_template.render({'name': adapter, 'data': adapters[adapter]})
ifcfg = ifcfg + tmp
if adapter == iface:
saved_ifcfg = tmp
_SEPARATE_FILE = False
if 'filename' in settings:
if not settings['filename'].startswith('/'):
filename = '{0}/{1}'.format(_DEB_NETWORK_DIR, settings['filename'])
else:
filename = settings['filename']
_SEPARATE_FILE = True
else:
if 'filename' in adapters[adapter]['data']:
filename = adapters[adapter]['data']
else:
filename = _DEB_NETWORK_FILE
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
if _SEPARATE_FILE:
fout.write(salt.utils.stringutils.to_str(saved_ifcfg))
else:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return saved_ifcfg.split('\n')
def _write_file_ppp_ifaces(iface, data):
'''
Writes a file to disk
'''
try:
template = JINJA.get_template('debian_ppp_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_ppp_eth.jinja')
return ''
adapters = _parse_interfaces()
adapters[iface] = data
ifcfg = ''
tmp = template.render({'data': adapters[iface]})
ifcfg = tmp + ifcfg
filename = _DEB_PPP_DIR + '/' + adapters[iface]['data']['inet']['provider']
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.fopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return filename
def build_bond(iface, **settings):
'''
Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb
'''
deb_major = __grains__['osrelease'][:1]
opts = _parse_settings_bond(settings, iface)
try:
template = JINJA.get_template('conf.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template conf.jinja')
return ''
data = template.render({'name': iface, 'bonding': opts})
if 'test' in settings and settings['test']:
return _read_temp(data)
_write_file(iface, data, _DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
if deb_major == '5':
for line_type in ('alias', 'options'):
cmd = ['sed', '-i', '-e', r'/^{0}\s{1}.*/d'.format(line_type, iface),
'/etc/modprobe.conf']
__salt__['cmd.run'](cmd, python_shell=False)
__salt__['file.append']('/etc/modprobe.conf', path)
# Load kernel module
__salt__['kmod.load']('bonding')
# install ifenslave-2.6
__salt__['pkg.install']('ifenslave-2.6')
return _read_file(path)
def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'vlan':
settings['vlan'] = 'yes'
__salt__['pkg.install']('vlan')
elif iface_type == 'pppoe':
settings['pppoe'] = 'yes'
if not __salt__['pkg.version']('ppp'):
inst = __salt__['pkg.install']('ppp')
elif iface_type == 'bond':
if 'slaves' not in settings:
msg = 'slaves is a required setting for bond interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'bridge':
if 'ports' not in settings:
msg = (
'ports is a required setting for bridge interfaces on Debian '
'or Ubuntu based systems'
)
log.error(msg)
raise AttributeError(msg)
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'pppoe']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
if iface_type in ['source']:
opts = _parse_settings_source(settings, iface_type, enabled, iface)
if 'test' in settings and settings['test']:
return _read_temp_ifaces(iface, opts[iface])
ifcfg = _write_file_ifaces(iface, opts[iface], **settings)
if iface_type == 'pppoe':
_write_file_ppp_ifaces(iface, opts[iface])
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg]
def build_routes(iface, **settings):
'''
Add route scripts for a network interface using up commands.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
'''
opts = _parse_routes(iface, settings)
try:
template = JINJA.get_template('route_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template route_eth.jinja')
return ''
add_routecfg = template.render(route_type='add',
routes=opts['routes'],
iface=iface)
del_routecfg = template.render(route_type='del',
routes=opts['routes'],
iface=iface)
if 'test' in settings and settings['test']:
return _read_temp(add_routecfg + del_routecfg)
filename = _write_file_routes(iface,
add_routecfg,
_DEB_NETWORK_UP_DIR,
'route-{0}')
results = _read_file(filename)
filename = _write_file_routes(iface,
del_routecfg,
_DEB_NETWORK_DOWN_DIR,
'route-{0}')
results += _read_file(filename)
return results
def down(iface, iface_type):
'''
Shutdown a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.down eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought down.
if iface_type not in ['slave', 'source']:
return __salt__['cmd.run'](['ifdown', iface])
return None
def get_bond(iface):
'''
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
'''
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
return _read_file(path)
def get_interface(iface):
'''
Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
adapters = _parse_interfaces()
if iface in adapters:
try:
if iface == 'source':
template = JINJA.get_template('debian_source.jinja')
else:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': adapters[iface]})
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg.split('\n')]
else:
return []
def up(iface, iface_type): # pylint: disable=C0103
'''
Start up a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.up eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought up.
if iface_type not in ('slave', 'source'):
return __salt__['cmd.run'](['ifup', iface])
return None
def get_network_settings():
'''
Return the contents of the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_network_settings
'''
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
settings = {}
if __salt__['service.available']('networking'):
if __salt__['service.status']('networking'):
settings['networking'] = "yes"
else:
settings['networking'] = "no"
else:
settings['networking'] = "no"
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
settings['hostname'] = hostname
settings['domainname'] = domainname
settings['searchdomain'] = searchdomain
else:
settings = _parse_current_network_settings()
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(settings)
return _read_temp(network)
def get_routes(iface):
'''
Return the routes for the interface
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0
'''
filename = os.path.join(_DEB_NETWORK_UP_DIR, 'route-{0}'.format(iface))
results = _read_file(filename)
filename = os.path.join(_DEB_NETWORK_DOWN_DIR, 'route-{0}'.format(iface))
results += _read_file(filename)
return results
def apply_network_settings(**settings):
'''
Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings
'''
if 'require_reboot' not in settings:
settings['require_reboot'] = False
if 'apply_hostname' not in settings:
settings['apply_hostname'] = False
hostname_res = True
if settings['apply_hostname'] in _CONFIG_TRUE:
if 'hostname' in settings:
hostname_res = __salt__['network.mod_hostname'](settings['hostname'])
else:
log.warning(
'The network state sls is trying to apply hostname '
'changes but no hostname is defined.'
)
hostname_res = False
res = True
if settings['require_reboot'] in _CONFIG_TRUE:
log.warning(
'The network state sls is requiring a reboot of the system to '
'properly apply network configuration.'
)
res = True
else:
stop = __salt__['service.stop']('networking')
time.sleep(2)
res = stop and __salt__['service.start']('networking')
return hostname_res and res
def build_network_settings(**settings):
'''
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
'''
changes = []
# Read current configuration and store default values
current_network_settings = _parse_current_network_settings()
# Build settings
opts = _parse_network_settings(settings, current_network_settings)
# Ubuntu has moved away from /etc/default/networking
# beginning with the 12.04 release so we disable or enable
# the networking related services on boot
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
if opts['networking'] == 'yes':
service_cmd = 'service.enable'
else:
service_cmd = 'service.disable'
if __salt__['service.available']('NetworkManager'):
__salt__[service_cmd]('NetworkManager')
if __salt__['service.available']('networking'):
__salt__[service_cmd]('networking')
else:
try:
template = JINJA.get_template('network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template network.jinja')
return ''
network = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(network)
# Write settings
_write_file_network(network, _DEB_NETWORKING_FILE, True)
# Get hostname and domain from opts
sline = opts['hostname'].split('.', 1)
opts['hostname'] = sline[0]
current_domainname = current_network_settings['domainname']
current_searchdomain = current_network_settings['searchdomain']
new_domain = False
if len(sline) > 1:
new_domainname = sline[1]
if new_domainname != current_domainname:
domainname = new_domainname
opts['domainname'] = new_domainname
new_domain = True
else:
domainname = current_domainname
opts['domainname'] = domainname
else:
domainname = current_domainname
opts['domainname'] = domainname
new_search = False
if 'search' in opts:
new_searchdomain = opts['search']
if new_searchdomain != current_searchdomain:
searchdomain = new_searchdomain
opts['searchdomain'] = new_searchdomain
new_search = True
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
# If the domain changes, then we should write the resolv.conf file.
if new_domain or new_search:
# Look for existing domain line and update if necessary
resolve = _parse_resolve()
domain_prog = re.compile(r'domain\s+')
search_prog = re.compile(r'search\s+')
new_contents = []
for item in _read_file(_DEB_RESOLV_FILE):
if domain_prog.match(item):
item = 'domain {0}'.format(domainname)
elif search_prog.match(item):
item = 'search {0}'.format(searchdomain)
new_contents.append(item)
# A domain line didn't exist so we'll add one in
# with the new domainname
if 'domain' not in resolve:
new_contents.insert(0, 'domain {0}' . format(domainname))
# A search line didn't exist so we'll add one in
# with the new search domain
if 'search' not in resolve:
new_contents.insert('domain' in resolve, 'search {0}'.format(searchdomain))
new_resolv = '\n'.join(new_contents)
# Write /etc/resolv.conf
if not ('test' in settings and settings['test']):
_write_file_network(new_resolv, _DEB_RESOLV_FILE)
# used for returning the results back
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(opts)
changes.extend(_read_temp(network))
return changes
|
saltstack/salt
|
salt/modules/debian_ip.py
|
_parse_settings_bond_2
|
python
|
def _parse_settings_bond_2(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond2.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '2'}
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
|
Filters given options and outputs valid settings for bond2.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_ip.py#L918-L962
| null |
# -*- coding: utf-8 -*-
'''
The networking module for Debian-based distros
References:
* http://www.debian.org/doc/manuals/debian-reference/ch05.en.html
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import functools
import logging
import os.path
import os
import re
import time
# Import third party libs
import jinja2
import jinja2.exceptions
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error,no-name-in-module
# Import salt libs
import salt.utils.dns
import salt.utils.files
import salt.utils.odict
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.validate.net
# Set up logging
log = logging.getLogger(__name__)
# Set up template environment
JINJA = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'debian_ip')
)
)
# Define the module's virtual name
__virtualname__ = 'ip'
def __virtual__():
'''
Confine this module to Debian-based distros
'''
if __grains__['os_family'] == 'Debian':
return __virtualname__
return (False, 'The debian_ip module could not be loaded: '
'unsupported OS family')
_ETHTOOL_CONFIG_OPTS = {
'speed': 'link-speed',
'duplex': 'link-duplex',
'autoneg': 'ethernet-autoneg',
'ethernet-port': 'ethernet-port',
'wol': 'ethernet-wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'rx': 'offload-rx',
'tx': 'offload-tx',
'sg': 'offload-sg',
'tso': 'offload-tso',
'ufo': 'offload-ufo',
'gso': 'offload-gso',
'gro': 'offload-gro',
'lro': 'offload-lro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_REV_ETHTOOL_CONFIG_OPTS = {
'link-speed': 'speed',
'link-duplex': 'duplex',
'ethernet-autoneg': 'autoneg',
'ethernet-port': 'ethernet-port',
'ethernet-wol': 'wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'offload-rx': 'rx',
'offload-tx': 'tx',
'offload-sg': 'sg',
'offload-tso': 'tso',
'offload-ufo': 'ufo',
'offload-gso': 'gso',
'offload-lro': 'lro',
'offload-gro': 'gro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_DEB_CONFIG_PPPOE_OPTS = {
'user': 'user',
'password': 'password',
'provider': 'provider',
'pppoe_iface': 'pppoe_iface',
'noipdefault': 'noipdefault',
'usepeerdns': 'usepeerdns',
'defaultroute': 'defaultroute',
'holdoff': 'holdoff',
'maxfail': 'maxfail',
'hide-password': 'hide-password',
'lcp-echo-interval': 'lcp-echo-interval',
'lcp-echo-failure': 'lcp-echo-failure',
'connect': 'connect',
'noauth': 'noauth',
'persist': 'persist',
'mtu': 'mtu',
'noaccomp': 'noaccomp',
'linkname': 'linkname',
}
_DEB_ROUTES_FILE = '/etc/network/routes'
_DEB_NETWORK_FILE = '/etc/network/interfaces'
_DEB_NETWORK_DIR = '/etc/network/interfaces.d/'
_DEB_NETWORK_UP_DIR = '/etc/network/if-up.d/'
_DEB_NETWORK_DOWN_DIR = '/etc/network/if-down.d/'
_DEB_NETWORK_CONF_FILES = '/etc/modprobe.d/'
_DEB_NETWORKING_FILE = '/etc/default/networking'
_DEB_HOSTNAME_FILE = '/etc/hostname'
_DEB_RESOLV_FILE = '/etc/resolv.conf'
_DEB_PPP_DIR = '/etc/ppp/peers/'
_CONFIG_TRUE = ['yes', 'on', 'true', '1', True]
_CONFIG_FALSE = ['no', 'off', 'false', '0', False]
_IFACE_TYPES = [
'eth', 'bond', 'alias', 'clone',
'ipsec', 'dialup', 'bridge', 'slave',
'vlan', 'pppoe', 'source',
]
def _error_msg_iface(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, '|'.join(str(e) for e in expected))
def _error_msg_routes(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, expected)
def _log_default_iface(iface, opt, value):
log.info(
'Using default option -- Interface: %s Option: %s Value: %s',
iface, opt, value
)
def _error_msg_network(option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]'
return msg.format(option, '|'.join(str(e) for e in expected))
def _log_default_network(opt, value):
log.info('Using existing setting -- Setting: %s Value: %s', opt, value)
def _raise_error_iface(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_iface(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_network(option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_network(option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_routes(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_routes(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _read_file(path):
'''
Reads and returns the contents of a text file
'''
try:
with salt.utils.files.flopen(path, 'rb') as contents:
return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]
except (OSError, IOError):
return ''
def _parse_resolve():
'''
Parse /etc/resolv.conf
'''
return salt.utils.dns.parse_resolv(_DEB_RESOLV_FILE)
def _parse_domainname():
'''
Parse /etc/resolv.conf and return domainname
'''
return _parse_resolve().get('domain', '')
def _parse_searchdomain():
'''
Parse /etc/resolv.conf and return searchdomain
'''
return _parse_resolve().get('search', '')
def _parse_hostname():
'''
Parse /etc/hostname and return hostname
'''
contents = _read_file(_DEB_HOSTNAME_FILE)
if contents:
return contents[0].split('\n')[0]
else:
return ''
def _parse_current_network_settings():
'''
Parse /etc/default/networking and return current configuration
'''
opts = salt.utils.odict.OrderedDict()
opts['networking'] = ''
if os.path.isfile(_DEB_NETWORKING_FILE):
with salt.utils.files.fopen(_DEB_NETWORKING_FILE) as contents:
for line in contents:
salt.utils.stringutils.to_unicode(line)
if line.startswith('#'):
continue
elif line.startswith('CONFIGURE_INTERFACES'):
opts['networking'] = line.split('=', 1)[1].strip()
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
opts['hostname'] = hostname
opts['domainname'] = domainname
opts['searchdomain'] = searchdomain
return opts
# def __validator_func(value):
# return (valid: True/False, (transformed) value, error message)
def __ipv4_quad(value):
'''validate an IPv4 address'''
return (salt.utils.validate.net.ipv4_addr(value), value,
'dotted IPv4 address')
def __ipv6(value):
'''validate an IPv6 address'''
return (salt.utils.validate.net.ipv6_addr(value), value,
'IPv6 address')
def __mac(value):
'''validate a mac address'''
return (salt.utils.validate.net.mac(value), value,
'MAC address')
def __anything(value):
return (True, value, None)
def __int(value):
'''validate an integer'''
valid, _value = False, value
try:
_value = int(value)
valid = True
except ValueError:
pass
return (valid, _value, 'integer')
def __float(value):
'''validate a float'''
valid, _value = False, value
try:
_value = float(value)
valid = True
except ValueError:
pass
return (valid, _value, 'float')
def __ipv4_netmask(value):
'''validate an IPv4 dotted quad or integer CIDR netmask'''
valid, errmsg = False, 'dotted quad or integer CIDR (0->32)'
valid, value, _ = __int(value)
if not (valid and 0 <= value <= 32):
valid = salt.utils.validate.net.netmask(value)
return (valid, value, errmsg)
def __ipv6_netmask(value):
'''validate an IPv6 integer netmask'''
valid, errmsg = False, 'IPv6 netmask (0->128)'
valid, value, _ = __int(value)
valid = (valid and 0 <= value <= 128)
return (valid, value, errmsg)
def __within2(value, within=None, errmsg=None, dtype=None):
'''validate that a value is in ``within`` and optionally a ``dtype``'''
valid, _value = False, value
if dtype:
try:
_value = dtype(value) # TODO: this is a bit loose when dtype is a class
valid = _value in within
except ValueError:
pass
else:
valid = _value in within
if errmsg is None:
if dtype:
typename = getattr(dtype, '__name__',
hasattr(dtype, '__class__')
and getattr(dtype.__class__, 'name', dtype))
errmsg = '{0} within \'{1}\''.format(typename, within)
else:
errmsg = 'within \'{0}\''.format(within)
return (valid, _value, errmsg)
def __within(within=None, errmsg=None, dtype=None):
return functools.partial(__within2, within=within,
errmsg=errmsg, dtype=dtype)
def __space_delimited_list(value):
'''validate that a value contains one or more space-delimited values'''
if isinstance(value, six.string_types):
value = value.strip().split()
if hasattr(value, '__iter__') and value != []:
return (True, value, 'space-delimited string')
else:
return (False, value, '{0} is not a valid space-delimited value.\n'.format(value))
SALT_ATTR_TO_DEBIAN_ATTR_MAP = {
'dns': 'dns-nameservers',
'search': 'dns-search',
'hwaddr': 'hwaddress', # TODO: this limits bootp functionality
'ipaddr': 'address',
'ipaddrs': 'addresses',
}
DEBIAN_ATTR_TO_SALT_ATTR_MAP = dict(
(v, k) for (k, v) in six.iteritems(SALT_ATTR_TO_DEBIAN_ATTR_MAP))
# TODO
DEBIAN_ATTR_TO_SALT_ATTR_MAP['address'] = 'address'
DEBIAN_ATTR_TO_SALT_ATTR_MAP['hwaddress'] = 'hwaddress'
IPV4_VALID_PROTO = ['bootp', 'dhcp', 'static', 'manual', 'loopback', 'ppp']
IPV4_ATTR_MAP = {
'proto': __within(IPV4_VALID_PROTO, dtype=six.text_type),
# ipv4 static & manual
'address': __ipv4_quad,
'addresses': __anything,
'netmask': __ipv4_netmask,
'broadcast': __ipv4_quad,
'metric': __int,
'gateway': __ipv4_quad, # supports a colon-delimited list
'pointopoint': __ipv4_quad,
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'link', 'host'], dtype=six.text_type),
# dhcp
'hostname': __anything,
'leasehours': __int,
'leasetime': __int,
'vendor': __anything,
'client': __anything,
# bootp
'bootfile': __anything,
'server': __ipv4_quad,
'hwaddr': __mac,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'dstaddr': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# bond
'slaves': __anything,
# ppp
'provider': __anything,
'unit': __int,
'options': __anything,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
#
'network': __anything, # i don't know what this is
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
IPV6_VALID_PROTO = ['auto', 'loopback', 'static', 'manual',
'dhcp', 'v4tunnel', '6to4']
IPV6_ATTR_MAP = {
'proto': __within(IPV6_VALID_PROTO),
# ipv6 static & manual
'address': __ipv6,
'addresses': __anything,
'netmask': __ipv6_netmask,
'broadcast': __ipv6,
'gateway': __ipv6, # supports a colon-delimited list
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'site', 'link', 'host'], dtype=six.text_type),
# inet6 auto
'privext': __within([0, 1, 2], dtype=int),
'dhcp': __within([0, 1], dtype=int),
# inet6 static & manual & dhcp
'media': __anything,
'accept_ra': __within([0, 1], dtype=int),
'autoconf': __within([0, 1], dtype=int),
'preferred-lifetime': __int,
'dad-attempts': __int, # 0 to disable
'dad-interval': __float,
# bond
'slaves': __anything,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
WIRELESS_ATTR_MAP = {
'wireless-essid': __anything,
'wireless-mode': __anything, # TODO
'wpa-ap-scan': __within([0, 1, 2], dtype=int), # TODO
'wpa-conf': __anything,
'wpa-driver': __anything,
'wpa-group': __anything,
'wpa-key-mgmt': __anything,
'wpa-pairwise': __anything,
'wpa-psk': __anything,
'wpa-proto': __anything, # partial(__within,
'wpa-roam': __anything,
'wpa-ssid': __anything, # TODO
}
ATTRMAPS = {
'inet': [IPV4_ATTR_MAP, WIRELESS_ATTR_MAP],
'inet6': [IPV6_ATTR_MAP, WIRELESS_ATTR_MAP]
}
def _validate_interface_option(attr, value, addrfam='inet'):
'''lookup the validation function for a [addrfam][attr] and
return the results
:param attr: attribute name
:param value: raw setting value
:param addrfam: address family (inet, inet6,
'''
valid, _value, errmsg = False, value, 'Unknown validator'
attrmaps = ATTRMAPS.get(addrfam, [])
for attrmap in attrmaps:
if attr in attrmap:
validate_func = attrmap[attr]
(valid, _value, errmsg) = validate_func(value)
break
return (valid, _value, errmsg)
def _attrmaps_contain_attr(attr):
return (
attr in WIRELESS_ATTR_MAP or
attr in IPV4_ATTR_MAP or
attr in IPV6_ATTR_MAP)
def _parse_interfaces(interface_files=None):
'''
Parse /etc/network/interfaces and return current configured interfaces
'''
if interface_files is None:
interface_files = []
# Add this later.
if os.path.exists(_DEB_NETWORK_DIR):
interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]
if os.path.isfile(_DEB_NETWORK_FILE):
interface_files.insert(0, _DEB_NETWORK_FILE)
adapters = salt.utils.odict.OrderedDict()
method = -1
for interface_file in interface_files:
with salt.utils.files.fopen(interface_file) as interfaces:
# This ensures iface_dict exists, but does not ensure we're not reading a new interface.
iface_dict = {}
for line in interfaces:
line = salt.utils.stringutils.to_unicode(line)
# Identify the clauses by the first word of each line.
# Go to the next line if the current line is a comment
# or all spaces.
if line.lstrip().startswith('#') or line.isspace():
continue
# Parse the iface clause
if line.startswith('iface'):
sline = line.split()
if len(sline) != 4:
msg = 'Interface file malformed: {0}.'
msg = msg.format(sline)
log.error(msg)
raise AttributeError(msg)
iface_name = sline[1]
addrfam = sline[2]
method = sline[3]
# Create item in dict, if not already there
if iface_name not in adapters:
adapters[iface_name] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters[iface_name]:
adapters[iface_name]['data'] = salt.utils.odict.OrderedDict()
if addrfam not in adapters[iface_name]['data']:
adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict()
iface_dict = adapters[iface_name]['data'][addrfam]
iface_dict['addrfam'] = addrfam
iface_dict['proto'] = method
iface_dict['filename'] = interface_file
# Parse the detail clauses.
elif line[0].isspace():
sline = line.split()
# conf file attr: dns-nameservers
# salt states.network attr: dns
attr, valuestr = line.rstrip().split(None, 1)
if _attrmaps_contain_attr(attr):
if '-' in attr:
attrname = attr.replace('-', '_')
else:
attrname = attr
(valid, value, errmsg) = _validate_interface_option(
attr, valuestr, addrfam)
if attrname == 'address' and 'address' in iface_dict:
if 'addresses' not in iface_dict:
iface_dict['addresses'] = []
iface_dict['addresses'].append(value)
else:
iface_dict[attrname] = value
elif attr in _REV_ETHTOOL_CONFIG_OPTS:
if 'ethtool' not in iface_dict:
iface_dict['ethtool'] = salt.utils.odict.OrderedDict()
iface_dict['ethtool'][attr] = valuestr
elif attr.startswith('bond'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bonding' not in iface_dict:
iface_dict['bonding'] = salt.utils.odict.OrderedDict()
iface_dict['bonding'][opt] = valuestr
elif attr.startswith('bridge'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bridging' not in iface_dict:
iface_dict['bridging'] = salt.utils.odict.OrderedDict()
iface_dict['bridging'][opt] = valuestr
elif attr in ['up', 'pre-up', 'post-up',
'down', 'pre-down', 'post-down']:
cmd = valuestr
cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr))
if cmd_key not in iface_dict:
iface_dict[cmd_key] = []
iface_dict[cmd_key].append(cmd)
elif line.startswith('auto'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['enabled'] = True
elif line.startswith('allow-hotplug'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['hotplug'] = True
elif line.startswith('source'):
if 'source' not in adapters:
adapters['source'] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters['source']:
adapters['source']['data'] = salt.utils.odict.OrderedDict()
adapters['source']['data']['sources'] = []
adapters['source']['data']['sources'].append(line.split()[1])
# Return a sorted list of the keys for bond, bridge and ethtool options to
# ensure a consistent order
for iface_name in adapters:
if iface_name == 'source':
continue
if 'data' not in adapters[iface_name]:
msg = 'Interface file malformed for interface: {0}.'.format(iface_name)
log.error(msg)
adapters.pop(iface_name)
continue
for opt in ['ethtool', 'bonding', 'bridging']:
for inet in ['inet', 'inet6']:
if inet in adapters[iface_name]['data']:
if opt in adapters[iface_name]['data'][inet]:
opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys())
adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys
return adapters
def _parse_ethtool_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
if 'autoneg' in opts:
if opts['autoneg'] in _CONFIG_TRUE:
config.update({'autoneg': 'on'})
elif opts['autoneg'] in _CONFIG_FALSE:
config.update({'autoneg': 'off'})
else:
_raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE)
if 'duplex' in opts:
valid = ['full', 'half']
if opts['duplex'] in valid:
config.update({'duplex': opts['duplex']})
else:
_raise_error_iface(iface, 'duplex', valid)
if 'speed' in opts:
valid = ['10', '100', '1000', '10000']
if six.text_type(opts['speed']) in valid:
config.update({'speed': opts['speed']})
else:
_raise_error_iface(iface, opts['speed'], valid)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'on'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'off'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_ethtool_pppoe_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
for opt in _DEB_CONFIG_PPPOE_OPTS:
if opt in opts:
config[opt] = opts[opt]
if 'provider' in opts and not opts['provider']:
_raise_error_iface(iface, 'provider', _CONFIG_TRUE + _CONFIG_FALSE)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('noipdefault', 'usepeerdns', 'defaultroute', 'hide-password', 'noauth', 'persist', 'noaccomp'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'True'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'False'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_settings_bond(opts, iface):
'''
Filters given options and outputs valid settings for requested
operation. If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond_def = {
# 803.ad aggregation selection logic
# 0 for stable (default)
# 1 for bandwidth
# 2 for count
'ad_select': '0',
# Max number of transmit queues (default = 16)
'tx_queues': '16',
# Link monitoring in milliseconds. Most NICs support this
'miimon': '100',
# ARP interval in milliseconds
'arp_interval': '250',
# Delay before considering link down in milliseconds (miimon * 2)
'downdelay': '200',
# lacp_rate 0: Slow - every 30 seconds
# lacp_rate 1: Fast - every 1 second
'lacp_rate': '0',
# Max bonds for this driver
'max_bonds': '1',
# Specifies the time, in milliseconds, to wait before
# enabling a slave after a link recovery has been
# detected. Only used with miimon.
'updelay': '0',
# Used with miimon.
# On: driver sends mii
# Off: ethtool sends mii
'use_carrier': 'on',
# Default. Don't change unless you know what you are doing.
'xmit_hash_policy': 'layer2',
}
if opts['mode'] in ['balance-rr', '0']:
log.info('Device: %s Bonding Mode: load balancing (round-robin)', iface)
return _parse_settings_bond_0(opts, iface, bond_def)
elif opts['mode'] in ['active-backup', '1']:
log.info('Device: %s Bonding Mode: fault-tolerance (active-backup)', iface)
return _parse_settings_bond_1(opts, iface, bond_def)
elif opts['mode'] in ['balance-xor', '2']:
log.info('Device: %s Bonding Mode: load balancing (xor)', iface)
return _parse_settings_bond_2(opts, iface, bond_def)
elif opts['mode'] in ['broadcast', '3']:
log.info('Device: %s Bonding Mode: fault-tolerance (broadcast)', iface)
return _parse_settings_bond_3(opts, iface, bond_def)
elif opts['mode'] in ['802.3ad', '4']:
log.info('Device: %s Bonding Mode: IEEE 802.3ad Dynamic link '
'aggregation', iface)
return _parse_settings_bond_4(opts, iface, bond_def)
elif opts['mode'] in ['balance-tlb', '5']:
log.info('Device: %s Bonding Mode: transmit load balancing', iface)
return _parse_settings_bond_5(opts, iface, bond_def)
elif opts['mode'] in ['balance-alb', '6']:
log.info('Device: %s Bonding Mode: adaptive load balancing', iface)
return _parse_settings_bond_6(opts, iface, bond_def)
else:
valid = [
'0', '1', '2', '3', '4', '5', '6',
'balance-rr', 'active-backup', 'balance-xor',
'broadcast', '802.3ad', 'balance-tlb', 'balance-alb'
]
_raise_error_iface(iface, 'mode', valid)
def _parse_settings_bond_0(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond0.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '0'}
# ARP targets in n.n.n.n form
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
return bond
def _parse_settings_bond_1(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '1'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
if not (__grains__['os'] == "Ubuntu" and __grains__['osrelease_info'][0] >= 16):
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_3(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond3.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '3'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_4(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond4.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '4'}
for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']:
if binding in opts:
if binding == 'lacp_rate':
if opts[binding] == 'fast':
opts.update({binding: '1'})
if opts[binding] == 'slow':
opts.update({binding: '0'})
valid = ['fast', '1', 'slow', '0']
else:
valid = ['integer']
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, valid)
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_5(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond5.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '5'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_settings_bond_6(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond6.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '6'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_bridge_opts(opts, iface):
'''
Filters given options and outputs valid settings for BRIDGING_OPTS
If an option has a value that is not expected, this
function will log the Interface, Setting and what was expected.
'''
config = {}
if 'ports' in opts:
if isinstance(opts['ports'], list):
opts['ports'] = ' '.join(opts['ports'])
config.update({'ports': opts['ports']})
for opt in ['ageing', 'fd', 'gcint', 'hello', 'maxage']:
if opt in opts:
try:
float(opts[opt])
config.update({opt: opts[opt]})
except ValueError:
_raise_error_iface(iface, opt, ['float'])
for opt in ['bridgeprio', 'maxwait']:
if opt in opts:
if isinstance(opts[opt], int):
config.update({opt: opts[opt]})
else:
_raise_error_iface(iface, opt, ['integer'])
if 'hw' in opts:
# match 12 hex digits with either : or - as separators between pairs
if re.match('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$',
opts['hw'].lower()):
config.update({'hw': opts['hw']})
else:
_raise_error_iface(iface, 'hw', ['valid MAC address'])
for opt in ['pathcost', 'portprio']:
if opt in opts:
try:
port, cost_or_prio = opts[opt].split()
int(cost_or_prio)
config.update({opt: '{0} {1}'.format(port, cost_or_prio)})
except ValueError:
_raise_error_iface(iface, opt, ['interface integer'])
if 'stp' in opts:
if opts['stp'] in _CONFIG_TRUE:
config.update({'stp': 'on'})
elif opts['stp'] in _CONFIG_FALSE:
config.update({'stp': 'off'})
else:
_raise_error_iface(iface, 'stp', _CONFIG_TRUE + _CONFIG_FALSE)
if 'waitport' in opts:
if isinstance(opts['waitport'], int):
config.update({'waitport': opts['waitport']})
else:
values = opts['waitport'].split()
waitport_time = values.pop(0)
if waitport_time.isdigit() and values:
config.update({
'waitport': '{0} {1}'.format(
waitport_time, ' '.join(values)
)
})
else:
_raise_error_iface(iface, opt, ['integer [interfaces]'])
return config
def _parse_settings_eth(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['inet'] = salt.utils.odict.OrderedDict()
iface_data['inet6'] = salt.utils.odict.OrderedDict()
if enabled:
adapters[iface]['enabled'] = True
if opts.get('hotplug', False):
adapters[iface]['hotplug'] = True
if opts.get('enable_ipv6', None) and opts.get('iface_type', '') == 'vlan':
iface_data['inet6']['vlan_raw_device'] = (
re.sub(r'\.\d*', '', iface))
for addrfam in ['inet', 'inet6']:
if iface_type not in ['bridge']:
tmp_ethtool = _parse_ethtool_opts(opts, iface)
if tmp_ethtool:
ethtool = {}
for item in tmp_ethtool:
ethtool[_ETHTOOL_CONFIG_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['ethtool'] = ethtool
# return a list of sorted keys to ensure consistent order
iface_data[addrfam]['ethtool_keys'] = sorted(ethtool)
if iface_type == 'bridge':
bridging = _parse_bridge_opts(opts, iface)
if bridging:
iface_data[addrfam]['bridging'] = bridging
iface_data[addrfam]['bridging_keys'] = sorted(bridging)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'bond':
bonding = _parse_settings_bond(opts, iface)
if bonding:
iface_data[addrfam]['bonding'] = bonding
iface_data[addrfam]['bonding']['slaves'] = opts['slaves']
iface_data[addrfam]['bonding_keys'] = sorted(bonding)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'slave':
adapters[iface]['master'] = opts['master']
opts['proto'] = 'manual'
iface_data[addrfam]['master'] = adapters[iface]['master']
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'vlan':
iface_data[addrfam]['vlan_raw_device'] = re.sub(r'\.\d*', '', iface)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'pppoe':
tmp_ethtool = _parse_ethtool_pppoe_opts(opts, iface)
if tmp_ethtool:
for item in tmp_ethtool:
adapters[iface]['data'][addrfam][_DEB_CONFIG_PPPOE_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['addrfam'] = addrfam
opts.pop('mode', None)
for opt, val in opts.items():
inet = None
if opt.startswith('ipv4'):
opt = opt[4:]
inet = 'inet'
iface_data['inet']['addrfam'] = 'inet'
elif opt.startswith('ipv6'):
iface_data['inet6']['addrfam'] = 'inet6'
opt = opt[4:]
inet = 'inet6'
elif opt in ['ipaddr', 'address', 'ipaddresses', 'addresses', 'gateway', 'proto']:
iface_data['inet']['addrfam'] = 'inet'
inet = 'inet'
_opt = SALT_ATTR_TO_DEBIAN_ATTR_MAP.get(opt, opt)
_debopt = _opt.replace('-', '_')
for addrfam in ['inet', 'inet6']:
(valid, value, errmsg) = _validate_interface_option(_opt, val, addrfam=addrfam)
if not valid:
continue
if inet is None and _debopt not in iface_data[addrfam]:
iface_data[addrfam][_debopt] = value
elif inet == addrfam:
iface_data[addrfam][_debopt] = value
for opt in ['up_cmds', 'pre_up_cmds', 'post_up_cmds',
'down_cmds', 'pre_down_cmds', 'post_down_cmds']:
if opt in opts:
iface_data['inet'][opt] = opts[opt]
iface_data['inet6'][opt] = opts[opt]
# Remove incomplete/disabled inet blocks
for (addrfam, opt) in [('inet', 'enable_ipv4'), ('inet6', 'enable_ipv6')]:
if opts.get(opt, None) is False:
iface_data.pop(addrfam)
elif iface_data[addrfam].get('addrfam', '') != addrfam:
iface_data.pop(addrfam)
return adapters
def _parse_settings_source(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['sources'] = [opts['source']]
return adapters
def _parse_network_settings(opts, current):
'''
Filters given options and outputs valid settings for
the global network settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
current = dict((k.lower(), v) for (k, v) in six.iteritems(current))
result = {}
valid = _CONFIG_TRUE + _CONFIG_FALSE
if 'enabled' not in opts:
try:
opts['networking'] = current['networking']
_log_default_network('networking', current['networking'])
except ValueError:
_raise_error_network('networking', valid)
else:
opts['networking'] = opts['enabled']
if opts['networking'] in valid:
if opts['networking'] in _CONFIG_TRUE:
result['networking'] = 'yes'
elif opts['networking'] in _CONFIG_FALSE:
result['networking'] = 'no'
else:
_raise_error_network('networking', valid)
if 'hostname' not in opts:
try:
opts['hostname'] = current['hostname']
_log_default_network('hostname', current['hostname'])
except ValueError:
_raise_error_network('hostname', ['server1.example.com'])
if opts['hostname']:
result['hostname'] = opts['hostname']
else:
_raise_error_network('hostname', ['server1.example.com'])
if 'search' in opts:
result['search'] = opts['search']
return result
def _parse_routes(iface, opts):
'''
Filters given options and outputs valid settings for
the route settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
result = {}
if 'routes' not in opts:
_raise_error_routes(iface, 'routes', 'List of routes')
for opt in opts:
result[opt] = opts[opt]
return result
def _write_file(iface, data, folder, pattern):
'''
Writes a file to disk
'''
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
return filename
def _write_file_routes(iface, data, folder, pattern):
'''
Writes a file to disk
'''
# ifup / ifdown is executing given folder via run-parts.
# according to run-parts man-page, only filenames with this pattern are
# executed: (^[a-zA-Z0-9_-]+$)
# In order to make the routes file work for vlan interfaces
# (default would have been in example /etc/network/if-up.d/route-bond0.12)
# these dots in the iface name need to be replaced by underscores, so it
# can be executed by run-parts
iface = iface.replace('.', '_')
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
__salt__['file.set_mode'](filename, '0755')
return filename
def _write_file_network(data, filename, create=False):
'''
Writes a file to disk
If file does not exist, only create if create
argument is True
'''
if not os.path.exists(filename) and not create:
msg = '{0} cannot be written. {0} does not exist\
and create is set to False'
msg = msg.format(filename)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
def _read_temp(data):
'''
Return what would be written to disk
'''
tout = StringIO()
tout.write(data)
tout.seek(0)
output = tout.readlines()
tout.close()
return output
def _read_temp_ifaces(iface, data):
'''
Return what would be written to disk for interfaces
'''
try:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': data})
# Return as an array so the difflib works
return [item + '\n' for item in ifcfg.split('\n')]
def _write_file_ifaces(iface, data, **settings):
'''
Writes a file to disk
'''
try:
eth_template = JINJA.get_template('debian_eth.jinja')
source_template = JINJA.get_template('debian_source.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
# Read /etc/network/interfaces into a dict
adapters = _parse_interfaces()
# Apply supplied settings over on-disk settings
adapters[iface] = data
ifcfg = ''
for adapter in adapters:
if 'type' in adapters[adapter] and adapters[adapter]['type'] == 'source':
tmp = source_template.render({'name': adapter, 'data': adapters[adapter]})
else:
tmp = eth_template.render({'name': adapter, 'data': adapters[adapter]})
ifcfg = ifcfg + tmp
if adapter == iface:
saved_ifcfg = tmp
_SEPARATE_FILE = False
if 'filename' in settings:
if not settings['filename'].startswith('/'):
filename = '{0}/{1}'.format(_DEB_NETWORK_DIR, settings['filename'])
else:
filename = settings['filename']
_SEPARATE_FILE = True
else:
if 'filename' in adapters[adapter]['data']:
filename = adapters[adapter]['data']
else:
filename = _DEB_NETWORK_FILE
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
if _SEPARATE_FILE:
fout.write(salt.utils.stringutils.to_str(saved_ifcfg))
else:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return saved_ifcfg.split('\n')
def _write_file_ppp_ifaces(iface, data):
'''
Writes a file to disk
'''
try:
template = JINJA.get_template('debian_ppp_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_ppp_eth.jinja')
return ''
adapters = _parse_interfaces()
adapters[iface] = data
ifcfg = ''
tmp = template.render({'data': adapters[iface]})
ifcfg = tmp + ifcfg
filename = _DEB_PPP_DIR + '/' + adapters[iface]['data']['inet']['provider']
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.fopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return filename
def build_bond(iface, **settings):
'''
Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb
'''
deb_major = __grains__['osrelease'][:1]
opts = _parse_settings_bond(settings, iface)
try:
template = JINJA.get_template('conf.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template conf.jinja')
return ''
data = template.render({'name': iface, 'bonding': opts})
if 'test' in settings and settings['test']:
return _read_temp(data)
_write_file(iface, data, _DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
if deb_major == '5':
for line_type in ('alias', 'options'):
cmd = ['sed', '-i', '-e', r'/^{0}\s{1}.*/d'.format(line_type, iface),
'/etc/modprobe.conf']
__salt__['cmd.run'](cmd, python_shell=False)
__salt__['file.append']('/etc/modprobe.conf', path)
# Load kernel module
__salt__['kmod.load']('bonding')
# install ifenslave-2.6
__salt__['pkg.install']('ifenslave-2.6')
return _read_file(path)
def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'vlan':
settings['vlan'] = 'yes'
__salt__['pkg.install']('vlan')
elif iface_type == 'pppoe':
settings['pppoe'] = 'yes'
if not __salt__['pkg.version']('ppp'):
inst = __salt__['pkg.install']('ppp')
elif iface_type == 'bond':
if 'slaves' not in settings:
msg = 'slaves is a required setting for bond interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'bridge':
if 'ports' not in settings:
msg = (
'ports is a required setting for bridge interfaces on Debian '
'or Ubuntu based systems'
)
log.error(msg)
raise AttributeError(msg)
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'pppoe']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
if iface_type in ['source']:
opts = _parse_settings_source(settings, iface_type, enabled, iface)
if 'test' in settings and settings['test']:
return _read_temp_ifaces(iface, opts[iface])
ifcfg = _write_file_ifaces(iface, opts[iface], **settings)
if iface_type == 'pppoe':
_write_file_ppp_ifaces(iface, opts[iface])
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg]
def build_routes(iface, **settings):
'''
Add route scripts for a network interface using up commands.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
'''
opts = _parse_routes(iface, settings)
try:
template = JINJA.get_template('route_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template route_eth.jinja')
return ''
add_routecfg = template.render(route_type='add',
routes=opts['routes'],
iface=iface)
del_routecfg = template.render(route_type='del',
routes=opts['routes'],
iface=iface)
if 'test' in settings and settings['test']:
return _read_temp(add_routecfg + del_routecfg)
filename = _write_file_routes(iface,
add_routecfg,
_DEB_NETWORK_UP_DIR,
'route-{0}')
results = _read_file(filename)
filename = _write_file_routes(iface,
del_routecfg,
_DEB_NETWORK_DOWN_DIR,
'route-{0}')
results += _read_file(filename)
return results
def down(iface, iface_type):
'''
Shutdown a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.down eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought down.
if iface_type not in ['slave', 'source']:
return __salt__['cmd.run'](['ifdown', iface])
return None
def get_bond(iface):
'''
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
'''
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
return _read_file(path)
def get_interface(iface):
'''
Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
adapters = _parse_interfaces()
if iface in adapters:
try:
if iface == 'source':
template = JINJA.get_template('debian_source.jinja')
else:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': adapters[iface]})
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg.split('\n')]
else:
return []
def up(iface, iface_type): # pylint: disable=C0103
'''
Start up a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.up eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought up.
if iface_type not in ('slave', 'source'):
return __salt__['cmd.run'](['ifup', iface])
return None
def get_network_settings():
'''
Return the contents of the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_network_settings
'''
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
settings = {}
if __salt__['service.available']('networking'):
if __salt__['service.status']('networking'):
settings['networking'] = "yes"
else:
settings['networking'] = "no"
else:
settings['networking'] = "no"
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
settings['hostname'] = hostname
settings['domainname'] = domainname
settings['searchdomain'] = searchdomain
else:
settings = _parse_current_network_settings()
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(settings)
return _read_temp(network)
def get_routes(iface):
'''
Return the routes for the interface
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0
'''
filename = os.path.join(_DEB_NETWORK_UP_DIR, 'route-{0}'.format(iface))
results = _read_file(filename)
filename = os.path.join(_DEB_NETWORK_DOWN_DIR, 'route-{0}'.format(iface))
results += _read_file(filename)
return results
def apply_network_settings(**settings):
'''
Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings
'''
if 'require_reboot' not in settings:
settings['require_reboot'] = False
if 'apply_hostname' not in settings:
settings['apply_hostname'] = False
hostname_res = True
if settings['apply_hostname'] in _CONFIG_TRUE:
if 'hostname' in settings:
hostname_res = __salt__['network.mod_hostname'](settings['hostname'])
else:
log.warning(
'The network state sls is trying to apply hostname '
'changes but no hostname is defined.'
)
hostname_res = False
res = True
if settings['require_reboot'] in _CONFIG_TRUE:
log.warning(
'The network state sls is requiring a reboot of the system to '
'properly apply network configuration.'
)
res = True
else:
stop = __salt__['service.stop']('networking')
time.sleep(2)
res = stop and __salt__['service.start']('networking')
return hostname_res and res
def build_network_settings(**settings):
'''
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
'''
changes = []
# Read current configuration and store default values
current_network_settings = _parse_current_network_settings()
# Build settings
opts = _parse_network_settings(settings, current_network_settings)
# Ubuntu has moved away from /etc/default/networking
# beginning with the 12.04 release so we disable or enable
# the networking related services on boot
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
if opts['networking'] == 'yes':
service_cmd = 'service.enable'
else:
service_cmd = 'service.disable'
if __salt__['service.available']('NetworkManager'):
__salt__[service_cmd]('NetworkManager')
if __salt__['service.available']('networking'):
__salt__[service_cmd]('networking')
else:
try:
template = JINJA.get_template('network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template network.jinja')
return ''
network = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(network)
# Write settings
_write_file_network(network, _DEB_NETWORKING_FILE, True)
# Get hostname and domain from opts
sline = opts['hostname'].split('.', 1)
opts['hostname'] = sline[0]
current_domainname = current_network_settings['domainname']
current_searchdomain = current_network_settings['searchdomain']
new_domain = False
if len(sline) > 1:
new_domainname = sline[1]
if new_domainname != current_domainname:
domainname = new_domainname
opts['domainname'] = new_domainname
new_domain = True
else:
domainname = current_domainname
opts['domainname'] = domainname
else:
domainname = current_domainname
opts['domainname'] = domainname
new_search = False
if 'search' in opts:
new_searchdomain = opts['search']
if new_searchdomain != current_searchdomain:
searchdomain = new_searchdomain
opts['searchdomain'] = new_searchdomain
new_search = True
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
# If the domain changes, then we should write the resolv.conf file.
if new_domain or new_search:
# Look for existing domain line and update if necessary
resolve = _parse_resolve()
domain_prog = re.compile(r'domain\s+')
search_prog = re.compile(r'search\s+')
new_contents = []
for item in _read_file(_DEB_RESOLV_FILE):
if domain_prog.match(item):
item = 'domain {0}'.format(domainname)
elif search_prog.match(item):
item = 'search {0}'.format(searchdomain)
new_contents.append(item)
# A domain line didn't exist so we'll add one in
# with the new domainname
if 'domain' not in resolve:
new_contents.insert(0, 'domain {0}' . format(domainname))
# A search line didn't exist so we'll add one in
# with the new search domain
if 'search' not in resolve:
new_contents.insert('domain' in resolve, 'search {0}'.format(searchdomain))
new_resolv = '\n'.join(new_contents)
# Write /etc/resolv.conf
if not ('test' in settings and settings['test']):
_write_file_network(new_resolv, _DEB_RESOLV_FILE)
# used for returning the results back
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(opts)
changes.extend(_read_temp(network))
return changes
|
saltstack/salt
|
salt/modules/debian_ip.py
|
_parse_bridge_opts
|
python
|
def _parse_bridge_opts(opts, iface):
'''
Filters given options and outputs valid settings for BRIDGING_OPTS
If an option has a value that is not expected, this
function will log the Interface, Setting and what was expected.
'''
config = {}
if 'ports' in opts:
if isinstance(opts['ports'], list):
opts['ports'] = ' '.join(opts['ports'])
config.update({'ports': opts['ports']})
for opt in ['ageing', 'fd', 'gcint', 'hello', 'maxage']:
if opt in opts:
try:
float(opts[opt])
config.update({opt: opts[opt]})
except ValueError:
_raise_error_iface(iface, opt, ['float'])
for opt in ['bridgeprio', 'maxwait']:
if opt in opts:
if isinstance(opts[opt], int):
config.update({opt: opts[opt]})
else:
_raise_error_iface(iface, opt, ['integer'])
if 'hw' in opts:
# match 12 hex digits with either : or - as separators between pairs
if re.match('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$',
opts['hw'].lower()):
config.update({'hw': opts['hw']})
else:
_raise_error_iface(iface, 'hw', ['valid MAC address'])
for opt in ['pathcost', 'portprio']:
if opt in opts:
try:
port, cost_or_prio = opts[opt].split()
int(cost_or_prio)
config.update({opt: '{0} {1}'.format(port, cost_or_prio)})
except ValueError:
_raise_error_iface(iface, opt, ['interface integer'])
if 'stp' in opts:
if opts['stp'] in _CONFIG_TRUE:
config.update({'stp': 'on'})
elif opts['stp'] in _CONFIG_FALSE:
config.update({'stp': 'off'})
else:
_raise_error_iface(iface, 'stp', _CONFIG_TRUE + _CONFIG_FALSE)
if 'waitport' in opts:
if isinstance(opts['waitport'], int):
config.update({'waitport': opts['waitport']})
else:
values = opts['waitport'].split()
waitport_time = values.pop(0)
if waitport_time.isdigit() and values:
config.update({
'waitport': '{0} {1}'.format(
waitport_time, ' '.join(values)
)
})
else:
_raise_error_iface(iface, opt, ['integer [interfaces]'])
return config
|
Filters given options and outputs valid settings for BRIDGING_OPTS
If an option has a value that is not expected, this
function will log the Interface, Setting and what was expected.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_ip.py#L1130-L1198
| null |
# -*- coding: utf-8 -*-
'''
The networking module for Debian-based distros
References:
* http://www.debian.org/doc/manuals/debian-reference/ch05.en.html
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import functools
import logging
import os.path
import os
import re
import time
# Import third party libs
import jinja2
import jinja2.exceptions
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error,no-name-in-module
# Import salt libs
import salt.utils.dns
import salt.utils.files
import salt.utils.odict
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.validate.net
# Set up logging
log = logging.getLogger(__name__)
# Set up template environment
JINJA = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'debian_ip')
)
)
# Define the module's virtual name
__virtualname__ = 'ip'
def __virtual__():
'''
Confine this module to Debian-based distros
'''
if __grains__['os_family'] == 'Debian':
return __virtualname__
return (False, 'The debian_ip module could not be loaded: '
'unsupported OS family')
_ETHTOOL_CONFIG_OPTS = {
'speed': 'link-speed',
'duplex': 'link-duplex',
'autoneg': 'ethernet-autoneg',
'ethernet-port': 'ethernet-port',
'wol': 'ethernet-wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'rx': 'offload-rx',
'tx': 'offload-tx',
'sg': 'offload-sg',
'tso': 'offload-tso',
'ufo': 'offload-ufo',
'gso': 'offload-gso',
'gro': 'offload-gro',
'lro': 'offload-lro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_REV_ETHTOOL_CONFIG_OPTS = {
'link-speed': 'speed',
'link-duplex': 'duplex',
'ethernet-autoneg': 'autoneg',
'ethernet-port': 'ethernet-port',
'ethernet-wol': 'wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'offload-rx': 'rx',
'offload-tx': 'tx',
'offload-sg': 'sg',
'offload-tso': 'tso',
'offload-ufo': 'ufo',
'offload-gso': 'gso',
'offload-lro': 'lro',
'offload-gro': 'gro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_DEB_CONFIG_PPPOE_OPTS = {
'user': 'user',
'password': 'password',
'provider': 'provider',
'pppoe_iface': 'pppoe_iface',
'noipdefault': 'noipdefault',
'usepeerdns': 'usepeerdns',
'defaultroute': 'defaultroute',
'holdoff': 'holdoff',
'maxfail': 'maxfail',
'hide-password': 'hide-password',
'lcp-echo-interval': 'lcp-echo-interval',
'lcp-echo-failure': 'lcp-echo-failure',
'connect': 'connect',
'noauth': 'noauth',
'persist': 'persist',
'mtu': 'mtu',
'noaccomp': 'noaccomp',
'linkname': 'linkname',
}
_DEB_ROUTES_FILE = '/etc/network/routes'
_DEB_NETWORK_FILE = '/etc/network/interfaces'
_DEB_NETWORK_DIR = '/etc/network/interfaces.d/'
_DEB_NETWORK_UP_DIR = '/etc/network/if-up.d/'
_DEB_NETWORK_DOWN_DIR = '/etc/network/if-down.d/'
_DEB_NETWORK_CONF_FILES = '/etc/modprobe.d/'
_DEB_NETWORKING_FILE = '/etc/default/networking'
_DEB_HOSTNAME_FILE = '/etc/hostname'
_DEB_RESOLV_FILE = '/etc/resolv.conf'
_DEB_PPP_DIR = '/etc/ppp/peers/'
_CONFIG_TRUE = ['yes', 'on', 'true', '1', True]
_CONFIG_FALSE = ['no', 'off', 'false', '0', False]
_IFACE_TYPES = [
'eth', 'bond', 'alias', 'clone',
'ipsec', 'dialup', 'bridge', 'slave',
'vlan', 'pppoe', 'source',
]
def _error_msg_iface(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, '|'.join(str(e) for e in expected))
def _error_msg_routes(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, expected)
def _log_default_iface(iface, opt, value):
log.info(
'Using default option -- Interface: %s Option: %s Value: %s',
iface, opt, value
)
def _error_msg_network(option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]'
return msg.format(option, '|'.join(str(e) for e in expected))
def _log_default_network(opt, value):
log.info('Using existing setting -- Setting: %s Value: %s', opt, value)
def _raise_error_iface(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_iface(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_network(option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_network(option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_routes(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_routes(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _read_file(path):
'''
Reads and returns the contents of a text file
'''
try:
with salt.utils.files.flopen(path, 'rb') as contents:
return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]
except (OSError, IOError):
return ''
def _parse_resolve():
'''
Parse /etc/resolv.conf
'''
return salt.utils.dns.parse_resolv(_DEB_RESOLV_FILE)
def _parse_domainname():
'''
Parse /etc/resolv.conf and return domainname
'''
return _parse_resolve().get('domain', '')
def _parse_searchdomain():
'''
Parse /etc/resolv.conf and return searchdomain
'''
return _parse_resolve().get('search', '')
def _parse_hostname():
'''
Parse /etc/hostname and return hostname
'''
contents = _read_file(_DEB_HOSTNAME_FILE)
if contents:
return contents[0].split('\n')[0]
else:
return ''
def _parse_current_network_settings():
'''
Parse /etc/default/networking and return current configuration
'''
opts = salt.utils.odict.OrderedDict()
opts['networking'] = ''
if os.path.isfile(_DEB_NETWORKING_FILE):
with salt.utils.files.fopen(_DEB_NETWORKING_FILE) as contents:
for line in contents:
salt.utils.stringutils.to_unicode(line)
if line.startswith('#'):
continue
elif line.startswith('CONFIGURE_INTERFACES'):
opts['networking'] = line.split('=', 1)[1].strip()
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
opts['hostname'] = hostname
opts['domainname'] = domainname
opts['searchdomain'] = searchdomain
return opts
# def __validator_func(value):
# return (valid: True/False, (transformed) value, error message)
def __ipv4_quad(value):
'''validate an IPv4 address'''
return (salt.utils.validate.net.ipv4_addr(value), value,
'dotted IPv4 address')
def __ipv6(value):
'''validate an IPv6 address'''
return (salt.utils.validate.net.ipv6_addr(value), value,
'IPv6 address')
def __mac(value):
'''validate a mac address'''
return (salt.utils.validate.net.mac(value), value,
'MAC address')
def __anything(value):
return (True, value, None)
def __int(value):
'''validate an integer'''
valid, _value = False, value
try:
_value = int(value)
valid = True
except ValueError:
pass
return (valid, _value, 'integer')
def __float(value):
'''validate a float'''
valid, _value = False, value
try:
_value = float(value)
valid = True
except ValueError:
pass
return (valid, _value, 'float')
def __ipv4_netmask(value):
'''validate an IPv4 dotted quad or integer CIDR netmask'''
valid, errmsg = False, 'dotted quad or integer CIDR (0->32)'
valid, value, _ = __int(value)
if not (valid and 0 <= value <= 32):
valid = salt.utils.validate.net.netmask(value)
return (valid, value, errmsg)
def __ipv6_netmask(value):
'''validate an IPv6 integer netmask'''
valid, errmsg = False, 'IPv6 netmask (0->128)'
valid, value, _ = __int(value)
valid = (valid and 0 <= value <= 128)
return (valid, value, errmsg)
def __within2(value, within=None, errmsg=None, dtype=None):
'''validate that a value is in ``within`` and optionally a ``dtype``'''
valid, _value = False, value
if dtype:
try:
_value = dtype(value) # TODO: this is a bit loose when dtype is a class
valid = _value in within
except ValueError:
pass
else:
valid = _value in within
if errmsg is None:
if dtype:
typename = getattr(dtype, '__name__',
hasattr(dtype, '__class__')
and getattr(dtype.__class__, 'name', dtype))
errmsg = '{0} within \'{1}\''.format(typename, within)
else:
errmsg = 'within \'{0}\''.format(within)
return (valid, _value, errmsg)
def __within(within=None, errmsg=None, dtype=None):
return functools.partial(__within2, within=within,
errmsg=errmsg, dtype=dtype)
def __space_delimited_list(value):
'''validate that a value contains one or more space-delimited values'''
if isinstance(value, six.string_types):
value = value.strip().split()
if hasattr(value, '__iter__') and value != []:
return (True, value, 'space-delimited string')
else:
return (False, value, '{0} is not a valid space-delimited value.\n'.format(value))
SALT_ATTR_TO_DEBIAN_ATTR_MAP = {
'dns': 'dns-nameservers',
'search': 'dns-search',
'hwaddr': 'hwaddress', # TODO: this limits bootp functionality
'ipaddr': 'address',
'ipaddrs': 'addresses',
}
DEBIAN_ATTR_TO_SALT_ATTR_MAP = dict(
(v, k) for (k, v) in six.iteritems(SALT_ATTR_TO_DEBIAN_ATTR_MAP))
# TODO
DEBIAN_ATTR_TO_SALT_ATTR_MAP['address'] = 'address'
DEBIAN_ATTR_TO_SALT_ATTR_MAP['hwaddress'] = 'hwaddress'
IPV4_VALID_PROTO = ['bootp', 'dhcp', 'static', 'manual', 'loopback', 'ppp']
IPV4_ATTR_MAP = {
'proto': __within(IPV4_VALID_PROTO, dtype=six.text_type),
# ipv4 static & manual
'address': __ipv4_quad,
'addresses': __anything,
'netmask': __ipv4_netmask,
'broadcast': __ipv4_quad,
'metric': __int,
'gateway': __ipv4_quad, # supports a colon-delimited list
'pointopoint': __ipv4_quad,
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'link', 'host'], dtype=six.text_type),
# dhcp
'hostname': __anything,
'leasehours': __int,
'leasetime': __int,
'vendor': __anything,
'client': __anything,
# bootp
'bootfile': __anything,
'server': __ipv4_quad,
'hwaddr': __mac,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'dstaddr': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# bond
'slaves': __anything,
# ppp
'provider': __anything,
'unit': __int,
'options': __anything,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
#
'network': __anything, # i don't know what this is
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
IPV6_VALID_PROTO = ['auto', 'loopback', 'static', 'manual',
'dhcp', 'v4tunnel', '6to4']
IPV6_ATTR_MAP = {
'proto': __within(IPV6_VALID_PROTO),
# ipv6 static & manual
'address': __ipv6,
'addresses': __anything,
'netmask': __ipv6_netmask,
'broadcast': __ipv6,
'gateway': __ipv6, # supports a colon-delimited list
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'site', 'link', 'host'], dtype=six.text_type),
# inet6 auto
'privext': __within([0, 1, 2], dtype=int),
'dhcp': __within([0, 1], dtype=int),
# inet6 static & manual & dhcp
'media': __anything,
'accept_ra': __within([0, 1], dtype=int),
'autoconf': __within([0, 1], dtype=int),
'preferred-lifetime': __int,
'dad-attempts': __int, # 0 to disable
'dad-interval': __float,
# bond
'slaves': __anything,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
WIRELESS_ATTR_MAP = {
'wireless-essid': __anything,
'wireless-mode': __anything, # TODO
'wpa-ap-scan': __within([0, 1, 2], dtype=int), # TODO
'wpa-conf': __anything,
'wpa-driver': __anything,
'wpa-group': __anything,
'wpa-key-mgmt': __anything,
'wpa-pairwise': __anything,
'wpa-psk': __anything,
'wpa-proto': __anything, # partial(__within,
'wpa-roam': __anything,
'wpa-ssid': __anything, # TODO
}
ATTRMAPS = {
'inet': [IPV4_ATTR_MAP, WIRELESS_ATTR_MAP],
'inet6': [IPV6_ATTR_MAP, WIRELESS_ATTR_MAP]
}
def _validate_interface_option(attr, value, addrfam='inet'):
'''lookup the validation function for a [addrfam][attr] and
return the results
:param attr: attribute name
:param value: raw setting value
:param addrfam: address family (inet, inet6,
'''
valid, _value, errmsg = False, value, 'Unknown validator'
attrmaps = ATTRMAPS.get(addrfam, [])
for attrmap in attrmaps:
if attr in attrmap:
validate_func = attrmap[attr]
(valid, _value, errmsg) = validate_func(value)
break
return (valid, _value, errmsg)
def _attrmaps_contain_attr(attr):
return (
attr in WIRELESS_ATTR_MAP or
attr in IPV4_ATTR_MAP or
attr in IPV6_ATTR_MAP)
def _parse_interfaces(interface_files=None):
'''
Parse /etc/network/interfaces and return current configured interfaces
'''
if interface_files is None:
interface_files = []
# Add this later.
if os.path.exists(_DEB_NETWORK_DIR):
interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]
if os.path.isfile(_DEB_NETWORK_FILE):
interface_files.insert(0, _DEB_NETWORK_FILE)
adapters = salt.utils.odict.OrderedDict()
method = -1
for interface_file in interface_files:
with salt.utils.files.fopen(interface_file) as interfaces:
# This ensures iface_dict exists, but does not ensure we're not reading a new interface.
iface_dict = {}
for line in interfaces:
line = salt.utils.stringutils.to_unicode(line)
# Identify the clauses by the first word of each line.
# Go to the next line if the current line is a comment
# or all spaces.
if line.lstrip().startswith('#') or line.isspace():
continue
# Parse the iface clause
if line.startswith('iface'):
sline = line.split()
if len(sline) != 4:
msg = 'Interface file malformed: {0}.'
msg = msg.format(sline)
log.error(msg)
raise AttributeError(msg)
iface_name = sline[1]
addrfam = sline[2]
method = sline[3]
# Create item in dict, if not already there
if iface_name not in adapters:
adapters[iface_name] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters[iface_name]:
adapters[iface_name]['data'] = salt.utils.odict.OrderedDict()
if addrfam not in adapters[iface_name]['data']:
adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict()
iface_dict = adapters[iface_name]['data'][addrfam]
iface_dict['addrfam'] = addrfam
iface_dict['proto'] = method
iface_dict['filename'] = interface_file
# Parse the detail clauses.
elif line[0].isspace():
sline = line.split()
# conf file attr: dns-nameservers
# salt states.network attr: dns
attr, valuestr = line.rstrip().split(None, 1)
if _attrmaps_contain_attr(attr):
if '-' in attr:
attrname = attr.replace('-', '_')
else:
attrname = attr
(valid, value, errmsg) = _validate_interface_option(
attr, valuestr, addrfam)
if attrname == 'address' and 'address' in iface_dict:
if 'addresses' not in iface_dict:
iface_dict['addresses'] = []
iface_dict['addresses'].append(value)
else:
iface_dict[attrname] = value
elif attr in _REV_ETHTOOL_CONFIG_OPTS:
if 'ethtool' not in iface_dict:
iface_dict['ethtool'] = salt.utils.odict.OrderedDict()
iface_dict['ethtool'][attr] = valuestr
elif attr.startswith('bond'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bonding' not in iface_dict:
iface_dict['bonding'] = salt.utils.odict.OrderedDict()
iface_dict['bonding'][opt] = valuestr
elif attr.startswith('bridge'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bridging' not in iface_dict:
iface_dict['bridging'] = salt.utils.odict.OrderedDict()
iface_dict['bridging'][opt] = valuestr
elif attr in ['up', 'pre-up', 'post-up',
'down', 'pre-down', 'post-down']:
cmd = valuestr
cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr))
if cmd_key not in iface_dict:
iface_dict[cmd_key] = []
iface_dict[cmd_key].append(cmd)
elif line.startswith('auto'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['enabled'] = True
elif line.startswith('allow-hotplug'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['hotplug'] = True
elif line.startswith('source'):
if 'source' not in adapters:
adapters['source'] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters['source']:
adapters['source']['data'] = salt.utils.odict.OrderedDict()
adapters['source']['data']['sources'] = []
adapters['source']['data']['sources'].append(line.split()[1])
# Return a sorted list of the keys for bond, bridge and ethtool options to
# ensure a consistent order
for iface_name in adapters:
if iface_name == 'source':
continue
if 'data' not in adapters[iface_name]:
msg = 'Interface file malformed for interface: {0}.'.format(iface_name)
log.error(msg)
adapters.pop(iface_name)
continue
for opt in ['ethtool', 'bonding', 'bridging']:
for inet in ['inet', 'inet6']:
if inet in adapters[iface_name]['data']:
if opt in adapters[iface_name]['data'][inet]:
opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys())
adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys
return adapters
def _parse_ethtool_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
if 'autoneg' in opts:
if opts['autoneg'] in _CONFIG_TRUE:
config.update({'autoneg': 'on'})
elif opts['autoneg'] in _CONFIG_FALSE:
config.update({'autoneg': 'off'})
else:
_raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE)
if 'duplex' in opts:
valid = ['full', 'half']
if opts['duplex'] in valid:
config.update({'duplex': opts['duplex']})
else:
_raise_error_iface(iface, 'duplex', valid)
if 'speed' in opts:
valid = ['10', '100', '1000', '10000']
if six.text_type(opts['speed']) in valid:
config.update({'speed': opts['speed']})
else:
_raise_error_iface(iface, opts['speed'], valid)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'on'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'off'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_ethtool_pppoe_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
for opt in _DEB_CONFIG_PPPOE_OPTS:
if opt in opts:
config[opt] = opts[opt]
if 'provider' in opts and not opts['provider']:
_raise_error_iface(iface, 'provider', _CONFIG_TRUE + _CONFIG_FALSE)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('noipdefault', 'usepeerdns', 'defaultroute', 'hide-password', 'noauth', 'persist', 'noaccomp'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'True'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'False'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_settings_bond(opts, iface):
'''
Filters given options and outputs valid settings for requested
operation. If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond_def = {
# 803.ad aggregation selection logic
# 0 for stable (default)
# 1 for bandwidth
# 2 for count
'ad_select': '0',
# Max number of transmit queues (default = 16)
'tx_queues': '16',
# Link monitoring in milliseconds. Most NICs support this
'miimon': '100',
# ARP interval in milliseconds
'arp_interval': '250',
# Delay before considering link down in milliseconds (miimon * 2)
'downdelay': '200',
# lacp_rate 0: Slow - every 30 seconds
# lacp_rate 1: Fast - every 1 second
'lacp_rate': '0',
# Max bonds for this driver
'max_bonds': '1',
# Specifies the time, in milliseconds, to wait before
# enabling a slave after a link recovery has been
# detected. Only used with miimon.
'updelay': '0',
# Used with miimon.
# On: driver sends mii
# Off: ethtool sends mii
'use_carrier': 'on',
# Default. Don't change unless you know what you are doing.
'xmit_hash_policy': 'layer2',
}
if opts['mode'] in ['balance-rr', '0']:
log.info('Device: %s Bonding Mode: load balancing (round-robin)', iface)
return _parse_settings_bond_0(opts, iface, bond_def)
elif opts['mode'] in ['active-backup', '1']:
log.info('Device: %s Bonding Mode: fault-tolerance (active-backup)', iface)
return _parse_settings_bond_1(opts, iface, bond_def)
elif opts['mode'] in ['balance-xor', '2']:
log.info('Device: %s Bonding Mode: load balancing (xor)', iface)
return _parse_settings_bond_2(opts, iface, bond_def)
elif opts['mode'] in ['broadcast', '3']:
log.info('Device: %s Bonding Mode: fault-tolerance (broadcast)', iface)
return _parse_settings_bond_3(opts, iface, bond_def)
elif opts['mode'] in ['802.3ad', '4']:
log.info('Device: %s Bonding Mode: IEEE 802.3ad Dynamic link '
'aggregation', iface)
return _parse_settings_bond_4(opts, iface, bond_def)
elif opts['mode'] in ['balance-tlb', '5']:
log.info('Device: %s Bonding Mode: transmit load balancing', iface)
return _parse_settings_bond_5(opts, iface, bond_def)
elif opts['mode'] in ['balance-alb', '6']:
log.info('Device: %s Bonding Mode: adaptive load balancing', iface)
return _parse_settings_bond_6(opts, iface, bond_def)
else:
valid = [
'0', '1', '2', '3', '4', '5', '6',
'balance-rr', 'active-backup', 'balance-xor',
'broadcast', '802.3ad', 'balance-tlb', 'balance-alb'
]
_raise_error_iface(iface, 'mode', valid)
def _parse_settings_bond_0(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond0.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '0'}
# ARP targets in n.n.n.n form
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
return bond
def _parse_settings_bond_1(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '1'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
if not (__grains__['os'] == "Ubuntu" and __grains__['osrelease_info'][0] >= 16):
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_2(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond2.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '2'}
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_3(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond3.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '3'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_4(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond4.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '4'}
for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']:
if binding in opts:
if binding == 'lacp_rate':
if opts[binding] == 'fast':
opts.update({binding: '1'})
if opts[binding] == 'slow':
opts.update({binding: '0'})
valid = ['fast', '1', 'slow', '0']
else:
valid = ['integer']
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, valid)
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_5(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond5.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '5'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_settings_bond_6(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond6.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '6'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_settings_eth(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['inet'] = salt.utils.odict.OrderedDict()
iface_data['inet6'] = salt.utils.odict.OrderedDict()
if enabled:
adapters[iface]['enabled'] = True
if opts.get('hotplug', False):
adapters[iface]['hotplug'] = True
if opts.get('enable_ipv6', None) and opts.get('iface_type', '') == 'vlan':
iface_data['inet6']['vlan_raw_device'] = (
re.sub(r'\.\d*', '', iface))
for addrfam in ['inet', 'inet6']:
if iface_type not in ['bridge']:
tmp_ethtool = _parse_ethtool_opts(opts, iface)
if tmp_ethtool:
ethtool = {}
for item in tmp_ethtool:
ethtool[_ETHTOOL_CONFIG_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['ethtool'] = ethtool
# return a list of sorted keys to ensure consistent order
iface_data[addrfam]['ethtool_keys'] = sorted(ethtool)
if iface_type == 'bridge':
bridging = _parse_bridge_opts(opts, iface)
if bridging:
iface_data[addrfam]['bridging'] = bridging
iface_data[addrfam]['bridging_keys'] = sorted(bridging)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'bond':
bonding = _parse_settings_bond(opts, iface)
if bonding:
iface_data[addrfam]['bonding'] = bonding
iface_data[addrfam]['bonding']['slaves'] = opts['slaves']
iface_data[addrfam]['bonding_keys'] = sorted(bonding)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'slave':
adapters[iface]['master'] = opts['master']
opts['proto'] = 'manual'
iface_data[addrfam]['master'] = adapters[iface]['master']
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'vlan':
iface_data[addrfam]['vlan_raw_device'] = re.sub(r'\.\d*', '', iface)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'pppoe':
tmp_ethtool = _parse_ethtool_pppoe_opts(opts, iface)
if tmp_ethtool:
for item in tmp_ethtool:
adapters[iface]['data'][addrfam][_DEB_CONFIG_PPPOE_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['addrfam'] = addrfam
opts.pop('mode', None)
for opt, val in opts.items():
inet = None
if opt.startswith('ipv4'):
opt = opt[4:]
inet = 'inet'
iface_data['inet']['addrfam'] = 'inet'
elif opt.startswith('ipv6'):
iface_data['inet6']['addrfam'] = 'inet6'
opt = opt[4:]
inet = 'inet6'
elif opt in ['ipaddr', 'address', 'ipaddresses', 'addresses', 'gateway', 'proto']:
iface_data['inet']['addrfam'] = 'inet'
inet = 'inet'
_opt = SALT_ATTR_TO_DEBIAN_ATTR_MAP.get(opt, opt)
_debopt = _opt.replace('-', '_')
for addrfam in ['inet', 'inet6']:
(valid, value, errmsg) = _validate_interface_option(_opt, val, addrfam=addrfam)
if not valid:
continue
if inet is None and _debopt not in iface_data[addrfam]:
iface_data[addrfam][_debopt] = value
elif inet == addrfam:
iface_data[addrfam][_debopt] = value
for opt in ['up_cmds', 'pre_up_cmds', 'post_up_cmds',
'down_cmds', 'pre_down_cmds', 'post_down_cmds']:
if opt in opts:
iface_data['inet'][opt] = opts[opt]
iface_data['inet6'][opt] = opts[opt]
# Remove incomplete/disabled inet blocks
for (addrfam, opt) in [('inet', 'enable_ipv4'), ('inet6', 'enable_ipv6')]:
if opts.get(opt, None) is False:
iface_data.pop(addrfam)
elif iface_data[addrfam].get('addrfam', '') != addrfam:
iface_data.pop(addrfam)
return adapters
def _parse_settings_source(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['sources'] = [opts['source']]
return adapters
def _parse_network_settings(opts, current):
'''
Filters given options and outputs valid settings for
the global network settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
current = dict((k.lower(), v) for (k, v) in six.iteritems(current))
result = {}
valid = _CONFIG_TRUE + _CONFIG_FALSE
if 'enabled' not in opts:
try:
opts['networking'] = current['networking']
_log_default_network('networking', current['networking'])
except ValueError:
_raise_error_network('networking', valid)
else:
opts['networking'] = opts['enabled']
if opts['networking'] in valid:
if opts['networking'] in _CONFIG_TRUE:
result['networking'] = 'yes'
elif opts['networking'] in _CONFIG_FALSE:
result['networking'] = 'no'
else:
_raise_error_network('networking', valid)
if 'hostname' not in opts:
try:
opts['hostname'] = current['hostname']
_log_default_network('hostname', current['hostname'])
except ValueError:
_raise_error_network('hostname', ['server1.example.com'])
if opts['hostname']:
result['hostname'] = opts['hostname']
else:
_raise_error_network('hostname', ['server1.example.com'])
if 'search' in opts:
result['search'] = opts['search']
return result
def _parse_routes(iface, opts):
'''
Filters given options and outputs valid settings for
the route settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
result = {}
if 'routes' not in opts:
_raise_error_routes(iface, 'routes', 'List of routes')
for opt in opts:
result[opt] = opts[opt]
return result
def _write_file(iface, data, folder, pattern):
'''
Writes a file to disk
'''
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
return filename
def _write_file_routes(iface, data, folder, pattern):
'''
Writes a file to disk
'''
# ifup / ifdown is executing given folder via run-parts.
# according to run-parts man-page, only filenames with this pattern are
# executed: (^[a-zA-Z0-9_-]+$)
# In order to make the routes file work for vlan interfaces
# (default would have been in example /etc/network/if-up.d/route-bond0.12)
# these dots in the iface name need to be replaced by underscores, so it
# can be executed by run-parts
iface = iface.replace('.', '_')
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
__salt__['file.set_mode'](filename, '0755')
return filename
def _write_file_network(data, filename, create=False):
'''
Writes a file to disk
If file does not exist, only create if create
argument is True
'''
if not os.path.exists(filename) and not create:
msg = '{0} cannot be written. {0} does not exist\
and create is set to False'
msg = msg.format(filename)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
def _read_temp(data):
'''
Return what would be written to disk
'''
tout = StringIO()
tout.write(data)
tout.seek(0)
output = tout.readlines()
tout.close()
return output
def _read_temp_ifaces(iface, data):
'''
Return what would be written to disk for interfaces
'''
try:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': data})
# Return as an array so the difflib works
return [item + '\n' for item in ifcfg.split('\n')]
def _write_file_ifaces(iface, data, **settings):
'''
Writes a file to disk
'''
try:
eth_template = JINJA.get_template('debian_eth.jinja')
source_template = JINJA.get_template('debian_source.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
# Read /etc/network/interfaces into a dict
adapters = _parse_interfaces()
# Apply supplied settings over on-disk settings
adapters[iface] = data
ifcfg = ''
for adapter in adapters:
if 'type' in adapters[adapter] and adapters[adapter]['type'] == 'source':
tmp = source_template.render({'name': adapter, 'data': adapters[adapter]})
else:
tmp = eth_template.render({'name': adapter, 'data': adapters[adapter]})
ifcfg = ifcfg + tmp
if adapter == iface:
saved_ifcfg = tmp
_SEPARATE_FILE = False
if 'filename' in settings:
if not settings['filename'].startswith('/'):
filename = '{0}/{1}'.format(_DEB_NETWORK_DIR, settings['filename'])
else:
filename = settings['filename']
_SEPARATE_FILE = True
else:
if 'filename' in adapters[adapter]['data']:
filename = adapters[adapter]['data']
else:
filename = _DEB_NETWORK_FILE
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
if _SEPARATE_FILE:
fout.write(salt.utils.stringutils.to_str(saved_ifcfg))
else:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return saved_ifcfg.split('\n')
def _write_file_ppp_ifaces(iface, data):
'''
Writes a file to disk
'''
try:
template = JINJA.get_template('debian_ppp_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_ppp_eth.jinja')
return ''
adapters = _parse_interfaces()
adapters[iface] = data
ifcfg = ''
tmp = template.render({'data': adapters[iface]})
ifcfg = tmp + ifcfg
filename = _DEB_PPP_DIR + '/' + adapters[iface]['data']['inet']['provider']
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.fopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return filename
def build_bond(iface, **settings):
'''
Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb
'''
deb_major = __grains__['osrelease'][:1]
opts = _parse_settings_bond(settings, iface)
try:
template = JINJA.get_template('conf.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template conf.jinja')
return ''
data = template.render({'name': iface, 'bonding': opts})
if 'test' in settings and settings['test']:
return _read_temp(data)
_write_file(iface, data, _DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
if deb_major == '5':
for line_type in ('alias', 'options'):
cmd = ['sed', '-i', '-e', r'/^{0}\s{1}.*/d'.format(line_type, iface),
'/etc/modprobe.conf']
__salt__['cmd.run'](cmd, python_shell=False)
__salt__['file.append']('/etc/modprobe.conf', path)
# Load kernel module
__salt__['kmod.load']('bonding')
# install ifenslave-2.6
__salt__['pkg.install']('ifenslave-2.6')
return _read_file(path)
def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'vlan':
settings['vlan'] = 'yes'
__salt__['pkg.install']('vlan')
elif iface_type == 'pppoe':
settings['pppoe'] = 'yes'
if not __salt__['pkg.version']('ppp'):
inst = __salt__['pkg.install']('ppp')
elif iface_type == 'bond':
if 'slaves' not in settings:
msg = 'slaves is a required setting for bond interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'bridge':
if 'ports' not in settings:
msg = (
'ports is a required setting for bridge interfaces on Debian '
'or Ubuntu based systems'
)
log.error(msg)
raise AttributeError(msg)
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'pppoe']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
if iface_type in ['source']:
opts = _parse_settings_source(settings, iface_type, enabled, iface)
if 'test' in settings and settings['test']:
return _read_temp_ifaces(iface, opts[iface])
ifcfg = _write_file_ifaces(iface, opts[iface], **settings)
if iface_type == 'pppoe':
_write_file_ppp_ifaces(iface, opts[iface])
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg]
def build_routes(iface, **settings):
'''
Add route scripts for a network interface using up commands.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
'''
opts = _parse_routes(iface, settings)
try:
template = JINJA.get_template('route_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template route_eth.jinja')
return ''
add_routecfg = template.render(route_type='add',
routes=opts['routes'],
iface=iface)
del_routecfg = template.render(route_type='del',
routes=opts['routes'],
iface=iface)
if 'test' in settings and settings['test']:
return _read_temp(add_routecfg + del_routecfg)
filename = _write_file_routes(iface,
add_routecfg,
_DEB_NETWORK_UP_DIR,
'route-{0}')
results = _read_file(filename)
filename = _write_file_routes(iface,
del_routecfg,
_DEB_NETWORK_DOWN_DIR,
'route-{0}')
results += _read_file(filename)
return results
def down(iface, iface_type):
'''
Shutdown a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.down eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought down.
if iface_type not in ['slave', 'source']:
return __salt__['cmd.run'](['ifdown', iface])
return None
def get_bond(iface):
'''
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
'''
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
return _read_file(path)
def get_interface(iface):
'''
Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
adapters = _parse_interfaces()
if iface in adapters:
try:
if iface == 'source':
template = JINJA.get_template('debian_source.jinja')
else:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': adapters[iface]})
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg.split('\n')]
else:
return []
def up(iface, iface_type): # pylint: disable=C0103
'''
Start up a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.up eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought up.
if iface_type not in ('slave', 'source'):
return __salt__['cmd.run'](['ifup', iface])
return None
def get_network_settings():
'''
Return the contents of the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_network_settings
'''
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
settings = {}
if __salt__['service.available']('networking'):
if __salt__['service.status']('networking'):
settings['networking'] = "yes"
else:
settings['networking'] = "no"
else:
settings['networking'] = "no"
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
settings['hostname'] = hostname
settings['domainname'] = domainname
settings['searchdomain'] = searchdomain
else:
settings = _parse_current_network_settings()
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(settings)
return _read_temp(network)
def get_routes(iface):
'''
Return the routes for the interface
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0
'''
filename = os.path.join(_DEB_NETWORK_UP_DIR, 'route-{0}'.format(iface))
results = _read_file(filename)
filename = os.path.join(_DEB_NETWORK_DOWN_DIR, 'route-{0}'.format(iface))
results += _read_file(filename)
return results
def apply_network_settings(**settings):
'''
Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings
'''
if 'require_reboot' not in settings:
settings['require_reboot'] = False
if 'apply_hostname' not in settings:
settings['apply_hostname'] = False
hostname_res = True
if settings['apply_hostname'] in _CONFIG_TRUE:
if 'hostname' in settings:
hostname_res = __salt__['network.mod_hostname'](settings['hostname'])
else:
log.warning(
'The network state sls is trying to apply hostname '
'changes but no hostname is defined.'
)
hostname_res = False
res = True
if settings['require_reboot'] in _CONFIG_TRUE:
log.warning(
'The network state sls is requiring a reboot of the system to '
'properly apply network configuration.'
)
res = True
else:
stop = __salt__['service.stop']('networking')
time.sleep(2)
res = stop and __salt__['service.start']('networking')
return hostname_res and res
def build_network_settings(**settings):
'''
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
'''
changes = []
# Read current configuration and store default values
current_network_settings = _parse_current_network_settings()
# Build settings
opts = _parse_network_settings(settings, current_network_settings)
# Ubuntu has moved away from /etc/default/networking
# beginning with the 12.04 release so we disable or enable
# the networking related services on boot
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
if opts['networking'] == 'yes':
service_cmd = 'service.enable'
else:
service_cmd = 'service.disable'
if __salt__['service.available']('NetworkManager'):
__salt__[service_cmd]('NetworkManager')
if __salt__['service.available']('networking'):
__salt__[service_cmd]('networking')
else:
try:
template = JINJA.get_template('network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template network.jinja')
return ''
network = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(network)
# Write settings
_write_file_network(network, _DEB_NETWORKING_FILE, True)
# Get hostname and domain from opts
sline = opts['hostname'].split('.', 1)
opts['hostname'] = sline[0]
current_domainname = current_network_settings['domainname']
current_searchdomain = current_network_settings['searchdomain']
new_domain = False
if len(sline) > 1:
new_domainname = sline[1]
if new_domainname != current_domainname:
domainname = new_domainname
opts['domainname'] = new_domainname
new_domain = True
else:
domainname = current_domainname
opts['domainname'] = domainname
else:
domainname = current_domainname
opts['domainname'] = domainname
new_search = False
if 'search' in opts:
new_searchdomain = opts['search']
if new_searchdomain != current_searchdomain:
searchdomain = new_searchdomain
opts['searchdomain'] = new_searchdomain
new_search = True
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
# If the domain changes, then we should write the resolv.conf file.
if new_domain or new_search:
# Look for existing domain line and update if necessary
resolve = _parse_resolve()
domain_prog = re.compile(r'domain\s+')
search_prog = re.compile(r'search\s+')
new_contents = []
for item in _read_file(_DEB_RESOLV_FILE):
if domain_prog.match(item):
item = 'domain {0}'.format(domainname)
elif search_prog.match(item):
item = 'search {0}'.format(searchdomain)
new_contents.append(item)
# A domain line didn't exist so we'll add one in
# with the new domainname
if 'domain' not in resolve:
new_contents.insert(0, 'domain {0}' . format(domainname))
# A search line didn't exist so we'll add one in
# with the new search domain
if 'search' not in resolve:
new_contents.insert('domain' in resolve, 'search {0}'.format(searchdomain))
new_resolv = '\n'.join(new_contents)
# Write /etc/resolv.conf
if not ('test' in settings and settings['test']):
_write_file_network(new_resolv, _DEB_RESOLV_FILE)
# used for returning the results back
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(opts)
changes.extend(_read_temp(network))
return changes
|
saltstack/salt
|
salt/modules/debian_ip.py
|
_parse_settings_eth
|
python
|
def _parse_settings_eth(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['inet'] = salt.utils.odict.OrderedDict()
iface_data['inet6'] = salt.utils.odict.OrderedDict()
if enabled:
adapters[iface]['enabled'] = True
if opts.get('hotplug', False):
adapters[iface]['hotplug'] = True
if opts.get('enable_ipv6', None) and opts.get('iface_type', '') == 'vlan':
iface_data['inet6']['vlan_raw_device'] = (
re.sub(r'\.\d*', '', iface))
for addrfam in ['inet', 'inet6']:
if iface_type not in ['bridge']:
tmp_ethtool = _parse_ethtool_opts(opts, iface)
if tmp_ethtool:
ethtool = {}
for item in tmp_ethtool:
ethtool[_ETHTOOL_CONFIG_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['ethtool'] = ethtool
# return a list of sorted keys to ensure consistent order
iface_data[addrfam]['ethtool_keys'] = sorted(ethtool)
if iface_type == 'bridge':
bridging = _parse_bridge_opts(opts, iface)
if bridging:
iface_data[addrfam]['bridging'] = bridging
iface_data[addrfam]['bridging_keys'] = sorted(bridging)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'bond':
bonding = _parse_settings_bond(opts, iface)
if bonding:
iface_data[addrfam]['bonding'] = bonding
iface_data[addrfam]['bonding']['slaves'] = opts['slaves']
iface_data[addrfam]['bonding_keys'] = sorted(bonding)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'slave':
adapters[iface]['master'] = opts['master']
opts['proto'] = 'manual'
iface_data[addrfam]['master'] = adapters[iface]['master']
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'vlan':
iface_data[addrfam]['vlan_raw_device'] = re.sub(r'\.\d*', '', iface)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'pppoe':
tmp_ethtool = _parse_ethtool_pppoe_opts(opts, iface)
if tmp_ethtool:
for item in tmp_ethtool:
adapters[iface]['data'][addrfam][_DEB_CONFIG_PPPOE_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['addrfam'] = addrfam
opts.pop('mode', None)
for opt, val in opts.items():
inet = None
if opt.startswith('ipv4'):
opt = opt[4:]
inet = 'inet'
iface_data['inet']['addrfam'] = 'inet'
elif opt.startswith('ipv6'):
iface_data['inet6']['addrfam'] = 'inet6'
opt = opt[4:]
inet = 'inet6'
elif opt in ['ipaddr', 'address', 'ipaddresses', 'addresses', 'gateway', 'proto']:
iface_data['inet']['addrfam'] = 'inet'
inet = 'inet'
_opt = SALT_ATTR_TO_DEBIAN_ATTR_MAP.get(opt, opt)
_debopt = _opt.replace('-', '_')
for addrfam in ['inet', 'inet6']:
(valid, value, errmsg) = _validate_interface_option(_opt, val, addrfam=addrfam)
if not valid:
continue
if inet is None and _debopt not in iface_data[addrfam]:
iface_data[addrfam][_debopt] = value
elif inet == addrfam:
iface_data[addrfam][_debopt] = value
for opt in ['up_cmds', 'pre_up_cmds', 'post_up_cmds',
'down_cmds', 'pre_down_cmds', 'post_down_cmds']:
if opt in opts:
iface_data['inet'][opt] = opts[opt]
iface_data['inet6'][opt] = opts[opt]
# Remove incomplete/disabled inet blocks
for (addrfam, opt) in [('inet', 'enable_ipv4'), ('inet6', 'enable_ipv6')]:
if opts.get(opt, None) is False:
iface_data.pop(addrfam)
elif iface_data[addrfam].get('addrfam', '') != addrfam:
iface_data.pop(addrfam)
return adapters
|
Filters given options and outputs valid settings for a
network interface.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_ip.py#L1201-L1312
|
[
"def _validate_interface_option(attr, value, addrfam='inet'):\n '''lookup the validation function for a [addrfam][attr] and\n return the results\n\n :param attr: attribute name\n :param value: raw setting value\n :param addrfam: address family (inet, inet6,\n '''\n valid, _value, errmsg = False, value, 'Unknown validator'\n attrmaps = ATTRMAPS.get(addrfam, [])\n for attrmap in attrmaps:\n if attr in attrmap:\n validate_func = attrmap[attr]\n (valid, _value, errmsg) = validate_func(value)\n break\n return (valid, _value, errmsg)\n",
"def _parse_ethtool_opts(opts, iface):\n '''\n Filters given options and outputs valid settings for ETHTOOLS_OPTS\n If an option has a value that is not expected, this\n function will log what the Interface, Setting and what it was\n expecting.\n '''\n config = {}\n\n if 'autoneg' in opts:\n if opts['autoneg'] in _CONFIG_TRUE:\n config.update({'autoneg': 'on'})\n elif opts['autoneg'] in _CONFIG_FALSE:\n config.update({'autoneg': 'off'})\n else:\n _raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE)\n\n if 'duplex' in opts:\n valid = ['full', 'half']\n if opts['duplex'] in valid:\n config.update({'duplex': opts['duplex']})\n else:\n _raise_error_iface(iface, 'duplex', valid)\n\n if 'speed' in opts:\n valid = ['10', '100', '1000', '10000']\n if six.text_type(opts['speed']) in valid:\n config.update({'speed': opts['speed']})\n else:\n _raise_error_iface(iface, opts['speed'], valid)\n\n valid = _CONFIG_TRUE + _CONFIG_FALSE\n for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'):\n if option in opts:\n if opts[option] in _CONFIG_TRUE:\n config.update({option: 'on'})\n elif opts[option] in _CONFIG_FALSE:\n config.update({option: 'off'})\n else:\n _raise_error_iface(iface, option, valid)\n\n return config\n",
"def _parse_ethtool_pppoe_opts(opts, iface):\n '''\n Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS\n If an option has a value that is not expected, this\n function will log what the Interface, Setting and what it was\n expecting.\n '''\n config = {}\n\n for opt in _DEB_CONFIG_PPPOE_OPTS:\n if opt in opts:\n config[opt] = opts[opt]\n\n if 'provider' in opts and not opts['provider']:\n _raise_error_iface(iface, 'provider', _CONFIG_TRUE + _CONFIG_FALSE)\n\n valid = _CONFIG_TRUE + _CONFIG_FALSE\n for option in ('noipdefault', 'usepeerdns', 'defaultroute', 'hide-password', 'noauth', 'persist', 'noaccomp'):\n if option in opts:\n if opts[option] in _CONFIG_TRUE:\n config.update({option: 'True'})\n elif opts[option] in _CONFIG_FALSE:\n config.update({option: 'False'})\n else:\n _raise_error_iface(iface, option, valid)\n\n return config\n",
"def _parse_settings_bond(opts, iface):\n '''\n Filters given options and outputs valid settings for requested\n operation. If an option has a value that is not expected, this\n function will log what the Interface, Setting and what it was\n expecting.\n '''\n\n bond_def = {\n # 803.ad aggregation selection logic\n # 0 for stable (default)\n # 1 for bandwidth\n # 2 for count\n 'ad_select': '0',\n # Max number of transmit queues (default = 16)\n 'tx_queues': '16',\n # Link monitoring in milliseconds. Most NICs support this\n 'miimon': '100',\n # ARP interval in milliseconds\n 'arp_interval': '250',\n # Delay before considering link down in milliseconds (miimon * 2)\n 'downdelay': '200',\n # lacp_rate 0: Slow - every 30 seconds\n # lacp_rate 1: Fast - every 1 second\n 'lacp_rate': '0',\n # Max bonds for this driver\n 'max_bonds': '1',\n # Specifies the time, in milliseconds, to wait before\n # enabling a slave after a link recovery has been\n # detected. Only used with miimon.\n 'updelay': '0',\n # Used with miimon.\n # On: driver sends mii\n # Off: ethtool sends mii\n 'use_carrier': 'on',\n # Default. Don't change unless you know what you are doing.\n 'xmit_hash_policy': 'layer2',\n }\n\n if opts['mode'] in ['balance-rr', '0']:\n log.info('Device: %s Bonding Mode: load balancing (round-robin)', iface)\n return _parse_settings_bond_0(opts, iface, bond_def)\n elif opts['mode'] in ['active-backup', '1']:\n log.info('Device: %s Bonding Mode: fault-tolerance (active-backup)', iface)\n return _parse_settings_bond_1(opts, iface, bond_def)\n elif opts['mode'] in ['balance-xor', '2']:\n log.info('Device: %s Bonding Mode: load balancing (xor)', iface)\n return _parse_settings_bond_2(opts, iface, bond_def)\n elif opts['mode'] in ['broadcast', '3']:\n log.info('Device: %s Bonding Mode: fault-tolerance (broadcast)', iface)\n return _parse_settings_bond_3(opts, iface, bond_def)\n elif opts['mode'] in ['802.3ad', '4']:\n log.info('Device: %s Bonding Mode: IEEE 802.3ad Dynamic link '\n 'aggregation', iface)\n return _parse_settings_bond_4(opts, iface, bond_def)\n elif opts['mode'] in ['balance-tlb', '5']:\n log.info('Device: %s Bonding Mode: transmit load balancing', iface)\n return _parse_settings_bond_5(opts, iface, bond_def)\n elif opts['mode'] in ['balance-alb', '6']:\n log.info('Device: %s Bonding Mode: adaptive load balancing', iface)\n return _parse_settings_bond_6(opts, iface, bond_def)\n else:\n valid = [\n '0', '1', '2', '3', '4', '5', '6',\n 'balance-rr', 'active-backup', 'balance-xor',\n 'broadcast', '802.3ad', 'balance-tlb', 'balance-alb'\n ]\n _raise_error_iface(iface, 'mode', valid)\n",
"def _parse_bridge_opts(opts, iface):\n '''\n Filters given options and outputs valid settings for BRIDGING_OPTS\n If an option has a value that is not expected, this\n function will log the Interface, Setting and what was expected.\n '''\n config = {}\n\n if 'ports' in opts:\n if isinstance(opts['ports'], list):\n opts['ports'] = ' '.join(opts['ports'])\n config.update({'ports': opts['ports']})\n\n for opt in ['ageing', 'fd', 'gcint', 'hello', 'maxage']:\n if opt in opts:\n try:\n float(opts[opt])\n config.update({opt: opts[opt]})\n except ValueError:\n _raise_error_iface(iface, opt, ['float'])\n\n for opt in ['bridgeprio', 'maxwait']:\n if opt in opts:\n if isinstance(opts[opt], int):\n config.update({opt: opts[opt]})\n else:\n _raise_error_iface(iface, opt, ['integer'])\n\n if 'hw' in opts:\n # match 12 hex digits with either : or - as separators between pairs\n if re.match('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\\\1[0-9a-f]{2}){4}$',\n opts['hw'].lower()):\n config.update({'hw': opts['hw']})\n else:\n _raise_error_iface(iface, 'hw', ['valid MAC address'])\n\n for opt in ['pathcost', 'portprio']:\n if opt in opts:\n try:\n port, cost_or_prio = opts[opt].split()\n int(cost_or_prio)\n config.update({opt: '{0} {1}'.format(port, cost_or_prio)})\n except ValueError:\n _raise_error_iface(iface, opt, ['interface integer'])\n\n if 'stp' in opts:\n if opts['stp'] in _CONFIG_TRUE:\n config.update({'stp': 'on'})\n elif opts['stp'] in _CONFIG_FALSE:\n config.update({'stp': 'off'})\n else:\n _raise_error_iface(iface, 'stp', _CONFIG_TRUE + _CONFIG_FALSE)\n\n if 'waitport' in opts:\n if isinstance(opts['waitport'], int):\n config.update({'waitport': opts['waitport']})\n else:\n values = opts['waitport'].split()\n waitport_time = values.pop(0)\n if waitport_time.isdigit() and values:\n config.update({\n 'waitport': '{0} {1}'.format(\n waitport_time, ' '.join(values)\n )\n })\n else:\n _raise_error_iface(iface, opt, ['integer [interfaces]'])\n\n return config\n"
] |
# -*- coding: utf-8 -*-
'''
The networking module for Debian-based distros
References:
* http://www.debian.org/doc/manuals/debian-reference/ch05.en.html
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import functools
import logging
import os.path
import os
import re
import time
# Import third party libs
import jinja2
import jinja2.exceptions
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error,no-name-in-module
# Import salt libs
import salt.utils.dns
import salt.utils.files
import salt.utils.odict
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.validate.net
# Set up logging
log = logging.getLogger(__name__)
# Set up template environment
JINJA = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'debian_ip')
)
)
# Define the module's virtual name
__virtualname__ = 'ip'
def __virtual__():
'''
Confine this module to Debian-based distros
'''
if __grains__['os_family'] == 'Debian':
return __virtualname__
return (False, 'The debian_ip module could not be loaded: '
'unsupported OS family')
_ETHTOOL_CONFIG_OPTS = {
'speed': 'link-speed',
'duplex': 'link-duplex',
'autoneg': 'ethernet-autoneg',
'ethernet-port': 'ethernet-port',
'wol': 'ethernet-wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'rx': 'offload-rx',
'tx': 'offload-tx',
'sg': 'offload-sg',
'tso': 'offload-tso',
'ufo': 'offload-ufo',
'gso': 'offload-gso',
'gro': 'offload-gro',
'lro': 'offload-lro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_REV_ETHTOOL_CONFIG_OPTS = {
'link-speed': 'speed',
'link-duplex': 'duplex',
'ethernet-autoneg': 'autoneg',
'ethernet-port': 'ethernet-port',
'ethernet-wol': 'wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'offload-rx': 'rx',
'offload-tx': 'tx',
'offload-sg': 'sg',
'offload-tso': 'tso',
'offload-ufo': 'ufo',
'offload-gso': 'gso',
'offload-lro': 'lro',
'offload-gro': 'gro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_DEB_CONFIG_PPPOE_OPTS = {
'user': 'user',
'password': 'password',
'provider': 'provider',
'pppoe_iface': 'pppoe_iface',
'noipdefault': 'noipdefault',
'usepeerdns': 'usepeerdns',
'defaultroute': 'defaultroute',
'holdoff': 'holdoff',
'maxfail': 'maxfail',
'hide-password': 'hide-password',
'lcp-echo-interval': 'lcp-echo-interval',
'lcp-echo-failure': 'lcp-echo-failure',
'connect': 'connect',
'noauth': 'noauth',
'persist': 'persist',
'mtu': 'mtu',
'noaccomp': 'noaccomp',
'linkname': 'linkname',
}
_DEB_ROUTES_FILE = '/etc/network/routes'
_DEB_NETWORK_FILE = '/etc/network/interfaces'
_DEB_NETWORK_DIR = '/etc/network/interfaces.d/'
_DEB_NETWORK_UP_DIR = '/etc/network/if-up.d/'
_DEB_NETWORK_DOWN_DIR = '/etc/network/if-down.d/'
_DEB_NETWORK_CONF_FILES = '/etc/modprobe.d/'
_DEB_NETWORKING_FILE = '/etc/default/networking'
_DEB_HOSTNAME_FILE = '/etc/hostname'
_DEB_RESOLV_FILE = '/etc/resolv.conf'
_DEB_PPP_DIR = '/etc/ppp/peers/'
_CONFIG_TRUE = ['yes', 'on', 'true', '1', True]
_CONFIG_FALSE = ['no', 'off', 'false', '0', False]
_IFACE_TYPES = [
'eth', 'bond', 'alias', 'clone',
'ipsec', 'dialup', 'bridge', 'slave',
'vlan', 'pppoe', 'source',
]
def _error_msg_iface(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, '|'.join(str(e) for e in expected))
def _error_msg_routes(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, expected)
def _log_default_iface(iface, opt, value):
log.info(
'Using default option -- Interface: %s Option: %s Value: %s',
iface, opt, value
)
def _error_msg_network(option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]'
return msg.format(option, '|'.join(str(e) for e in expected))
def _log_default_network(opt, value):
log.info('Using existing setting -- Setting: %s Value: %s', opt, value)
def _raise_error_iface(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_iface(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_network(option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_network(option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_routes(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_routes(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _read_file(path):
'''
Reads and returns the contents of a text file
'''
try:
with salt.utils.files.flopen(path, 'rb') as contents:
return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]
except (OSError, IOError):
return ''
def _parse_resolve():
'''
Parse /etc/resolv.conf
'''
return salt.utils.dns.parse_resolv(_DEB_RESOLV_FILE)
def _parse_domainname():
'''
Parse /etc/resolv.conf and return domainname
'''
return _parse_resolve().get('domain', '')
def _parse_searchdomain():
'''
Parse /etc/resolv.conf and return searchdomain
'''
return _parse_resolve().get('search', '')
def _parse_hostname():
'''
Parse /etc/hostname and return hostname
'''
contents = _read_file(_DEB_HOSTNAME_FILE)
if contents:
return contents[0].split('\n')[0]
else:
return ''
def _parse_current_network_settings():
'''
Parse /etc/default/networking and return current configuration
'''
opts = salt.utils.odict.OrderedDict()
opts['networking'] = ''
if os.path.isfile(_DEB_NETWORKING_FILE):
with salt.utils.files.fopen(_DEB_NETWORKING_FILE) as contents:
for line in contents:
salt.utils.stringutils.to_unicode(line)
if line.startswith('#'):
continue
elif line.startswith('CONFIGURE_INTERFACES'):
opts['networking'] = line.split('=', 1)[1].strip()
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
opts['hostname'] = hostname
opts['domainname'] = domainname
opts['searchdomain'] = searchdomain
return opts
# def __validator_func(value):
# return (valid: True/False, (transformed) value, error message)
def __ipv4_quad(value):
'''validate an IPv4 address'''
return (salt.utils.validate.net.ipv4_addr(value), value,
'dotted IPv4 address')
def __ipv6(value):
'''validate an IPv6 address'''
return (salt.utils.validate.net.ipv6_addr(value), value,
'IPv6 address')
def __mac(value):
'''validate a mac address'''
return (salt.utils.validate.net.mac(value), value,
'MAC address')
def __anything(value):
return (True, value, None)
def __int(value):
'''validate an integer'''
valid, _value = False, value
try:
_value = int(value)
valid = True
except ValueError:
pass
return (valid, _value, 'integer')
def __float(value):
'''validate a float'''
valid, _value = False, value
try:
_value = float(value)
valid = True
except ValueError:
pass
return (valid, _value, 'float')
def __ipv4_netmask(value):
'''validate an IPv4 dotted quad or integer CIDR netmask'''
valid, errmsg = False, 'dotted quad or integer CIDR (0->32)'
valid, value, _ = __int(value)
if not (valid and 0 <= value <= 32):
valid = salt.utils.validate.net.netmask(value)
return (valid, value, errmsg)
def __ipv6_netmask(value):
'''validate an IPv6 integer netmask'''
valid, errmsg = False, 'IPv6 netmask (0->128)'
valid, value, _ = __int(value)
valid = (valid and 0 <= value <= 128)
return (valid, value, errmsg)
def __within2(value, within=None, errmsg=None, dtype=None):
'''validate that a value is in ``within`` and optionally a ``dtype``'''
valid, _value = False, value
if dtype:
try:
_value = dtype(value) # TODO: this is a bit loose when dtype is a class
valid = _value in within
except ValueError:
pass
else:
valid = _value in within
if errmsg is None:
if dtype:
typename = getattr(dtype, '__name__',
hasattr(dtype, '__class__')
and getattr(dtype.__class__, 'name', dtype))
errmsg = '{0} within \'{1}\''.format(typename, within)
else:
errmsg = 'within \'{0}\''.format(within)
return (valid, _value, errmsg)
def __within(within=None, errmsg=None, dtype=None):
return functools.partial(__within2, within=within,
errmsg=errmsg, dtype=dtype)
def __space_delimited_list(value):
'''validate that a value contains one or more space-delimited values'''
if isinstance(value, six.string_types):
value = value.strip().split()
if hasattr(value, '__iter__') and value != []:
return (True, value, 'space-delimited string')
else:
return (False, value, '{0} is not a valid space-delimited value.\n'.format(value))
SALT_ATTR_TO_DEBIAN_ATTR_MAP = {
'dns': 'dns-nameservers',
'search': 'dns-search',
'hwaddr': 'hwaddress', # TODO: this limits bootp functionality
'ipaddr': 'address',
'ipaddrs': 'addresses',
}
DEBIAN_ATTR_TO_SALT_ATTR_MAP = dict(
(v, k) for (k, v) in six.iteritems(SALT_ATTR_TO_DEBIAN_ATTR_MAP))
# TODO
DEBIAN_ATTR_TO_SALT_ATTR_MAP['address'] = 'address'
DEBIAN_ATTR_TO_SALT_ATTR_MAP['hwaddress'] = 'hwaddress'
IPV4_VALID_PROTO = ['bootp', 'dhcp', 'static', 'manual', 'loopback', 'ppp']
IPV4_ATTR_MAP = {
'proto': __within(IPV4_VALID_PROTO, dtype=six.text_type),
# ipv4 static & manual
'address': __ipv4_quad,
'addresses': __anything,
'netmask': __ipv4_netmask,
'broadcast': __ipv4_quad,
'metric': __int,
'gateway': __ipv4_quad, # supports a colon-delimited list
'pointopoint': __ipv4_quad,
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'link', 'host'], dtype=six.text_type),
# dhcp
'hostname': __anything,
'leasehours': __int,
'leasetime': __int,
'vendor': __anything,
'client': __anything,
# bootp
'bootfile': __anything,
'server': __ipv4_quad,
'hwaddr': __mac,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'dstaddr': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# bond
'slaves': __anything,
# ppp
'provider': __anything,
'unit': __int,
'options': __anything,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
#
'network': __anything, # i don't know what this is
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
IPV6_VALID_PROTO = ['auto', 'loopback', 'static', 'manual',
'dhcp', 'v4tunnel', '6to4']
IPV6_ATTR_MAP = {
'proto': __within(IPV6_VALID_PROTO),
# ipv6 static & manual
'address': __ipv6,
'addresses': __anything,
'netmask': __ipv6_netmask,
'broadcast': __ipv6,
'gateway': __ipv6, # supports a colon-delimited list
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'site', 'link', 'host'], dtype=six.text_type),
# inet6 auto
'privext': __within([0, 1, 2], dtype=int),
'dhcp': __within([0, 1], dtype=int),
# inet6 static & manual & dhcp
'media': __anything,
'accept_ra': __within([0, 1], dtype=int),
'autoconf': __within([0, 1], dtype=int),
'preferred-lifetime': __int,
'dad-attempts': __int, # 0 to disable
'dad-interval': __float,
# bond
'slaves': __anything,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
WIRELESS_ATTR_MAP = {
'wireless-essid': __anything,
'wireless-mode': __anything, # TODO
'wpa-ap-scan': __within([0, 1, 2], dtype=int), # TODO
'wpa-conf': __anything,
'wpa-driver': __anything,
'wpa-group': __anything,
'wpa-key-mgmt': __anything,
'wpa-pairwise': __anything,
'wpa-psk': __anything,
'wpa-proto': __anything, # partial(__within,
'wpa-roam': __anything,
'wpa-ssid': __anything, # TODO
}
ATTRMAPS = {
'inet': [IPV4_ATTR_MAP, WIRELESS_ATTR_MAP],
'inet6': [IPV6_ATTR_MAP, WIRELESS_ATTR_MAP]
}
def _validate_interface_option(attr, value, addrfam='inet'):
'''lookup the validation function for a [addrfam][attr] and
return the results
:param attr: attribute name
:param value: raw setting value
:param addrfam: address family (inet, inet6,
'''
valid, _value, errmsg = False, value, 'Unknown validator'
attrmaps = ATTRMAPS.get(addrfam, [])
for attrmap in attrmaps:
if attr in attrmap:
validate_func = attrmap[attr]
(valid, _value, errmsg) = validate_func(value)
break
return (valid, _value, errmsg)
def _attrmaps_contain_attr(attr):
return (
attr in WIRELESS_ATTR_MAP or
attr in IPV4_ATTR_MAP or
attr in IPV6_ATTR_MAP)
def _parse_interfaces(interface_files=None):
'''
Parse /etc/network/interfaces and return current configured interfaces
'''
if interface_files is None:
interface_files = []
# Add this later.
if os.path.exists(_DEB_NETWORK_DIR):
interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]
if os.path.isfile(_DEB_NETWORK_FILE):
interface_files.insert(0, _DEB_NETWORK_FILE)
adapters = salt.utils.odict.OrderedDict()
method = -1
for interface_file in interface_files:
with salt.utils.files.fopen(interface_file) as interfaces:
# This ensures iface_dict exists, but does not ensure we're not reading a new interface.
iface_dict = {}
for line in interfaces:
line = salt.utils.stringutils.to_unicode(line)
# Identify the clauses by the first word of each line.
# Go to the next line if the current line is a comment
# or all spaces.
if line.lstrip().startswith('#') or line.isspace():
continue
# Parse the iface clause
if line.startswith('iface'):
sline = line.split()
if len(sline) != 4:
msg = 'Interface file malformed: {0}.'
msg = msg.format(sline)
log.error(msg)
raise AttributeError(msg)
iface_name = sline[1]
addrfam = sline[2]
method = sline[3]
# Create item in dict, if not already there
if iface_name not in adapters:
adapters[iface_name] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters[iface_name]:
adapters[iface_name]['data'] = salt.utils.odict.OrderedDict()
if addrfam not in adapters[iface_name]['data']:
adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict()
iface_dict = adapters[iface_name]['data'][addrfam]
iface_dict['addrfam'] = addrfam
iface_dict['proto'] = method
iface_dict['filename'] = interface_file
# Parse the detail clauses.
elif line[0].isspace():
sline = line.split()
# conf file attr: dns-nameservers
# salt states.network attr: dns
attr, valuestr = line.rstrip().split(None, 1)
if _attrmaps_contain_attr(attr):
if '-' in attr:
attrname = attr.replace('-', '_')
else:
attrname = attr
(valid, value, errmsg) = _validate_interface_option(
attr, valuestr, addrfam)
if attrname == 'address' and 'address' in iface_dict:
if 'addresses' not in iface_dict:
iface_dict['addresses'] = []
iface_dict['addresses'].append(value)
else:
iface_dict[attrname] = value
elif attr in _REV_ETHTOOL_CONFIG_OPTS:
if 'ethtool' not in iface_dict:
iface_dict['ethtool'] = salt.utils.odict.OrderedDict()
iface_dict['ethtool'][attr] = valuestr
elif attr.startswith('bond'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bonding' not in iface_dict:
iface_dict['bonding'] = salt.utils.odict.OrderedDict()
iface_dict['bonding'][opt] = valuestr
elif attr.startswith('bridge'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bridging' not in iface_dict:
iface_dict['bridging'] = salt.utils.odict.OrderedDict()
iface_dict['bridging'][opt] = valuestr
elif attr in ['up', 'pre-up', 'post-up',
'down', 'pre-down', 'post-down']:
cmd = valuestr
cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr))
if cmd_key not in iface_dict:
iface_dict[cmd_key] = []
iface_dict[cmd_key].append(cmd)
elif line.startswith('auto'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['enabled'] = True
elif line.startswith('allow-hotplug'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['hotplug'] = True
elif line.startswith('source'):
if 'source' not in adapters:
adapters['source'] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters['source']:
adapters['source']['data'] = salt.utils.odict.OrderedDict()
adapters['source']['data']['sources'] = []
adapters['source']['data']['sources'].append(line.split()[1])
# Return a sorted list of the keys for bond, bridge and ethtool options to
# ensure a consistent order
for iface_name in adapters:
if iface_name == 'source':
continue
if 'data' not in adapters[iface_name]:
msg = 'Interface file malformed for interface: {0}.'.format(iface_name)
log.error(msg)
adapters.pop(iface_name)
continue
for opt in ['ethtool', 'bonding', 'bridging']:
for inet in ['inet', 'inet6']:
if inet in adapters[iface_name]['data']:
if opt in adapters[iface_name]['data'][inet]:
opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys())
adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys
return adapters
def _parse_ethtool_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
if 'autoneg' in opts:
if opts['autoneg'] in _CONFIG_TRUE:
config.update({'autoneg': 'on'})
elif opts['autoneg'] in _CONFIG_FALSE:
config.update({'autoneg': 'off'})
else:
_raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE)
if 'duplex' in opts:
valid = ['full', 'half']
if opts['duplex'] in valid:
config.update({'duplex': opts['duplex']})
else:
_raise_error_iface(iface, 'duplex', valid)
if 'speed' in opts:
valid = ['10', '100', '1000', '10000']
if six.text_type(opts['speed']) in valid:
config.update({'speed': opts['speed']})
else:
_raise_error_iface(iface, opts['speed'], valid)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'on'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'off'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_ethtool_pppoe_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
for opt in _DEB_CONFIG_PPPOE_OPTS:
if opt in opts:
config[opt] = opts[opt]
if 'provider' in opts and not opts['provider']:
_raise_error_iface(iface, 'provider', _CONFIG_TRUE + _CONFIG_FALSE)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('noipdefault', 'usepeerdns', 'defaultroute', 'hide-password', 'noauth', 'persist', 'noaccomp'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'True'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'False'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_settings_bond(opts, iface):
'''
Filters given options and outputs valid settings for requested
operation. If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond_def = {
# 803.ad aggregation selection logic
# 0 for stable (default)
# 1 for bandwidth
# 2 for count
'ad_select': '0',
# Max number of transmit queues (default = 16)
'tx_queues': '16',
# Link monitoring in milliseconds. Most NICs support this
'miimon': '100',
# ARP interval in milliseconds
'arp_interval': '250',
# Delay before considering link down in milliseconds (miimon * 2)
'downdelay': '200',
# lacp_rate 0: Slow - every 30 seconds
# lacp_rate 1: Fast - every 1 second
'lacp_rate': '0',
# Max bonds for this driver
'max_bonds': '1',
# Specifies the time, in milliseconds, to wait before
# enabling a slave after a link recovery has been
# detected. Only used with miimon.
'updelay': '0',
# Used with miimon.
# On: driver sends mii
# Off: ethtool sends mii
'use_carrier': 'on',
# Default. Don't change unless you know what you are doing.
'xmit_hash_policy': 'layer2',
}
if opts['mode'] in ['balance-rr', '0']:
log.info('Device: %s Bonding Mode: load balancing (round-robin)', iface)
return _parse_settings_bond_0(opts, iface, bond_def)
elif opts['mode'] in ['active-backup', '1']:
log.info('Device: %s Bonding Mode: fault-tolerance (active-backup)', iface)
return _parse_settings_bond_1(opts, iface, bond_def)
elif opts['mode'] in ['balance-xor', '2']:
log.info('Device: %s Bonding Mode: load balancing (xor)', iface)
return _parse_settings_bond_2(opts, iface, bond_def)
elif opts['mode'] in ['broadcast', '3']:
log.info('Device: %s Bonding Mode: fault-tolerance (broadcast)', iface)
return _parse_settings_bond_3(opts, iface, bond_def)
elif opts['mode'] in ['802.3ad', '4']:
log.info('Device: %s Bonding Mode: IEEE 802.3ad Dynamic link '
'aggregation', iface)
return _parse_settings_bond_4(opts, iface, bond_def)
elif opts['mode'] in ['balance-tlb', '5']:
log.info('Device: %s Bonding Mode: transmit load balancing', iface)
return _parse_settings_bond_5(opts, iface, bond_def)
elif opts['mode'] in ['balance-alb', '6']:
log.info('Device: %s Bonding Mode: adaptive load balancing', iface)
return _parse_settings_bond_6(opts, iface, bond_def)
else:
valid = [
'0', '1', '2', '3', '4', '5', '6',
'balance-rr', 'active-backup', 'balance-xor',
'broadcast', '802.3ad', 'balance-tlb', 'balance-alb'
]
_raise_error_iface(iface, 'mode', valid)
def _parse_settings_bond_0(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond0.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '0'}
# ARP targets in n.n.n.n form
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
return bond
def _parse_settings_bond_1(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '1'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
if not (__grains__['os'] == "Ubuntu" and __grains__['osrelease_info'][0] >= 16):
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_2(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond2.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '2'}
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_3(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond3.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '3'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_4(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond4.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '4'}
for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']:
if binding in opts:
if binding == 'lacp_rate':
if opts[binding] == 'fast':
opts.update({binding: '1'})
if opts[binding] == 'slow':
opts.update({binding: '0'})
valid = ['fast', '1', 'slow', '0']
else:
valid = ['integer']
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, valid)
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_5(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond5.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '5'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_settings_bond_6(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond6.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '6'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_bridge_opts(opts, iface):
'''
Filters given options and outputs valid settings for BRIDGING_OPTS
If an option has a value that is not expected, this
function will log the Interface, Setting and what was expected.
'''
config = {}
if 'ports' in opts:
if isinstance(opts['ports'], list):
opts['ports'] = ' '.join(opts['ports'])
config.update({'ports': opts['ports']})
for opt in ['ageing', 'fd', 'gcint', 'hello', 'maxage']:
if opt in opts:
try:
float(opts[opt])
config.update({opt: opts[opt]})
except ValueError:
_raise_error_iface(iface, opt, ['float'])
for opt in ['bridgeprio', 'maxwait']:
if opt in opts:
if isinstance(opts[opt], int):
config.update({opt: opts[opt]})
else:
_raise_error_iface(iface, opt, ['integer'])
if 'hw' in opts:
# match 12 hex digits with either : or - as separators between pairs
if re.match('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$',
opts['hw'].lower()):
config.update({'hw': opts['hw']})
else:
_raise_error_iface(iface, 'hw', ['valid MAC address'])
for opt in ['pathcost', 'portprio']:
if opt in opts:
try:
port, cost_or_prio = opts[opt].split()
int(cost_or_prio)
config.update({opt: '{0} {1}'.format(port, cost_or_prio)})
except ValueError:
_raise_error_iface(iface, opt, ['interface integer'])
if 'stp' in opts:
if opts['stp'] in _CONFIG_TRUE:
config.update({'stp': 'on'})
elif opts['stp'] in _CONFIG_FALSE:
config.update({'stp': 'off'})
else:
_raise_error_iface(iface, 'stp', _CONFIG_TRUE + _CONFIG_FALSE)
if 'waitport' in opts:
if isinstance(opts['waitport'], int):
config.update({'waitport': opts['waitport']})
else:
values = opts['waitport'].split()
waitport_time = values.pop(0)
if waitport_time.isdigit() and values:
config.update({
'waitport': '{0} {1}'.format(
waitport_time, ' '.join(values)
)
})
else:
_raise_error_iface(iface, opt, ['integer [interfaces]'])
return config
def _parse_settings_source(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['sources'] = [opts['source']]
return adapters
def _parse_network_settings(opts, current):
'''
Filters given options and outputs valid settings for
the global network settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
current = dict((k.lower(), v) for (k, v) in six.iteritems(current))
result = {}
valid = _CONFIG_TRUE + _CONFIG_FALSE
if 'enabled' not in opts:
try:
opts['networking'] = current['networking']
_log_default_network('networking', current['networking'])
except ValueError:
_raise_error_network('networking', valid)
else:
opts['networking'] = opts['enabled']
if opts['networking'] in valid:
if opts['networking'] in _CONFIG_TRUE:
result['networking'] = 'yes'
elif opts['networking'] in _CONFIG_FALSE:
result['networking'] = 'no'
else:
_raise_error_network('networking', valid)
if 'hostname' not in opts:
try:
opts['hostname'] = current['hostname']
_log_default_network('hostname', current['hostname'])
except ValueError:
_raise_error_network('hostname', ['server1.example.com'])
if opts['hostname']:
result['hostname'] = opts['hostname']
else:
_raise_error_network('hostname', ['server1.example.com'])
if 'search' in opts:
result['search'] = opts['search']
return result
def _parse_routes(iface, opts):
'''
Filters given options and outputs valid settings for
the route settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
result = {}
if 'routes' not in opts:
_raise_error_routes(iface, 'routes', 'List of routes')
for opt in opts:
result[opt] = opts[opt]
return result
def _write_file(iface, data, folder, pattern):
'''
Writes a file to disk
'''
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
return filename
def _write_file_routes(iface, data, folder, pattern):
'''
Writes a file to disk
'''
# ifup / ifdown is executing given folder via run-parts.
# according to run-parts man-page, only filenames with this pattern are
# executed: (^[a-zA-Z0-9_-]+$)
# In order to make the routes file work for vlan interfaces
# (default would have been in example /etc/network/if-up.d/route-bond0.12)
# these dots in the iface name need to be replaced by underscores, so it
# can be executed by run-parts
iface = iface.replace('.', '_')
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
__salt__['file.set_mode'](filename, '0755')
return filename
def _write_file_network(data, filename, create=False):
'''
Writes a file to disk
If file does not exist, only create if create
argument is True
'''
if not os.path.exists(filename) and not create:
msg = '{0} cannot be written. {0} does not exist\
and create is set to False'
msg = msg.format(filename)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
def _read_temp(data):
'''
Return what would be written to disk
'''
tout = StringIO()
tout.write(data)
tout.seek(0)
output = tout.readlines()
tout.close()
return output
def _read_temp_ifaces(iface, data):
'''
Return what would be written to disk for interfaces
'''
try:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': data})
# Return as an array so the difflib works
return [item + '\n' for item in ifcfg.split('\n')]
def _write_file_ifaces(iface, data, **settings):
'''
Writes a file to disk
'''
try:
eth_template = JINJA.get_template('debian_eth.jinja')
source_template = JINJA.get_template('debian_source.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
# Read /etc/network/interfaces into a dict
adapters = _parse_interfaces()
# Apply supplied settings over on-disk settings
adapters[iface] = data
ifcfg = ''
for adapter in adapters:
if 'type' in adapters[adapter] and adapters[adapter]['type'] == 'source':
tmp = source_template.render({'name': adapter, 'data': adapters[adapter]})
else:
tmp = eth_template.render({'name': adapter, 'data': adapters[adapter]})
ifcfg = ifcfg + tmp
if adapter == iface:
saved_ifcfg = tmp
_SEPARATE_FILE = False
if 'filename' in settings:
if not settings['filename'].startswith('/'):
filename = '{0}/{1}'.format(_DEB_NETWORK_DIR, settings['filename'])
else:
filename = settings['filename']
_SEPARATE_FILE = True
else:
if 'filename' in adapters[adapter]['data']:
filename = adapters[adapter]['data']
else:
filename = _DEB_NETWORK_FILE
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
if _SEPARATE_FILE:
fout.write(salt.utils.stringutils.to_str(saved_ifcfg))
else:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return saved_ifcfg.split('\n')
def _write_file_ppp_ifaces(iface, data):
'''
Writes a file to disk
'''
try:
template = JINJA.get_template('debian_ppp_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_ppp_eth.jinja')
return ''
adapters = _parse_interfaces()
adapters[iface] = data
ifcfg = ''
tmp = template.render({'data': adapters[iface]})
ifcfg = tmp + ifcfg
filename = _DEB_PPP_DIR + '/' + adapters[iface]['data']['inet']['provider']
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.fopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return filename
def build_bond(iface, **settings):
'''
Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb
'''
deb_major = __grains__['osrelease'][:1]
opts = _parse_settings_bond(settings, iface)
try:
template = JINJA.get_template('conf.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template conf.jinja')
return ''
data = template.render({'name': iface, 'bonding': opts})
if 'test' in settings and settings['test']:
return _read_temp(data)
_write_file(iface, data, _DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
if deb_major == '5':
for line_type in ('alias', 'options'):
cmd = ['sed', '-i', '-e', r'/^{0}\s{1}.*/d'.format(line_type, iface),
'/etc/modprobe.conf']
__salt__['cmd.run'](cmd, python_shell=False)
__salt__['file.append']('/etc/modprobe.conf', path)
# Load kernel module
__salt__['kmod.load']('bonding')
# install ifenslave-2.6
__salt__['pkg.install']('ifenslave-2.6')
return _read_file(path)
def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'vlan':
settings['vlan'] = 'yes'
__salt__['pkg.install']('vlan')
elif iface_type == 'pppoe':
settings['pppoe'] = 'yes'
if not __salt__['pkg.version']('ppp'):
inst = __salt__['pkg.install']('ppp')
elif iface_type == 'bond':
if 'slaves' not in settings:
msg = 'slaves is a required setting for bond interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'bridge':
if 'ports' not in settings:
msg = (
'ports is a required setting for bridge interfaces on Debian '
'or Ubuntu based systems'
)
log.error(msg)
raise AttributeError(msg)
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'pppoe']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
if iface_type in ['source']:
opts = _parse_settings_source(settings, iface_type, enabled, iface)
if 'test' in settings and settings['test']:
return _read_temp_ifaces(iface, opts[iface])
ifcfg = _write_file_ifaces(iface, opts[iface], **settings)
if iface_type == 'pppoe':
_write_file_ppp_ifaces(iface, opts[iface])
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg]
def build_routes(iface, **settings):
'''
Add route scripts for a network interface using up commands.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
'''
opts = _parse_routes(iface, settings)
try:
template = JINJA.get_template('route_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template route_eth.jinja')
return ''
add_routecfg = template.render(route_type='add',
routes=opts['routes'],
iface=iface)
del_routecfg = template.render(route_type='del',
routes=opts['routes'],
iface=iface)
if 'test' in settings and settings['test']:
return _read_temp(add_routecfg + del_routecfg)
filename = _write_file_routes(iface,
add_routecfg,
_DEB_NETWORK_UP_DIR,
'route-{0}')
results = _read_file(filename)
filename = _write_file_routes(iface,
del_routecfg,
_DEB_NETWORK_DOWN_DIR,
'route-{0}')
results += _read_file(filename)
return results
def down(iface, iface_type):
'''
Shutdown a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.down eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought down.
if iface_type not in ['slave', 'source']:
return __salt__['cmd.run'](['ifdown', iface])
return None
def get_bond(iface):
'''
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
'''
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
return _read_file(path)
def get_interface(iface):
'''
Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
adapters = _parse_interfaces()
if iface in adapters:
try:
if iface == 'source':
template = JINJA.get_template('debian_source.jinja')
else:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': adapters[iface]})
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg.split('\n')]
else:
return []
def up(iface, iface_type): # pylint: disable=C0103
'''
Start up a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.up eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought up.
if iface_type not in ('slave', 'source'):
return __salt__['cmd.run'](['ifup', iface])
return None
def get_network_settings():
'''
Return the contents of the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_network_settings
'''
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
settings = {}
if __salt__['service.available']('networking'):
if __salt__['service.status']('networking'):
settings['networking'] = "yes"
else:
settings['networking'] = "no"
else:
settings['networking'] = "no"
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
settings['hostname'] = hostname
settings['domainname'] = domainname
settings['searchdomain'] = searchdomain
else:
settings = _parse_current_network_settings()
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(settings)
return _read_temp(network)
def get_routes(iface):
'''
Return the routes for the interface
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0
'''
filename = os.path.join(_DEB_NETWORK_UP_DIR, 'route-{0}'.format(iface))
results = _read_file(filename)
filename = os.path.join(_DEB_NETWORK_DOWN_DIR, 'route-{0}'.format(iface))
results += _read_file(filename)
return results
def apply_network_settings(**settings):
'''
Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings
'''
if 'require_reboot' not in settings:
settings['require_reboot'] = False
if 'apply_hostname' not in settings:
settings['apply_hostname'] = False
hostname_res = True
if settings['apply_hostname'] in _CONFIG_TRUE:
if 'hostname' in settings:
hostname_res = __salt__['network.mod_hostname'](settings['hostname'])
else:
log.warning(
'The network state sls is trying to apply hostname '
'changes but no hostname is defined.'
)
hostname_res = False
res = True
if settings['require_reboot'] in _CONFIG_TRUE:
log.warning(
'The network state sls is requiring a reboot of the system to '
'properly apply network configuration.'
)
res = True
else:
stop = __salt__['service.stop']('networking')
time.sleep(2)
res = stop and __salt__['service.start']('networking')
return hostname_res and res
def build_network_settings(**settings):
'''
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
'''
changes = []
# Read current configuration and store default values
current_network_settings = _parse_current_network_settings()
# Build settings
opts = _parse_network_settings(settings, current_network_settings)
# Ubuntu has moved away from /etc/default/networking
# beginning with the 12.04 release so we disable or enable
# the networking related services on boot
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
if opts['networking'] == 'yes':
service_cmd = 'service.enable'
else:
service_cmd = 'service.disable'
if __salt__['service.available']('NetworkManager'):
__salt__[service_cmd]('NetworkManager')
if __salt__['service.available']('networking'):
__salt__[service_cmd]('networking')
else:
try:
template = JINJA.get_template('network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template network.jinja')
return ''
network = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(network)
# Write settings
_write_file_network(network, _DEB_NETWORKING_FILE, True)
# Get hostname and domain from opts
sline = opts['hostname'].split('.', 1)
opts['hostname'] = sline[0]
current_domainname = current_network_settings['domainname']
current_searchdomain = current_network_settings['searchdomain']
new_domain = False
if len(sline) > 1:
new_domainname = sline[1]
if new_domainname != current_domainname:
domainname = new_domainname
opts['domainname'] = new_domainname
new_domain = True
else:
domainname = current_domainname
opts['domainname'] = domainname
else:
domainname = current_domainname
opts['domainname'] = domainname
new_search = False
if 'search' in opts:
new_searchdomain = opts['search']
if new_searchdomain != current_searchdomain:
searchdomain = new_searchdomain
opts['searchdomain'] = new_searchdomain
new_search = True
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
# If the domain changes, then we should write the resolv.conf file.
if new_domain or new_search:
# Look for existing domain line and update if necessary
resolve = _parse_resolve()
domain_prog = re.compile(r'domain\s+')
search_prog = re.compile(r'search\s+')
new_contents = []
for item in _read_file(_DEB_RESOLV_FILE):
if domain_prog.match(item):
item = 'domain {0}'.format(domainname)
elif search_prog.match(item):
item = 'search {0}'.format(searchdomain)
new_contents.append(item)
# A domain line didn't exist so we'll add one in
# with the new domainname
if 'domain' not in resolve:
new_contents.insert(0, 'domain {0}' . format(domainname))
# A search line didn't exist so we'll add one in
# with the new search domain
if 'search' not in resolve:
new_contents.insert('domain' in resolve, 'search {0}'.format(searchdomain))
new_resolv = '\n'.join(new_contents)
# Write /etc/resolv.conf
if not ('test' in settings and settings['test']):
_write_file_network(new_resolv, _DEB_RESOLV_FILE)
# used for returning the results back
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(opts)
changes.extend(_read_temp(network))
return changes
|
saltstack/salt
|
salt/modules/debian_ip.py
|
_parse_settings_source
|
python
|
def _parse_settings_source(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['sources'] = [opts['source']]
return adapters
|
Filters given options and outputs valid settings for a
network interface.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_ip.py#L1315-L1329
| null |
# -*- coding: utf-8 -*-
'''
The networking module for Debian-based distros
References:
* http://www.debian.org/doc/manuals/debian-reference/ch05.en.html
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import functools
import logging
import os.path
import os
import re
import time
# Import third party libs
import jinja2
import jinja2.exceptions
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error,no-name-in-module
# Import salt libs
import salt.utils.dns
import salt.utils.files
import salt.utils.odict
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.validate.net
# Set up logging
log = logging.getLogger(__name__)
# Set up template environment
JINJA = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'debian_ip')
)
)
# Define the module's virtual name
__virtualname__ = 'ip'
def __virtual__():
'''
Confine this module to Debian-based distros
'''
if __grains__['os_family'] == 'Debian':
return __virtualname__
return (False, 'The debian_ip module could not be loaded: '
'unsupported OS family')
_ETHTOOL_CONFIG_OPTS = {
'speed': 'link-speed',
'duplex': 'link-duplex',
'autoneg': 'ethernet-autoneg',
'ethernet-port': 'ethernet-port',
'wol': 'ethernet-wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'rx': 'offload-rx',
'tx': 'offload-tx',
'sg': 'offload-sg',
'tso': 'offload-tso',
'ufo': 'offload-ufo',
'gso': 'offload-gso',
'gro': 'offload-gro',
'lro': 'offload-lro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_REV_ETHTOOL_CONFIG_OPTS = {
'link-speed': 'speed',
'link-duplex': 'duplex',
'ethernet-autoneg': 'autoneg',
'ethernet-port': 'ethernet-port',
'ethernet-wol': 'wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'offload-rx': 'rx',
'offload-tx': 'tx',
'offload-sg': 'sg',
'offload-tso': 'tso',
'offload-ufo': 'ufo',
'offload-gso': 'gso',
'offload-lro': 'lro',
'offload-gro': 'gro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_DEB_CONFIG_PPPOE_OPTS = {
'user': 'user',
'password': 'password',
'provider': 'provider',
'pppoe_iface': 'pppoe_iface',
'noipdefault': 'noipdefault',
'usepeerdns': 'usepeerdns',
'defaultroute': 'defaultroute',
'holdoff': 'holdoff',
'maxfail': 'maxfail',
'hide-password': 'hide-password',
'lcp-echo-interval': 'lcp-echo-interval',
'lcp-echo-failure': 'lcp-echo-failure',
'connect': 'connect',
'noauth': 'noauth',
'persist': 'persist',
'mtu': 'mtu',
'noaccomp': 'noaccomp',
'linkname': 'linkname',
}
_DEB_ROUTES_FILE = '/etc/network/routes'
_DEB_NETWORK_FILE = '/etc/network/interfaces'
_DEB_NETWORK_DIR = '/etc/network/interfaces.d/'
_DEB_NETWORK_UP_DIR = '/etc/network/if-up.d/'
_DEB_NETWORK_DOWN_DIR = '/etc/network/if-down.d/'
_DEB_NETWORK_CONF_FILES = '/etc/modprobe.d/'
_DEB_NETWORKING_FILE = '/etc/default/networking'
_DEB_HOSTNAME_FILE = '/etc/hostname'
_DEB_RESOLV_FILE = '/etc/resolv.conf'
_DEB_PPP_DIR = '/etc/ppp/peers/'
_CONFIG_TRUE = ['yes', 'on', 'true', '1', True]
_CONFIG_FALSE = ['no', 'off', 'false', '0', False]
_IFACE_TYPES = [
'eth', 'bond', 'alias', 'clone',
'ipsec', 'dialup', 'bridge', 'slave',
'vlan', 'pppoe', 'source',
]
def _error_msg_iface(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, '|'.join(str(e) for e in expected))
def _error_msg_routes(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, expected)
def _log_default_iface(iface, opt, value):
log.info(
'Using default option -- Interface: %s Option: %s Value: %s',
iface, opt, value
)
def _error_msg_network(option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]'
return msg.format(option, '|'.join(str(e) for e in expected))
def _log_default_network(opt, value):
log.info('Using existing setting -- Setting: %s Value: %s', opt, value)
def _raise_error_iface(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_iface(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_network(option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_network(option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_routes(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_routes(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _read_file(path):
'''
Reads and returns the contents of a text file
'''
try:
with salt.utils.files.flopen(path, 'rb') as contents:
return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]
except (OSError, IOError):
return ''
def _parse_resolve():
'''
Parse /etc/resolv.conf
'''
return salt.utils.dns.parse_resolv(_DEB_RESOLV_FILE)
def _parse_domainname():
'''
Parse /etc/resolv.conf and return domainname
'''
return _parse_resolve().get('domain', '')
def _parse_searchdomain():
'''
Parse /etc/resolv.conf and return searchdomain
'''
return _parse_resolve().get('search', '')
def _parse_hostname():
'''
Parse /etc/hostname and return hostname
'''
contents = _read_file(_DEB_HOSTNAME_FILE)
if contents:
return contents[0].split('\n')[0]
else:
return ''
def _parse_current_network_settings():
'''
Parse /etc/default/networking and return current configuration
'''
opts = salt.utils.odict.OrderedDict()
opts['networking'] = ''
if os.path.isfile(_DEB_NETWORKING_FILE):
with salt.utils.files.fopen(_DEB_NETWORKING_FILE) as contents:
for line in contents:
salt.utils.stringutils.to_unicode(line)
if line.startswith('#'):
continue
elif line.startswith('CONFIGURE_INTERFACES'):
opts['networking'] = line.split('=', 1)[1].strip()
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
opts['hostname'] = hostname
opts['domainname'] = domainname
opts['searchdomain'] = searchdomain
return opts
# def __validator_func(value):
# return (valid: True/False, (transformed) value, error message)
def __ipv4_quad(value):
'''validate an IPv4 address'''
return (salt.utils.validate.net.ipv4_addr(value), value,
'dotted IPv4 address')
def __ipv6(value):
'''validate an IPv6 address'''
return (salt.utils.validate.net.ipv6_addr(value), value,
'IPv6 address')
def __mac(value):
'''validate a mac address'''
return (salt.utils.validate.net.mac(value), value,
'MAC address')
def __anything(value):
return (True, value, None)
def __int(value):
'''validate an integer'''
valid, _value = False, value
try:
_value = int(value)
valid = True
except ValueError:
pass
return (valid, _value, 'integer')
def __float(value):
'''validate a float'''
valid, _value = False, value
try:
_value = float(value)
valid = True
except ValueError:
pass
return (valid, _value, 'float')
def __ipv4_netmask(value):
'''validate an IPv4 dotted quad or integer CIDR netmask'''
valid, errmsg = False, 'dotted quad or integer CIDR (0->32)'
valid, value, _ = __int(value)
if not (valid and 0 <= value <= 32):
valid = salt.utils.validate.net.netmask(value)
return (valid, value, errmsg)
def __ipv6_netmask(value):
'''validate an IPv6 integer netmask'''
valid, errmsg = False, 'IPv6 netmask (0->128)'
valid, value, _ = __int(value)
valid = (valid and 0 <= value <= 128)
return (valid, value, errmsg)
def __within2(value, within=None, errmsg=None, dtype=None):
'''validate that a value is in ``within`` and optionally a ``dtype``'''
valid, _value = False, value
if dtype:
try:
_value = dtype(value) # TODO: this is a bit loose when dtype is a class
valid = _value in within
except ValueError:
pass
else:
valid = _value in within
if errmsg is None:
if dtype:
typename = getattr(dtype, '__name__',
hasattr(dtype, '__class__')
and getattr(dtype.__class__, 'name', dtype))
errmsg = '{0} within \'{1}\''.format(typename, within)
else:
errmsg = 'within \'{0}\''.format(within)
return (valid, _value, errmsg)
def __within(within=None, errmsg=None, dtype=None):
return functools.partial(__within2, within=within,
errmsg=errmsg, dtype=dtype)
def __space_delimited_list(value):
'''validate that a value contains one or more space-delimited values'''
if isinstance(value, six.string_types):
value = value.strip().split()
if hasattr(value, '__iter__') and value != []:
return (True, value, 'space-delimited string')
else:
return (False, value, '{0} is not a valid space-delimited value.\n'.format(value))
SALT_ATTR_TO_DEBIAN_ATTR_MAP = {
'dns': 'dns-nameservers',
'search': 'dns-search',
'hwaddr': 'hwaddress', # TODO: this limits bootp functionality
'ipaddr': 'address',
'ipaddrs': 'addresses',
}
DEBIAN_ATTR_TO_SALT_ATTR_MAP = dict(
(v, k) for (k, v) in six.iteritems(SALT_ATTR_TO_DEBIAN_ATTR_MAP))
# TODO
DEBIAN_ATTR_TO_SALT_ATTR_MAP['address'] = 'address'
DEBIAN_ATTR_TO_SALT_ATTR_MAP['hwaddress'] = 'hwaddress'
IPV4_VALID_PROTO = ['bootp', 'dhcp', 'static', 'manual', 'loopback', 'ppp']
IPV4_ATTR_MAP = {
'proto': __within(IPV4_VALID_PROTO, dtype=six.text_type),
# ipv4 static & manual
'address': __ipv4_quad,
'addresses': __anything,
'netmask': __ipv4_netmask,
'broadcast': __ipv4_quad,
'metric': __int,
'gateway': __ipv4_quad, # supports a colon-delimited list
'pointopoint': __ipv4_quad,
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'link', 'host'], dtype=six.text_type),
# dhcp
'hostname': __anything,
'leasehours': __int,
'leasetime': __int,
'vendor': __anything,
'client': __anything,
# bootp
'bootfile': __anything,
'server': __ipv4_quad,
'hwaddr': __mac,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'dstaddr': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# bond
'slaves': __anything,
# ppp
'provider': __anything,
'unit': __int,
'options': __anything,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
#
'network': __anything, # i don't know what this is
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
IPV6_VALID_PROTO = ['auto', 'loopback', 'static', 'manual',
'dhcp', 'v4tunnel', '6to4']
IPV6_ATTR_MAP = {
'proto': __within(IPV6_VALID_PROTO),
# ipv6 static & manual
'address': __ipv6,
'addresses': __anything,
'netmask': __ipv6_netmask,
'broadcast': __ipv6,
'gateway': __ipv6, # supports a colon-delimited list
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'site', 'link', 'host'], dtype=six.text_type),
# inet6 auto
'privext': __within([0, 1, 2], dtype=int),
'dhcp': __within([0, 1], dtype=int),
# inet6 static & manual & dhcp
'media': __anything,
'accept_ra': __within([0, 1], dtype=int),
'autoconf': __within([0, 1], dtype=int),
'preferred-lifetime': __int,
'dad-attempts': __int, # 0 to disable
'dad-interval': __float,
# bond
'slaves': __anything,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
WIRELESS_ATTR_MAP = {
'wireless-essid': __anything,
'wireless-mode': __anything, # TODO
'wpa-ap-scan': __within([0, 1, 2], dtype=int), # TODO
'wpa-conf': __anything,
'wpa-driver': __anything,
'wpa-group': __anything,
'wpa-key-mgmt': __anything,
'wpa-pairwise': __anything,
'wpa-psk': __anything,
'wpa-proto': __anything, # partial(__within,
'wpa-roam': __anything,
'wpa-ssid': __anything, # TODO
}
ATTRMAPS = {
'inet': [IPV4_ATTR_MAP, WIRELESS_ATTR_MAP],
'inet6': [IPV6_ATTR_MAP, WIRELESS_ATTR_MAP]
}
def _validate_interface_option(attr, value, addrfam='inet'):
'''lookup the validation function for a [addrfam][attr] and
return the results
:param attr: attribute name
:param value: raw setting value
:param addrfam: address family (inet, inet6,
'''
valid, _value, errmsg = False, value, 'Unknown validator'
attrmaps = ATTRMAPS.get(addrfam, [])
for attrmap in attrmaps:
if attr in attrmap:
validate_func = attrmap[attr]
(valid, _value, errmsg) = validate_func(value)
break
return (valid, _value, errmsg)
def _attrmaps_contain_attr(attr):
return (
attr in WIRELESS_ATTR_MAP or
attr in IPV4_ATTR_MAP or
attr in IPV6_ATTR_MAP)
def _parse_interfaces(interface_files=None):
'''
Parse /etc/network/interfaces and return current configured interfaces
'''
if interface_files is None:
interface_files = []
# Add this later.
if os.path.exists(_DEB_NETWORK_DIR):
interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]
if os.path.isfile(_DEB_NETWORK_FILE):
interface_files.insert(0, _DEB_NETWORK_FILE)
adapters = salt.utils.odict.OrderedDict()
method = -1
for interface_file in interface_files:
with salt.utils.files.fopen(interface_file) as interfaces:
# This ensures iface_dict exists, but does not ensure we're not reading a new interface.
iface_dict = {}
for line in interfaces:
line = salt.utils.stringutils.to_unicode(line)
# Identify the clauses by the first word of each line.
# Go to the next line if the current line is a comment
# or all spaces.
if line.lstrip().startswith('#') or line.isspace():
continue
# Parse the iface clause
if line.startswith('iface'):
sline = line.split()
if len(sline) != 4:
msg = 'Interface file malformed: {0}.'
msg = msg.format(sline)
log.error(msg)
raise AttributeError(msg)
iface_name = sline[1]
addrfam = sline[2]
method = sline[3]
# Create item in dict, if not already there
if iface_name not in adapters:
adapters[iface_name] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters[iface_name]:
adapters[iface_name]['data'] = salt.utils.odict.OrderedDict()
if addrfam not in adapters[iface_name]['data']:
adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict()
iface_dict = adapters[iface_name]['data'][addrfam]
iface_dict['addrfam'] = addrfam
iface_dict['proto'] = method
iface_dict['filename'] = interface_file
# Parse the detail clauses.
elif line[0].isspace():
sline = line.split()
# conf file attr: dns-nameservers
# salt states.network attr: dns
attr, valuestr = line.rstrip().split(None, 1)
if _attrmaps_contain_attr(attr):
if '-' in attr:
attrname = attr.replace('-', '_')
else:
attrname = attr
(valid, value, errmsg) = _validate_interface_option(
attr, valuestr, addrfam)
if attrname == 'address' and 'address' in iface_dict:
if 'addresses' not in iface_dict:
iface_dict['addresses'] = []
iface_dict['addresses'].append(value)
else:
iface_dict[attrname] = value
elif attr in _REV_ETHTOOL_CONFIG_OPTS:
if 'ethtool' not in iface_dict:
iface_dict['ethtool'] = salt.utils.odict.OrderedDict()
iface_dict['ethtool'][attr] = valuestr
elif attr.startswith('bond'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bonding' not in iface_dict:
iface_dict['bonding'] = salt.utils.odict.OrderedDict()
iface_dict['bonding'][opt] = valuestr
elif attr.startswith('bridge'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bridging' not in iface_dict:
iface_dict['bridging'] = salt.utils.odict.OrderedDict()
iface_dict['bridging'][opt] = valuestr
elif attr in ['up', 'pre-up', 'post-up',
'down', 'pre-down', 'post-down']:
cmd = valuestr
cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr))
if cmd_key not in iface_dict:
iface_dict[cmd_key] = []
iface_dict[cmd_key].append(cmd)
elif line.startswith('auto'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['enabled'] = True
elif line.startswith('allow-hotplug'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['hotplug'] = True
elif line.startswith('source'):
if 'source' not in adapters:
adapters['source'] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters['source']:
adapters['source']['data'] = salt.utils.odict.OrderedDict()
adapters['source']['data']['sources'] = []
adapters['source']['data']['sources'].append(line.split()[1])
# Return a sorted list of the keys for bond, bridge and ethtool options to
# ensure a consistent order
for iface_name in adapters:
if iface_name == 'source':
continue
if 'data' not in adapters[iface_name]:
msg = 'Interface file malformed for interface: {0}.'.format(iface_name)
log.error(msg)
adapters.pop(iface_name)
continue
for opt in ['ethtool', 'bonding', 'bridging']:
for inet in ['inet', 'inet6']:
if inet in adapters[iface_name]['data']:
if opt in adapters[iface_name]['data'][inet]:
opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys())
adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys
return adapters
def _parse_ethtool_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
if 'autoneg' in opts:
if opts['autoneg'] in _CONFIG_TRUE:
config.update({'autoneg': 'on'})
elif opts['autoneg'] in _CONFIG_FALSE:
config.update({'autoneg': 'off'})
else:
_raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE)
if 'duplex' in opts:
valid = ['full', 'half']
if opts['duplex'] in valid:
config.update({'duplex': opts['duplex']})
else:
_raise_error_iface(iface, 'duplex', valid)
if 'speed' in opts:
valid = ['10', '100', '1000', '10000']
if six.text_type(opts['speed']) in valid:
config.update({'speed': opts['speed']})
else:
_raise_error_iface(iface, opts['speed'], valid)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'on'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'off'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_ethtool_pppoe_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
for opt in _DEB_CONFIG_PPPOE_OPTS:
if opt in opts:
config[opt] = opts[opt]
if 'provider' in opts and not opts['provider']:
_raise_error_iface(iface, 'provider', _CONFIG_TRUE + _CONFIG_FALSE)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('noipdefault', 'usepeerdns', 'defaultroute', 'hide-password', 'noauth', 'persist', 'noaccomp'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'True'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'False'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_settings_bond(opts, iface):
'''
Filters given options and outputs valid settings for requested
operation. If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond_def = {
# 803.ad aggregation selection logic
# 0 for stable (default)
# 1 for bandwidth
# 2 for count
'ad_select': '0',
# Max number of transmit queues (default = 16)
'tx_queues': '16',
# Link monitoring in milliseconds. Most NICs support this
'miimon': '100',
# ARP interval in milliseconds
'arp_interval': '250',
# Delay before considering link down in milliseconds (miimon * 2)
'downdelay': '200',
# lacp_rate 0: Slow - every 30 seconds
# lacp_rate 1: Fast - every 1 second
'lacp_rate': '0',
# Max bonds for this driver
'max_bonds': '1',
# Specifies the time, in milliseconds, to wait before
# enabling a slave after a link recovery has been
# detected. Only used with miimon.
'updelay': '0',
# Used with miimon.
# On: driver sends mii
# Off: ethtool sends mii
'use_carrier': 'on',
# Default. Don't change unless you know what you are doing.
'xmit_hash_policy': 'layer2',
}
if opts['mode'] in ['balance-rr', '0']:
log.info('Device: %s Bonding Mode: load balancing (round-robin)', iface)
return _parse_settings_bond_0(opts, iface, bond_def)
elif opts['mode'] in ['active-backup', '1']:
log.info('Device: %s Bonding Mode: fault-tolerance (active-backup)', iface)
return _parse_settings_bond_1(opts, iface, bond_def)
elif opts['mode'] in ['balance-xor', '2']:
log.info('Device: %s Bonding Mode: load balancing (xor)', iface)
return _parse_settings_bond_2(opts, iface, bond_def)
elif opts['mode'] in ['broadcast', '3']:
log.info('Device: %s Bonding Mode: fault-tolerance (broadcast)', iface)
return _parse_settings_bond_3(opts, iface, bond_def)
elif opts['mode'] in ['802.3ad', '4']:
log.info('Device: %s Bonding Mode: IEEE 802.3ad Dynamic link '
'aggregation', iface)
return _parse_settings_bond_4(opts, iface, bond_def)
elif opts['mode'] in ['balance-tlb', '5']:
log.info('Device: %s Bonding Mode: transmit load balancing', iface)
return _parse_settings_bond_5(opts, iface, bond_def)
elif opts['mode'] in ['balance-alb', '6']:
log.info('Device: %s Bonding Mode: adaptive load balancing', iface)
return _parse_settings_bond_6(opts, iface, bond_def)
else:
valid = [
'0', '1', '2', '3', '4', '5', '6',
'balance-rr', 'active-backup', 'balance-xor',
'broadcast', '802.3ad', 'balance-tlb', 'balance-alb'
]
_raise_error_iface(iface, 'mode', valid)
def _parse_settings_bond_0(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond0.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '0'}
# ARP targets in n.n.n.n form
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
return bond
def _parse_settings_bond_1(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '1'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
if not (__grains__['os'] == "Ubuntu" and __grains__['osrelease_info'][0] >= 16):
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_2(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond2.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '2'}
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_3(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond3.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '3'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_4(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond4.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '4'}
for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']:
if binding in opts:
if binding == 'lacp_rate':
if opts[binding] == 'fast':
opts.update({binding: '1'})
if opts[binding] == 'slow':
opts.update({binding: '0'})
valid = ['fast', '1', 'slow', '0']
else:
valid = ['integer']
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, valid)
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_5(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond5.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '5'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_settings_bond_6(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond6.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '6'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_bridge_opts(opts, iface):
'''
Filters given options and outputs valid settings for BRIDGING_OPTS
If an option has a value that is not expected, this
function will log the Interface, Setting and what was expected.
'''
config = {}
if 'ports' in opts:
if isinstance(opts['ports'], list):
opts['ports'] = ' '.join(opts['ports'])
config.update({'ports': opts['ports']})
for opt in ['ageing', 'fd', 'gcint', 'hello', 'maxage']:
if opt in opts:
try:
float(opts[opt])
config.update({opt: opts[opt]})
except ValueError:
_raise_error_iface(iface, opt, ['float'])
for opt in ['bridgeprio', 'maxwait']:
if opt in opts:
if isinstance(opts[opt], int):
config.update({opt: opts[opt]})
else:
_raise_error_iface(iface, opt, ['integer'])
if 'hw' in opts:
# match 12 hex digits with either : or - as separators between pairs
if re.match('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$',
opts['hw'].lower()):
config.update({'hw': opts['hw']})
else:
_raise_error_iface(iface, 'hw', ['valid MAC address'])
for opt in ['pathcost', 'portprio']:
if opt in opts:
try:
port, cost_or_prio = opts[opt].split()
int(cost_or_prio)
config.update({opt: '{0} {1}'.format(port, cost_or_prio)})
except ValueError:
_raise_error_iface(iface, opt, ['interface integer'])
if 'stp' in opts:
if opts['stp'] in _CONFIG_TRUE:
config.update({'stp': 'on'})
elif opts['stp'] in _CONFIG_FALSE:
config.update({'stp': 'off'})
else:
_raise_error_iface(iface, 'stp', _CONFIG_TRUE + _CONFIG_FALSE)
if 'waitport' in opts:
if isinstance(opts['waitport'], int):
config.update({'waitport': opts['waitport']})
else:
values = opts['waitport'].split()
waitport_time = values.pop(0)
if waitport_time.isdigit() and values:
config.update({
'waitport': '{0} {1}'.format(
waitport_time, ' '.join(values)
)
})
else:
_raise_error_iface(iface, opt, ['integer [interfaces]'])
return config
def _parse_settings_eth(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['inet'] = salt.utils.odict.OrderedDict()
iface_data['inet6'] = salt.utils.odict.OrderedDict()
if enabled:
adapters[iface]['enabled'] = True
if opts.get('hotplug', False):
adapters[iface]['hotplug'] = True
if opts.get('enable_ipv6', None) and opts.get('iface_type', '') == 'vlan':
iface_data['inet6']['vlan_raw_device'] = (
re.sub(r'\.\d*', '', iface))
for addrfam in ['inet', 'inet6']:
if iface_type not in ['bridge']:
tmp_ethtool = _parse_ethtool_opts(opts, iface)
if tmp_ethtool:
ethtool = {}
for item in tmp_ethtool:
ethtool[_ETHTOOL_CONFIG_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['ethtool'] = ethtool
# return a list of sorted keys to ensure consistent order
iface_data[addrfam]['ethtool_keys'] = sorted(ethtool)
if iface_type == 'bridge':
bridging = _parse_bridge_opts(opts, iface)
if bridging:
iface_data[addrfam]['bridging'] = bridging
iface_data[addrfam]['bridging_keys'] = sorted(bridging)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'bond':
bonding = _parse_settings_bond(opts, iface)
if bonding:
iface_data[addrfam]['bonding'] = bonding
iface_data[addrfam]['bonding']['slaves'] = opts['slaves']
iface_data[addrfam]['bonding_keys'] = sorted(bonding)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'slave':
adapters[iface]['master'] = opts['master']
opts['proto'] = 'manual'
iface_data[addrfam]['master'] = adapters[iface]['master']
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'vlan':
iface_data[addrfam]['vlan_raw_device'] = re.sub(r'\.\d*', '', iface)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'pppoe':
tmp_ethtool = _parse_ethtool_pppoe_opts(opts, iface)
if tmp_ethtool:
for item in tmp_ethtool:
adapters[iface]['data'][addrfam][_DEB_CONFIG_PPPOE_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['addrfam'] = addrfam
opts.pop('mode', None)
for opt, val in opts.items():
inet = None
if opt.startswith('ipv4'):
opt = opt[4:]
inet = 'inet'
iface_data['inet']['addrfam'] = 'inet'
elif opt.startswith('ipv6'):
iface_data['inet6']['addrfam'] = 'inet6'
opt = opt[4:]
inet = 'inet6'
elif opt in ['ipaddr', 'address', 'ipaddresses', 'addresses', 'gateway', 'proto']:
iface_data['inet']['addrfam'] = 'inet'
inet = 'inet'
_opt = SALT_ATTR_TO_DEBIAN_ATTR_MAP.get(opt, opt)
_debopt = _opt.replace('-', '_')
for addrfam in ['inet', 'inet6']:
(valid, value, errmsg) = _validate_interface_option(_opt, val, addrfam=addrfam)
if not valid:
continue
if inet is None and _debopt not in iface_data[addrfam]:
iface_data[addrfam][_debopt] = value
elif inet == addrfam:
iface_data[addrfam][_debopt] = value
for opt in ['up_cmds', 'pre_up_cmds', 'post_up_cmds',
'down_cmds', 'pre_down_cmds', 'post_down_cmds']:
if opt in opts:
iface_data['inet'][opt] = opts[opt]
iface_data['inet6'][opt] = opts[opt]
# Remove incomplete/disabled inet blocks
for (addrfam, opt) in [('inet', 'enable_ipv4'), ('inet6', 'enable_ipv6')]:
if opts.get(opt, None) is False:
iface_data.pop(addrfam)
elif iface_data[addrfam].get('addrfam', '') != addrfam:
iface_data.pop(addrfam)
return adapters
def _parse_network_settings(opts, current):
'''
Filters given options and outputs valid settings for
the global network settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
current = dict((k.lower(), v) for (k, v) in six.iteritems(current))
result = {}
valid = _CONFIG_TRUE + _CONFIG_FALSE
if 'enabled' not in opts:
try:
opts['networking'] = current['networking']
_log_default_network('networking', current['networking'])
except ValueError:
_raise_error_network('networking', valid)
else:
opts['networking'] = opts['enabled']
if opts['networking'] in valid:
if opts['networking'] in _CONFIG_TRUE:
result['networking'] = 'yes'
elif opts['networking'] in _CONFIG_FALSE:
result['networking'] = 'no'
else:
_raise_error_network('networking', valid)
if 'hostname' not in opts:
try:
opts['hostname'] = current['hostname']
_log_default_network('hostname', current['hostname'])
except ValueError:
_raise_error_network('hostname', ['server1.example.com'])
if opts['hostname']:
result['hostname'] = opts['hostname']
else:
_raise_error_network('hostname', ['server1.example.com'])
if 'search' in opts:
result['search'] = opts['search']
return result
def _parse_routes(iface, opts):
'''
Filters given options and outputs valid settings for
the route settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
result = {}
if 'routes' not in opts:
_raise_error_routes(iface, 'routes', 'List of routes')
for opt in opts:
result[opt] = opts[opt]
return result
def _write_file(iface, data, folder, pattern):
'''
Writes a file to disk
'''
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
return filename
def _write_file_routes(iface, data, folder, pattern):
'''
Writes a file to disk
'''
# ifup / ifdown is executing given folder via run-parts.
# according to run-parts man-page, only filenames with this pattern are
# executed: (^[a-zA-Z0-9_-]+$)
# In order to make the routes file work for vlan interfaces
# (default would have been in example /etc/network/if-up.d/route-bond0.12)
# these dots in the iface name need to be replaced by underscores, so it
# can be executed by run-parts
iface = iface.replace('.', '_')
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
__salt__['file.set_mode'](filename, '0755')
return filename
def _write_file_network(data, filename, create=False):
'''
Writes a file to disk
If file does not exist, only create if create
argument is True
'''
if not os.path.exists(filename) and not create:
msg = '{0} cannot be written. {0} does not exist\
and create is set to False'
msg = msg.format(filename)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
def _read_temp(data):
'''
Return what would be written to disk
'''
tout = StringIO()
tout.write(data)
tout.seek(0)
output = tout.readlines()
tout.close()
return output
def _read_temp_ifaces(iface, data):
'''
Return what would be written to disk for interfaces
'''
try:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': data})
# Return as an array so the difflib works
return [item + '\n' for item in ifcfg.split('\n')]
def _write_file_ifaces(iface, data, **settings):
'''
Writes a file to disk
'''
try:
eth_template = JINJA.get_template('debian_eth.jinja')
source_template = JINJA.get_template('debian_source.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
# Read /etc/network/interfaces into a dict
adapters = _parse_interfaces()
# Apply supplied settings over on-disk settings
adapters[iface] = data
ifcfg = ''
for adapter in adapters:
if 'type' in adapters[adapter] and adapters[adapter]['type'] == 'source':
tmp = source_template.render({'name': adapter, 'data': adapters[adapter]})
else:
tmp = eth_template.render({'name': adapter, 'data': adapters[adapter]})
ifcfg = ifcfg + tmp
if adapter == iface:
saved_ifcfg = tmp
_SEPARATE_FILE = False
if 'filename' in settings:
if not settings['filename'].startswith('/'):
filename = '{0}/{1}'.format(_DEB_NETWORK_DIR, settings['filename'])
else:
filename = settings['filename']
_SEPARATE_FILE = True
else:
if 'filename' in adapters[adapter]['data']:
filename = adapters[adapter]['data']
else:
filename = _DEB_NETWORK_FILE
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
if _SEPARATE_FILE:
fout.write(salt.utils.stringutils.to_str(saved_ifcfg))
else:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return saved_ifcfg.split('\n')
def _write_file_ppp_ifaces(iface, data):
'''
Writes a file to disk
'''
try:
template = JINJA.get_template('debian_ppp_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_ppp_eth.jinja')
return ''
adapters = _parse_interfaces()
adapters[iface] = data
ifcfg = ''
tmp = template.render({'data': adapters[iface]})
ifcfg = tmp + ifcfg
filename = _DEB_PPP_DIR + '/' + adapters[iface]['data']['inet']['provider']
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.fopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return filename
def build_bond(iface, **settings):
'''
Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb
'''
deb_major = __grains__['osrelease'][:1]
opts = _parse_settings_bond(settings, iface)
try:
template = JINJA.get_template('conf.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template conf.jinja')
return ''
data = template.render({'name': iface, 'bonding': opts})
if 'test' in settings and settings['test']:
return _read_temp(data)
_write_file(iface, data, _DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
if deb_major == '5':
for line_type in ('alias', 'options'):
cmd = ['sed', '-i', '-e', r'/^{0}\s{1}.*/d'.format(line_type, iface),
'/etc/modprobe.conf']
__salt__['cmd.run'](cmd, python_shell=False)
__salt__['file.append']('/etc/modprobe.conf', path)
# Load kernel module
__salt__['kmod.load']('bonding')
# install ifenslave-2.6
__salt__['pkg.install']('ifenslave-2.6')
return _read_file(path)
def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'vlan':
settings['vlan'] = 'yes'
__salt__['pkg.install']('vlan')
elif iface_type == 'pppoe':
settings['pppoe'] = 'yes'
if not __salt__['pkg.version']('ppp'):
inst = __salt__['pkg.install']('ppp')
elif iface_type == 'bond':
if 'slaves' not in settings:
msg = 'slaves is a required setting for bond interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'bridge':
if 'ports' not in settings:
msg = (
'ports is a required setting for bridge interfaces on Debian '
'or Ubuntu based systems'
)
log.error(msg)
raise AttributeError(msg)
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'pppoe']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
if iface_type in ['source']:
opts = _parse_settings_source(settings, iface_type, enabled, iface)
if 'test' in settings and settings['test']:
return _read_temp_ifaces(iface, opts[iface])
ifcfg = _write_file_ifaces(iface, opts[iface], **settings)
if iface_type == 'pppoe':
_write_file_ppp_ifaces(iface, opts[iface])
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg]
def build_routes(iface, **settings):
'''
Add route scripts for a network interface using up commands.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
'''
opts = _parse_routes(iface, settings)
try:
template = JINJA.get_template('route_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template route_eth.jinja')
return ''
add_routecfg = template.render(route_type='add',
routes=opts['routes'],
iface=iface)
del_routecfg = template.render(route_type='del',
routes=opts['routes'],
iface=iface)
if 'test' in settings and settings['test']:
return _read_temp(add_routecfg + del_routecfg)
filename = _write_file_routes(iface,
add_routecfg,
_DEB_NETWORK_UP_DIR,
'route-{0}')
results = _read_file(filename)
filename = _write_file_routes(iface,
del_routecfg,
_DEB_NETWORK_DOWN_DIR,
'route-{0}')
results += _read_file(filename)
return results
def down(iface, iface_type):
'''
Shutdown a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.down eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought down.
if iface_type not in ['slave', 'source']:
return __salt__['cmd.run'](['ifdown', iface])
return None
def get_bond(iface):
'''
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
'''
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
return _read_file(path)
def get_interface(iface):
'''
Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
adapters = _parse_interfaces()
if iface in adapters:
try:
if iface == 'source':
template = JINJA.get_template('debian_source.jinja')
else:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': adapters[iface]})
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg.split('\n')]
else:
return []
def up(iface, iface_type): # pylint: disable=C0103
'''
Start up a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.up eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought up.
if iface_type not in ('slave', 'source'):
return __salt__['cmd.run'](['ifup', iface])
return None
def get_network_settings():
'''
Return the contents of the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_network_settings
'''
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
settings = {}
if __salt__['service.available']('networking'):
if __salt__['service.status']('networking'):
settings['networking'] = "yes"
else:
settings['networking'] = "no"
else:
settings['networking'] = "no"
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
settings['hostname'] = hostname
settings['domainname'] = domainname
settings['searchdomain'] = searchdomain
else:
settings = _parse_current_network_settings()
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(settings)
return _read_temp(network)
def get_routes(iface):
'''
Return the routes for the interface
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0
'''
filename = os.path.join(_DEB_NETWORK_UP_DIR, 'route-{0}'.format(iface))
results = _read_file(filename)
filename = os.path.join(_DEB_NETWORK_DOWN_DIR, 'route-{0}'.format(iface))
results += _read_file(filename)
return results
def apply_network_settings(**settings):
'''
Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings
'''
if 'require_reboot' not in settings:
settings['require_reboot'] = False
if 'apply_hostname' not in settings:
settings['apply_hostname'] = False
hostname_res = True
if settings['apply_hostname'] in _CONFIG_TRUE:
if 'hostname' in settings:
hostname_res = __salt__['network.mod_hostname'](settings['hostname'])
else:
log.warning(
'The network state sls is trying to apply hostname '
'changes but no hostname is defined.'
)
hostname_res = False
res = True
if settings['require_reboot'] in _CONFIG_TRUE:
log.warning(
'The network state sls is requiring a reboot of the system to '
'properly apply network configuration.'
)
res = True
else:
stop = __salt__['service.stop']('networking')
time.sleep(2)
res = stop and __salt__['service.start']('networking')
return hostname_res and res
def build_network_settings(**settings):
'''
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
'''
changes = []
# Read current configuration and store default values
current_network_settings = _parse_current_network_settings()
# Build settings
opts = _parse_network_settings(settings, current_network_settings)
# Ubuntu has moved away from /etc/default/networking
# beginning with the 12.04 release so we disable or enable
# the networking related services on boot
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
if opts['networking'] == 'yes':
service_cmd = 'service.enable'
else:
service_cmd = 'service.disable'
if __salt__['service.available']('NetworkManager'):
__salt__[service_cmd]('NetworkManager')
if __salt__['service.available']('networking'):
__salt__[service_cmd]('networking')
else:
try:
template = JINJA.get_template('network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template network.jinja')
return ''
network = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(network)
# Write settings
_write_file_network(network, _DEB_NETWORKING_FILE, True)
# Get hostname and domain from opts
sline = opts['hostname'].split('.', 1)
opts['hostname'] = sline[0]
current_domainname = current_network_settings['domainname']
current_searchdomain = current_network_settings['searchdomain']
new_domain = False
if len(sline) > 1:
new_domainname = sline[1]
if new_domainname != current_domainname:
domainname = new_domainname
opts['domainname'] = new_domainname
new_domain = True
else:
domainname = current_domainname
opts['domainname'] = domainname
else:
domainname = current_domainname
opts['domainname'] = domainname
new_search = False
if 'search' in opts:
new_searchdomain = opts['search']
if new_searchdomain != current_searchdomain:
searchdomain = new_searchdomain
opts['searchdomain'] = new_searchdomain
new_search = True
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
# If the domain changes, then we should write the resolv.conf file.
if new_domain or new_search:
# Look for existing domain line and update if necessary
resolve = _parse_resolve()
domain_prog = re.compile(r'domain\s+')
search_prog = re.compile(r'search\s+')
new_contents = []
for item in _read_file(_DEB_RESOLV_FILE):
if domain_prog.match(item):
item = 'domain {0}'.format(domainname)
elif search_prog.match(item):
item = 'search {0}'.format(searchdomain)
new_contents.append(item)
# A domain line didn't exist so we'll add one in
# with the new domainname
if 'domain' not in resolve:
new_contents.insert(0, 'domain {0}' . format(domainname))
# A search line didn't exist so we'll add one in
# with the new search domain
if 'search' not in resolve:
new_contents.insert('domain' in resolve, 'search {0}'.format(searchdomain))
new_resolv = '\n'.join(new_contents)
# Write /etc/resolv.conf
if not ('test' in settings and settings['test']):
_write_file_network(new_resolv, _DEB_RESOLV_FILE)
# used for returning the results back
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(opts)
changes.extend(_read_temp(network))
return changes
|
saltstack/salt
|
salt/modules/debian_ip.py
|
_parse_network_settings
|
python
|
def _parse_network_settings(opts, current):
'''
Filters given options and outputs valid settings for
the global network settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
current = dict((k.lower(), v) for (k, v) in six.iteritems(current))
result = {}
valid = _CONFIG_TRUE + _CONFIG_FALSE
if 'enabled' not in opts:
try:
opts['networking'] = current['networking']
_log_default_network('networking', current['networking'])
except ValueError:
_raise_error_network('networking', valid)
else:
opts['networking'] = opts['enabled']
if opts['networking'] in valid:
if opts['networking'] in _CONFIG_TRUE:
result['networking'] = 'yes'
elif opts['networking'] in _CONFIG_FALSE:
result['networking'] = 'no'
else:
_raise_error_network('networking', valid)
if 'hostname' not in opts:
try:
opts['hostname'] = current['hostname']
_log_default_network('hostname', current['hostname'])
except ValueError:
_raise_error_network('hostname', ['server1.example.com'])
if opts['hostname']:
result['hostname'] = opts['hostname']
else:
_raise_error_network('hostname', ['server1.example.com'])
if 'search' in opts:
result['search'] = opts['search']
return result
|
Filters given options and outputs valid settings for
the global network settings file.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_ip.py#L1332-L1375
| null |
# -*- coding: utf-8 -*-
'''
The networking module for Debian-based distros
References:
* http://www.debian.org/doc/manuals/debian-reference/ch05.en.html
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import functools
import logging
import os.path
import os
import re
import time
# Import third party libs
import jinja2
import jinja2.exceptions
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error,no-name-in-module
# Import salt libs
import salt.utils.dns
import salt.utils.files
import salt.utils.odict
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.validate.net
# Set up logging
log = logging.getLogger(__name__)
# Set up template environment
JINJA = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'debian_ip')
)
)
# Define the module's virtual name
__virtualname__ = 'ip'
def __virtual__():
'''
Confine this module to Debian-based distros
'''
if __grains__['os_family'] == 'Debian':
return __virtualname__
return (False, 'The debian_ip module could not be loaded: '
'unsupported OS family')
_ETHTOOL_CONFIG_OPTS = {
'speed': 'link-speed',
'duplex': 'link-duplex',
'autoneg': 'ethernet-autoneg',
'ethernet-port': 'ethernet-port',
'wol': 'ethernet-wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'rx': 'offload-rx',
'tx': 'offload-tx',
'sg': 'offload-sg',
'tso': 'offload-tso',
'ufo': 'offload-ufo',
'gso': 'offload-gso',
'gro': 'offload-gro',
'lro': 'offload-lro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_REV_ETHTOOL_CONFIG_OPTS = {
'link-speed': 'speed',
'link-duplex': 'duplex',
'ethernet-autoneg': 'autoneg',
'ethernet-port': 'ethernet-port',
'ethernet-wol': 'wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'offload-rx': 'rx',
'offload-tx': 'tx',
'offload-sg': 'sg',
'offload-tso': 'tso',
'offload-ufo': 'ufo',
'offload-gso': 'gso',
'offload-lro': 'lro',
'offload-gro': 'gro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_DEB_CONFIG_PPPOE_OPTS = {
'user': 'user',
'password': 'password',
'provider': 'provider',
'pppoe_iface': 'pppoe_iface',
'noipdefault': 'noipdefault',
'usepeerdns': 'usepeerdns',
'defaultroute': 'defaultroute',
'holdoff': 'holdoff',
'maxfail': 'maxfail',
'hide-password': 'hide-password',
'lcp-echo-interval': 'lcp-echo-interval',
'lcp-echo-failure': 'lcp-echo-failure',
'connect': 'connect',
'noauth': 'noauth',
'persist': 'persist',
'mtu': 'mtu',
'noaccomp': 'noaccomp',
'linkname': 'linkname',
}
_DEB_ROUTES_FILE = '/etc/network/routes'
_DEB_NETWORK_FILE = '/etc/network/interfaces'
_DEB_NETWORK_DIR = '/etc/network/interfaces.d/'
_DEB_NETWORK_UP_DIR = '/etc/network/if-up.d/'
_DEB_NETWORK_DOWN_DIR = '/etc/network/if-down.d/'
_DEB_NETWORK_CONF_FILES = '/etc/modprobe.d/'
_DEB_NETWORKING_FILE = '/etc/default/networking'
_DEB_HOSTNAME_FILE = '/etc/hostname'
_DEB_RESOLV_FILE = '/etc/resolv.conf'
_DEB_PPP_DIR = '/etc/ppp/peers/'
_CONFIG_TRUE = ['yes', 'on', 'true', '1', True]
_CONFIG_FALSE = ['no', 'off', 'false', '0', False]
_IFACE_TYPES = [
'eth', 'bond', 'alias', 'clone',
'ipsec', 'dialup', 'bridge', 'slave',
'vlan', 'pppoe', 'source',
]
def _error_msg_iface(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, '|'.join(str(e) for e in expected))
def _error_msg_routes(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, expected)
def _log_default_iface(iface, opt, value):
log.info(
'Using default option -- Interface: %s Option: %s Value: %s',
iface, opt, value
)
def _error_msg_network(option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]'
return msg.format(option, '|'.join(str(e) for e in expected))
def _log_default_network(opt, value):
log.info('Using existing setting -- Setting: %s Value: %s', opt, value)
def _raise_error_iface(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_iface(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_network(option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_network(option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_routes(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_routes(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _read_file(path):
'''
Reads and returns the contents of a text file
'''
try:
with salt.utils.files.flopen(path, 'rb') as contents:
return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]
except (OSError, IOError):
return ''
def _parse_resolve():
'''
Parse /etc/resolv.conf
'''
return salt.utils.dns.parse_resolv(_DEB_RESOLV_FILE)
def _parse_domainname():
'''
Parse /etc/resolv.conf and return domainname
'''
return _parse_resolve().get('domain', '')
def _parse_searchdomain():
'''
Parse /etc/resolv.conf and return searchdomain
'''
return _parse_resolve().get('search', '')
def _parse_hostname():
'''
Parse /etc/hostname and return hostname
'''
contents = _read_file(_DEB_HOSTNAME_FILE)
if contents:
return contents[0].split('\n')[0]
else:
return ''
def _parse_current_network_settings():
'''
Parse /etc/default/networking and return current configuration
'''
opts = salt.utils.odict.OrderedDict()
opts['networking'] = ''
if os.path.isfile(_DEB_NETWORKING_FILE):
with salt.utils.files.fopen(_DEB_NETWORKING_FILE) as contents:
for line in contents:
salt.utils.stringutils.to_unicode(line)
if line.startswith('#'):
continue
elif line.startswith('CONFIGURE_INTERFACES'):
opts['networking'] = line.split('=', 1)[1].strip()
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
opts['hostname'] = hostname
opts['domainname'] = domainname
opts['searchdomain'] = searchdomain
return opts
# def __validator_func(value):
# return (valid: True/False, (transformed) value, error message)
def __ipv4_quad(value):
'''validate an IPv4 address'''
return (salt.utils.validate.net.ipv4_addr(value), value,
'dotted IPv4 address')
def __ipv6(value):
'''validate an IPv6 address'''
return (salt.utils.validate.net.ipv6_addr(value), value,
'IPv6 address')
def __mac(value):
'''validate a mac address'''
return (salt.utils.validate.net.mac(value), value,
'MAC address')
def __anything(value):
return (True, value, None)
def __int(value):
'''validate an integer'''
valid, _value = False, value
try:
_value = int(value)
valid = True
except ValueError:
pass
return (valid, _value, 'integer')
def __float(value):
'''validate a float'''
valid, _value = False, value
try:
_value = float(value)
valid = True
except ValueError:
pass
return (valid, _value, 'float')
def __ipv4_netmask(value):
'''validate an IPv4 dotted quad or integer CIDR netmask'''
valid, errmsg = False, 'dotted quad or integer CIDR (0->32)'
valid, value, _ = __int(value)
if not (valid and 0 <= value <= 32):
valid = salt.utils.validate.net.netmask(value)
return (valid, value, errmsg)
def __ipv6_netmask(value):
'''validate an IPv6 integer netmask'''
valid, errmsg = False, 'IPv6 netmask (0->128)'
valid, value, _ = __int(value)
valid = (valid and 0 <= value <= 128)
return (valid, value, errmsg)
def __within2(value, within=None, errmsg=None, dtype=None):
'''validate that a value is in ``within`` and optionally a ``dtype``'''
valid, _value = False, value
if dtype:
try:
_value = dtype(value) # TODO: this is a bit loose when dtype is a class
valid = _value in within
except ValueError:
pass
else:
valid = _value in within
if errmsg is None:
if dtype:
typename = getattr(dtype, '__name__',
hasattr(dtype, '__class__')
and getattr(dtype.__class__, 'name', dtype))
errmsg = '{0} within \'{1}\''.format(typename, within)
else:
errmsg = 'within \'{0}\''.format(within)
return (valid, _value, errmsg)
def __within(within=None, errmsg=None, dtype=None):
return functools.partial(__within2, within=within,
errmsg=errmsg, dtype=dtype)
def __space_delimited_list(value):
'''validate that a value contains one or more space-delimited values'''
if isinstance(value, six.string_types):
value = value.strip().split()
if hasattr(value, '__iter__') and value != []:
return (True, value, 'space-delimited string')
else:
return (False, value, '{0} is not a valid space-delimited value.\n'.format(value))
SALT_ATTR_TO_DEBIAN_ATTR_MAP = {
'dns': 'dns-nameservers',
'search': 'dns-search',
'hwaddr': 'hwaddress', # TODO: this limits bootp functionality
'ipaddr': 'address',
'ipaddrs': 'addresses',
}
DEBIAN_ATTR_TO_SALT_ATTR_MAP = dict(
(v, k) for (k, v) in six.iteritems(SALT_ATTR_TO_DEBIAN_ATTR_MAP))
# TODO
DEBIAN_ATTR_TO_SALT_ATTR_MAP['address'] = 'address'
DEBIAN_ATTR_TO_SALT_ATTR_MAP['hwaddress'] = 'hwaddress'
IPV4_VALID_PROTO = ['bootp', 'dhcp', 'static', 'manual', 'loopback', 'ppp']
IPV4_ATTR_MAP = {
'proto': __within(IPV4_VALID_PROTO, dtype=six.text_type),
# ipv4 static & manual
'address': __ipv4_quad,
'addresses': __anything,
'netmask': __ipv4_netmask,
'broadcast': __ipv4_quad,
'metric': __int,
'gateway': __ipv4_quad, # supports a colon-delimited list
'pointopoint': __ipv4_quad,
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'link', 'host'], dtype=six.text_type),
# dhcp
'hostname': __anything,
'leasehours': __int,
'leasetime': __int,
'vendor': __anything,
'client': __anything,
# bootp
'bootfile': __anything,
'server': __ipv4_quad,
'hwaddr': __mac,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'dstaddr': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# bond
'slaves': __anything,
# ppp
'provider': __anything,
'unit': __int,
'options': __anything,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
#
'network': __anything, # i don't know what this is
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
IPV6_VALID_PROTO = ['auto', 'loopback', 'static', 'manual',
'dhcp', 'v4tunnel', '6to4']
IPV6_ATTR_MAP = {
'proto': __within(IPV6_VALID_PROTO),
# ipv6 static & manual
'address': __ipv6,
'addresses': __anything,
'netmask': __ipv6_netmask,
'broadcast': __ipv6,
'gateway': __ipv6, # supports a colon-delimited list
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'site', 'link', 'host'], dtype=six.text_type),
# inet6 auto
'privext': __within([0, 1, 2], dtype=int),
'dhcp': __within([0, 1], dtype=int),
# inet6 static & manual & dhcp
'media': __anything,
'accept_ra': __within([0, 1], dtype=int),
'autoconf': __within([0, 1], dtype=int),
'preferred-lifetime': __int,
'dad-attempts': __int, # 0 to disable
'dad-interval': __float,
# bond
'slaves': __anything,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
WIRELESS_ATTR_MAP = {
'wireless-essid': __anything,
'wireless-mode': __anything, # TODO
'wpa-ap-scan': __within([0, 1, 2], dtype=int), # TODO
'wpa-conf': __anything,
'wpa-driver': __anything,
'wpa-group': __anything,
'wpa-key-mgmt': __anything,
'wpa-pairwise': __anything,
'wpa-psk': __anything,
'wpa-proto': __anything, # partial(__within,
'wpa-roam': __anything,
'wpa-ssid': __anything, # TODO
}
ATTRMAPS = {
'inet': [IPV4_ATTR_MAP, WIRELESS_ATTR_MAP],
'inet6': [IPV6_ATTR_MAP, WIRELESS_ATTR_MAP]
}
def _validate_interface_option(attr, value, addrfam='inet'):
'''lookup the validation function for a [addrfam][attr] and
return the results
:param attr: attribute name
:param value: raw setting value
:param addrfam: address family (inet, inet6,
'''
valid, _value, errmsg = False, value, 'Unknown validator'
attrmaps = ATTRMAPS.get(addrfam, [])
for attrmap in attrmaps:
if attr in attrmap:
validate_func = attrmap[attr]
(valid, _value, errmsg) = validate_func(value)
break
return (valid, _value, errmsg)
def _attrmaps_contain_attr(attr):
return (
attr in WIRELESS_ATTR_MAP or
attr in IPV4_ATTR_MAP or
attr in IPV6_ATTR_MAP)
def _parse_interfaces(interface_files=None):
'''
Parse /etc/network/interfaces and return current configured interfaces
'''
if interface_files is None:
interface_files = []
# Add this later.
if os.path.exists(_DEB_NETWORK_DIR):
interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]
if os.path.isfile(_DEB_NETWORK_FILE):
interface_files.insert(0, _DEB_NETWORK_FILE)
adapters = salt.utils.odict.OrderedDict()
method = -1
for interface_file in interface_files:
with salt.utils.files.fopen(interface_file) as interfaces:
# This ensures iface_dict exists, but does not ensure we're not reading a new interface.
iface_dict = {}
for line in interfaces:
line = salt.utils.stringutils.to_unicode(line)
# Identify the clauses by the first word of each line.
# Go to the next line if the current line is a comment
# or all spaces.
if line.lstrip().startswith('#') or line.isspace():
continue
# Parse the iface clause
if line.startswith('iface'):
sline = line.split()
if len(sline) != 4:
msg = 'Interface file malformed: {0}.'
msg = msg.format(sline)
log.error(msg)
raise AttributeError(msg)
iface_name = sline[1]
addrfam = sline[2]
method = sline[3]
# Create item in dict, if not already there
if iface_name not in adapters:
adapters[iface_name] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters[iface_name]:
adapters[iface_name]['data'] = salt.utils.odict.OrderedDict()
if addrfam not in adapters[iface_name]['data']:
adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict()
iface_dict = adapters[iface_name]['data'][addrfam]
iface_dict['addrfam'] = addrfam
iface_dict['proto'] = method
iface_dict['filename'] = interface_file
# Parse the detail clauses.
elif line[0].isspace():
sline = line.split()
# conf file attr: dns-nameservers
# salt states.network attr: dns
attr, valuestr = line.rstrip().split(None, 1)
if _attrmaps_contain_attr(attr):
if '-' in attr:
attrname = attr.replace('-', '_')
else:
attrname = attr
(valid, value, errmsg) = _validate_interface_option(
attr, valuestr, addrfam)
if attrname == 'address' and 'address' in iface_dict:
if 'addresses' not in iface_dict:
iface_dict['addresses'] = []
iface_dict['addresses'].append(value)
else:
iface_dict[attrname] = value
elif attr in _REV_ETHTOOL_CONFIG_OPTS:
if 'ethtool' not in iface_dict:
iface_dict['ethtool'] = salt.utils.odict.OrderedDict()
iface_dict['ethtool'][attr] = valuestr
elif attr.startswith('bond'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bonding' not in iface_dict:
iface_dict['bonding'] = salt.utils.odict.OrderedDict()
iface_dict['bonding'][opt] = valuestr
elif attr.startswith('bridge'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bridging' not in iface_dict:
iface_dict['bridging'] = salt.utils.odict.OrderedDict()
iface_dict['bridging'][opt] = valuestr
elif attr in ['up', 'pre-up', 'post-up',
'down', 'pre-down', 'post-down']:
cmd = valuestr
cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr))
if cmd_key not in iface_dict:
iface_dict[cmd_key] = []
iface_dict[cmd_key].append(cmd)
elif line.startswith('auto'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['enabled'] = True
elif line.startswith('allow-hotplug'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['hotplug'] = True
elif line.startswith('source'):
if 'source' not in adapters:
adapters['source'] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters['source']:
adapters['source']['data'] = salt.utils.odict.OrderedDict()
adapters['source']['data']['sources'] = []
adapters['source']['data']['sources'].append(line.split()[1])
# Return a sorted list of the keys for bond, bridge and ethtool options to
# ensure a consistent order
for iface_name in adapters:
if iface_name == 'source':
continue
if 'data' not in adapters[iface_name]:
msg = 'Interface file malformed for interface: {0}.'.format(iface_name)
log.error(msg)
adapters.pop(iface_name)
continue
for opt in ['ethtool', 'bonding', 'bridging']:
for inet in ['inet', 'inet6']:
if inet in adapters[iface_name]['data']:
if opt in adapters[iface_name]['data'][inet]:
opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys())
adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys
return adapters
def _parse_ethtool_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
if 'autoneg' in opts:
if opts['autoneg'] in _CONFIG_TRUE:
config.update({'autoneg': 'on'})
elif opts['autoneg'] in _CONFIG_FALSE:
config.update({'autoneg': 'off'})
else:
_raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE)
if 'duplex' in opts:
valid = ['full', 'half']
if opts['duplex'] in valid:
config.update({'duplex': opts['duplex']})
else:
_raise_error_iface(iface, 'duplex', valid)
if 'speed' in opts:
valid = ['10', '100', '1000', '10000']
if six.text_type(opts['speed']) in valid:
config.update({'speed': opts['speed']})
else:
_raise_error_iface(iface, opts['speed'], valid)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'on'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'off'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_ethtool_pppoe_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
for opt in _DEB_CONFIG_PPPOE_OPTS:
if opt in opts:
config[opt] = opts[opt]
if 'provider' in opts and not opts['provider']:
_raise_error_iface(iface, 'provider', _CONFIG_TRUE + _CONFIG_FALSE)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('noipdefault', 'usepeerdns', 'defaultroute', 'hide-password', 'noauth', 'persist', 'noaccomp'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'True'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'False'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_settings_bond(opts, iface):
'''
Filters given options and outputs valid settings for requested
operation. If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond_def = {
# 803.ad aggregation selection logic
# 0 for stable (default)
# 1 for bandwidth
# 2 for count
'ad_select': '0',
# Max number of transmit queues (default = 16)
'tx_queues': '16',
# Link monitoring in milliseconds. Most NICs support this
'miimon': '100',
# ARP interval in milliseconds
'arp_interval': '250',
# Delay before considering link down in milliseconds (miimon * 2)
'downdelay': '200',
# lacp_rate 0: Slow - every 30 seconds
# lacp_rate 1: Fast - every 1 second
'lacp_rate': '0',
# Max bonds for this driver
'max_bonds': '1',
# Specifies the time, in milliseconds, to wait before
# enabling a slave after a link recovery has been
# detected. Only used with miimon.
'updelay': '0',
# Used with miimon.
# On: driver sends mii
# Off: ethtool sends mii
'use_carrier': 'on',
# Default. Don't change unless you know what you are doing.
'xmit_hash_policy': 'layer2',
}
if opts['mode'] in ['balance-rr', '0']:
log.info('Device: %s Bonding Mode: load balancing (round-robin)', iface)
return _parse_settings_bond_0(opts, iface, bond_def)
elif opts['mode'] in ['active-backup', '1']:
log.info('Device: %s Bonding Mode: fault-tolerance (active-backup)', iface)
return _parse_settings_bond_1(opts, iface, bond_def)
elif opts['mode'] in ['balance-xor', '2']:
log.info('Device: %s Bonding Mode: load balancing (xor)', iface)
return _parse_settings_bond_2(opts, iface, bond_def)
elif opts['mode'] in ['broadcast', '3']:
log.info('Device: %s Bonding Mode: fault-tolerance (broadcast)', iface)
return _parse_settings_bond_3(opts, iface, bond_def)
elif opts['mode'] in ['802.3ad', '4']:
log.info('Device: %s Bonding Mode: IEEE 802.3ad Dynamic link '
'aggregation', iface)
return _parse_settings_bond_4(opts, iface, bond_def)
elif opts['mode'] in ['balance-tlb', '5']:
log.info('Device: %s Bonding Mode: transmit load balancing', iface)
return _parse_settings_bond_5(opts, iface, bond_def)
elif opts['mode'] in ['balance-alb', '6']:
log.info('Device: %s Bonding Mode: adaptive load balancing', iface)
return _parse_settings_bond_6(opts, iface, bond_def)
else:
valid = [
'0', '1', '2', '3', '4', '5', '6',
'balance-rr', 'active-backup', 'balance-xor',
'broadcast', '802.3ad', 'balance-tlb', 'balance-alb'
]
_raise_error_iface(iface, 'mode', valid)
def _parse_settings_bond_0(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond0.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '0'}
# ARP targets in n.n.n.n form
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
return bond
def _parse_settings_bond_1(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '1'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
if not (__grains__['os'] == "Ubuntu" and __grains__['osrelease_info'][0] >= 16):
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_2(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond2.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '2'}
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_3(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond3.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '3'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_4(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond4.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '4'}
for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']:
if binding in opts:
if binding == 'lacp_rate':
if opts[binding] == 'fast':
opts.update({binding: '1'})
if opts[binding] == 'slow':
opts.update({binding: '0'})
valid = ['fast', '1', 'slow', '0']
else:
valid = ['integer']
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, valid)
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_5(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond5.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '5'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_settings_bond_6(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond6.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '6'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_bridge_opts(opts, iface):
'''
Filters given options and outputs valid settings for BRIDGING_OPTS
If an option has a value that is not expected, this
function will log the Interface, Setting and what was expected.
'''
config = {}
if 'ports' in opts:
if isinstance(opts['ports'], list):
opts['ports'] = ' '.join(opts['ports'])
config.update({'ports': opts['ports']})
for opt in ['ageing', 'fd', 'gcint', 'hello', 'maxage']:
if opt in opts:
try:
float(opts[opt])
config.update({opt: opts[opt]})
except ValueError:
_raise_error_iface(iface, opt, ['float'])
for opt in ['bridgeprio', 'maxwait']:
if opt in opts:
if isinstance(opts[opt], int):
config.update({opt: opts[opt]})
else:
_raise_error_iface(iface, opt, ['integer'])
if 'hw' in opts:
# match 12 hex digits with either : or - as separators between pairs
if re.match('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$',
opts['hw'].lower()):
config.update({'hw': opts['hw']})
else:
_raise_error_iface(iface, 'hw', ['valid MAC address'])
for opt in ['pathcost', 'portprio']:
if opt in opts:
try:
port, cost_or_prio = opts[opt].split()
int(cost_or_prio)
config.update({opt: '{0} {1}'.format(port, cost_or_prio)})
except ValueError:
_raise_error_iface(iface, opt, ['interface integer'])
if 'stp' in opts:
if opts['stp'] in _CONFIG_TRUE:
config.update({'stp': 'on'})
elif opts['stp'] in _CONFIG_FALSE:
config.update({'stp': 'off'})
else:
_raise_error_iface(iface, 'stp', _CONFIG_TRUE + _CONFIG_FALSE)
if 'waitport' in opts:
if isinstance(opts['waitport'], int):
config.update({'waitport': opts['waitport']})
else:
values = opts['waitport'].split()
waitport_time = values.pop(0)
if waitport_time.isdigit() and values:
config.update({
'waitport': '{0} {1}'.format(
waitport_time, ' '.join(values)
)
})
else:
_raise_error_iface(iface, opt, ['integer [interfaces]'])
return config
def _parse_settings_eth(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['inet'] = salt.utils.odict.OrderedDict()
iface_data['inet6'] = salt.utils.odict.OrderedDict()
if enabled:
adapters[iface]['enabled'] = True
if opts.get('hotplug', False):
adapters[iface]['hotplug'] = True
if opts.get('enable_ipv6', None) and opts.get('iface_type', '') == 'vlan':
iface_data['inet6']['vlan_raw_device'] = (
re.sub(r'\.\d*', '', iface))
for addrfam in ['inet', 'inet6']:
if iface_type not in ['bridge']:
tmp_ethtool = _parse_ethtool_opts(opts, iface)
if tmp_ethtool:
ethtool = {}
for item in tmp_ethtool:
ethtool[_ETHTOOL_CONFIG_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['ethtool'] = ethtool
# return a list of sorted keys to ensure consistent order
iface_data[addrfam]['ethtool_keys'] = sorted(ethtool)
if iface_type == 'bridge':
bridging = _parse_bridge_opts(opts, iface)
if bridging:
iface_data[addrfam]['bridging'] = bridging
iface_data[addrfam]['bridging_keys'] = sorted(bridging)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'bond':
bonding = _parse_settings_bond(opts, iface)
if bonding:
iface_data[addrfam]['bonding'] = bonding
iface_data[addrfam]['bonding']['slaves'] = opts['slaves']
iface_data[addrfam]['bonding_keys'] = sorted(bonding)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'slave':
adapters[iface]['master'] = opts['master']
opts['proto'] = 'manual'
iface_data[addrfam]['master'] = adapters[iface]['master']
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'vlan':
iface_data[addrfam]['vlan_raw_device'] = re.sub(r'\.\d*', '', iface)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'pppoe':
tmp_ethtool = _parse_ethtool_pppoe_opts(opts, iface)
if tmp_ethtool:
for item in tmp_ethtool:
adapters[iface]['data'][addrfam][_DEB_CONFIG_PPPOE_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['addrfam'] = addrfam
opts.pop('mode', None)
for opt, val in opts.items():
inet = None
if opt.startswith('ipv4'):
opt = opt[4:]
inet = 'inet'
iface_data['inet']['addrfam'] = 'inet'
elif opt.startswith('ipv6'):
iface_data['inet6']['addrfam'] = 'inet6'
opt = opt[4:]
inet = 'inet6'
elif opt in ['ipaddr', 'address', 'ipaddresses', 'addresses', 'gateway', 'proto']:
iface_data['inet']['addrfam'] = 'inet'
inet = 'inet'
_opt = SALT_ATTR_TO_DEBIAN_ATTR_MAP.get(opt, opt)
_debopt = _opt.replace('-', '_')
for addrfam in ['inet', 'inet6']:
(valid, value, errmsg) = _validate_interface_option(_opt, val, addrfam=addrfam)
if not valid:
continue
if inet is None and _debopt not in iface_data[addrfam]:
iface_data[addrfam][_debopt] = value
elif inet == addrfam:
iface_data[addrfam][_debopt] = value
for opt in ['up_cmds', 'pre_up_cmds', 'post_up_cmds',
'down_cmds', 'pre_down_cmds', 'post_down_cmds']:
if opt in opts:
iface_data['inet'][opt] = opts[opt]
iface_data['inet6'][opt] = opts[opt]
# Remove incomplete/disabled inet blocks
for (addrfam, opt) in [('inet', 'enable_ipv4'), ('inet6', 'enable_ipv6')]:
if opts.get(opt, None) is False:
iface_data.pop(addrfam)
elif iface_data[addrfam].get('addrfam', '') != addrfam:
iface_data.pop(addrfam)
return adapters
def _parse_settings_source(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['sources'] = [opts['source']]
return adapters
def _parse_routes(iface, opts):
'''
Filters given options and outputs valid settings for
the route settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
result = {}
if 'routes' not in opts:
_raise_error_routes(iface, 'routes', 'List of routes')
for opt in opts:
result[opt] = opts[opt]
return result
def _write_file(iface, data, folder, pattern):
'''
Writes a file to disk
'''
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
return filename
def _write_file_routes(iface, data, folder, pattern):
'''
Writes a file to disk
'''
# ifup / ifdown is executing given folder via run-parts.
# according to run-parts man-page, only filenames with this pattern are
# executed: (^[a-zA-Z0-9_-]+$)
# In order to make the routes file work for vlan interfaces
# (default would have been in example /etc/network/if-up.d/route-bond0.12)
# these dots in the iface name need to be replaced by underscores, so it
# can be executed by run-parts
iface = iface.replace('.', '_')
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
__salt__['file.set_mode'](filename, '0755')
return filename
def _write_file_network(data, filename, create=False):
'''
Writes a file to disk
If file does not exist, only create if create
argument is True
'''
if not os.path.exists(filename) and not create:
msg = '{0} cannot be written. {0} does not exist\
and create is set to False'
msg = msg.format(filename)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
def _read_temp(data):
'''
Return what would be written to disk
'''
tout = StringIO()
tout.write(data)
tout.seek(0)
output = tout.readlines()
tout.close()
return output
def _read_temp_ifaces(iface, data):
'''
Return what would be written to disk for interfaces
'''
try:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': data})
# Return as an array so the difflib works
return [item + '\n' for item in ifcfg.split('\n')]
def _write_file_ifaces(iface, data, **settings):
'''
Writes a file to disk
'''
try:
eth_template = JINJA.get_template('debian_eth.jinja')
source_template = JINJA.get_template('debian_source.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
# Read /etc/network/interfaces into a dict
adapters = _parse_interfaces()
# Apply supplied settings over on-disk settings
adapters[iface] = data
ifcfg = ''
for adapter in adapters:
if 'type' in adapters[adapter] and adapters[adapter]['type'] == 'source':
tmp = source_template.render({'name': adapter, 'data': adapters[adapter]})
else:
tmp = eth_template.render({'name': adapter, 'data': adapters[adapter]})
ifcfg = ifcfg + tmp
if adapter == iface:
saved_ifcfg = tmp
_SEPARATE_FILE = False
if 'filename' in settings:
if not settings['filename'].startswith('/'):
filename = '{0}/{1}'.format(_DEB_NETWORK_DIR, settings['filename'])
else:
filename = settings['filename']
_SEPARATE_FILE = True
else:
if 'filename' in adapters[adapter]['data']:
filename = adapters[adapter]['data']
else:
filename = _DEB_NETWORK_FILE
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
if _SEPARATE_FILE:
fout.write(salt.utils.stringutils.to_str(saved_ifcfg))
else:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return saved_ifcfg.split('\n')
def _write_file_ppp_ifaces(iface, data):
'''
Writes a file to disk
'''
try:
template = JINJA.get_template('debian_ppp_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_ppp_eth.jinja')
return ''
adapters = _parse_interfaces()
adapters[iface] = data
ifcfg = ''
tmp = template.render({'data': adapters[iface]})
ifcfg = tmp + ifcfg
filename = _DEB_PPP_DIR + '/' + adapters[iface]['data']['inet']['provider']
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.fopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return filename
def build_bond(iface, **settings):
'''
Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb
'''
deb_major = __grains__['osrelease'][:1]
opts = _parse_settings_bond(settings, iface)
try:
template = JINJA.get_template('conf.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template conf.jinja')
return ''
data = template.render({'name': iface, 'bonding': opts})
if 'test' in settings and settings['test']:
return _read_temp(data)
_write_file(iface, data, _DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
if deb_major == '5':
for line_type in ('alias', 'options'):
cmd = ['sed', '-i', '-e', r'/^{0}\s{1}.*/d'.format(line_type, iface),
'/etc/modprobe.conf']
__salt__['cmd.run'](cmd, python_shell=False)
__salt__['file.append']('/etc/modprobe.conf', path)
# Load kernel module
__salt__['kmod.load']('bonding')
# install ifenslave-2.6
__salt__['pkg.install']('ifenslave-2.6')
return _read_file(path)
def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'vlan':
settings['vlan'] = 'yes'
__salt__['pkg.install']('vlan')
elif iface_type == 'pppoe':
settings['pppoe'] = 'yes'
if not __salt__['pkg.version']('ppp'):
inst = __salt__['pkg.install']('ppp')
elif iface_type == 'bond':
if 'slaves' not in settings:
msg = 'slaves is a required setting for bond interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'bridge':
if 'ports' not in settings:
msg = (
'ports is a required setting for bridge interfaces on Debian '
'or Ubuntu based systems'
)
log.error(msg)
raise AttributeError(msg)
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'pppoe']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
if iface_type in ['source']:
opts = _parse_settings_source(settings, iface_type, enabled, iface)
if 'test' in settings and settings['test']:
return _read_temp_ifaces(iface, opts[iface])
ifcfg = _write_file_ifaces(iface, opts[iface], **settings)
if iface_type == 'pppoe':
_write_file_ppp_ifaces(iface, opts[iface])
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg]
def build_routes(iface, **settings):
'''
Add route scripts for a network interface using up commands.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
'''
opts = _parse_routes(iface, settings)
try:
template = JINJA.get_template('route_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template route_eth.jinja')
return ''
add_routecfg = template.render(route_type='add',
routes=opts['routes'],
iface=iface)
del_routecfg = template.render(route_type='del',
routes=opts['routes'],
iface=iface)
if 'test' in settings and settings['test']:
return _read_temp(add_routecfg + del_routecfg)
filename = _write_file_routes(iface,
add_routecfg,
_DEB_NETWORK_UP_DIR,
'route-{0}')
results = _read_file(filename)
filename = _write_file_routes(iface,
del_routecfg,
_DEB_NETWORK_DOWN_DIR,
'route-{0}')
results += _read_file(filename)
return results
def down(iface, iface_type):
'''
Shutdown a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.down eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought down.
if iface_type not in ['slave', 'source']:
return __salt__['cmd.run'](['ifdown', iface])
return None
def get_bond(iface):
'''
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
'''
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
return _read_file(path)
def get_interface(iface):
'''
Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
adapters = _parse_interfaces()
if iface in adapters:
try:
if iface == 'source':
template = JINJA.get_template('debian_source.jinja')
else:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': adapters[iface]})
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg.split('\n')]
else:
return []
def up(iface, iface_type): # pylint: disable=C0103
'''
Start up a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.up eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought up.
if iface_type not in ('slave', 'source'):
return __salt__['cmd.run'](['ifup', iface])
return None
def get_network_settings():
'''
Return the contents of the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_network_settings
'''
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
settings = {}
if __salt__['service.available']('networking'):
if __salt__['service.status']('networking'):
settings['networking'] = "yes"
else:
settings['networking'] = "no"
else:
settings['networking'] = "no"
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
settings['hostname'] = hostname
settings['domainname'] = domainname
settings['searchdomain'] = searchdomain
else:
settings = _parse_current_network_settings()
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(settings)
return _read_temp(network)
def get_routes(iface):
'''
Return the routes for the interface
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0
'''
filename = os.path.join(_DEB_NETWORK_UP_DIR, 'route-{0}'.format(iface))
results = _read_file(filename)
filename = os.path.join(_DEB_NETWORK_DOWN_DIR, 'route-{0}'.format(iface))
results += _read_file(filename)
return results
def apply_network_settings(**settings):
'''
Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings
'''
if 'require_reboot' not in settings:
settings['require_reboot'] = False
if 'apply_hostname' not in settings:
settings['apply_hostname'] = False
hostname_res = True
if settings['apply_hostname'] in _CONFIG_TRUE:
if 'hostname' in settings:
hostname_res = __salt__['network.mod_hostname'](settings['hostname'])
else:
log.warning(
'The network state sls is trying to apply hostname '
'changes but no hostname is defined.'
)
hostname_res = False
res = True
if settings['require_reboot'] in _CONFIG_TRUE:
log.warning(
'The network state sls is requiring a reboot of the system to '
'properly apply network configuration.'
)
res = True
else:
stop = __salt__['service.stop']('networking')
time.sleep(2)
res = stop and __salt__['service.start']('networking')
return hostname_res and res
def build_network_settings(**settings):
'''
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
'''
changes = []
# Read current configuration and store default values
current_network_settings = _parse_current_network_settings()
# Build settings
opts = _parse_network_settings(settings, current_network_settings)
# Ubuntu has moved away from /etc/default/networking
# beginning with the 12.04 release so we disable or enable
# the networking related services on boot
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
if opts['networking'] == 'yes':
service_cmd = 'service.enable'
else:
service_cmd = 'service.disable'
if __salt__['service.available']('NetworkManager'):
__salt__[service_cmd]('NetworkManager')
if __salt__['service.available']('networking'):
__salt__[service_cmd]('networking')
else:
try:
template = JINJA.get_template('network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template network.jinja')
return ''
network = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(network)
# Write settings
_write_file_network(network, _DEB_NETWORKING_FILE, True)
# Get hostname and domain from opts
sline = opts['hostname'].split('.', 1)
opts['hostname'] = sline[0]
current_domainname = current_network_settings['domainname']
current_searchdomain = current_network_settings['searchdomain']
new_domain = False
if len(sline) > 1:
new_domainname = sline[1]
if new_domainname != current_domainname:
domainname = new_domainname
opts['domainname'] = new_domainname
new_domain = True
else:
domainname = current_domainname
opts['domainname'] = domainname
else:
domainname = current_domainname
opts['domainname'] = domainname
new_search = False
if 'search' in opts:
new_searchdomain = opts['search']
if new_searchdomain != current_searchdomain:
searchdomain = new_searchdomain
opts['searchdomain'] = new_searchdomain
new_search = True
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
# If the domain changes, then we should write the resolv.conf file.
if new_domain or new_search:
# Look for existing domain line and update if necessary
resolve = _parse_resolve()
domain_prog = re.compile(r'domain\s+')
search_prog = re.compile(r'search\s+')
new_contents = []
for item in _read_file(_DEB_RESOLV_FILE):
if domain_prog.match(item):
item = 'domain {0}'.format(domainname)
elif search_prog.match(item):
item = 'search {0}'.format(searchdomain)
new_contents.append(item)
# A domain line didn't exist so we'll add one in
# with the new domainname
if 'domain' not in resolve:
new_contents.insert(0, 'domain {0}' . format(domainname))
# A search line didn't exist so we'll add one in
# with the new search domain
if 'search' not in resolve:
new_contents.insert('domain' in resolve, 'search {0}'.format(searchdomain))
new_resolv = '\n'.join(new_contents)
# Write /etc/resolv.conf
if not ('test' in settings and settings['test']):
_write_file_network(new_resolv, _DEB_RESOLV_FILE)
# used for returning the results back
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(opts)
changes.extend(_read_temp(network))
return changes
|
saltstack/salt
|
salt/modules/debian_ip.py
|
_parse_routes
|
python
|
def _parse_routes(iface, opts):
'''
Filters given options and outputs valid settings for
the route settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
result = {}
if 'routes' not in opts:
_raise_error_routes(iface, 'routes', 'List of routes')
for opt in opts:
result[opt] = opts[opt]
return result
|
Filters given options and outputs valid settings for
the route settings file.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_ip.py#L1378-L1392
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def _raise_error_routes(iface, option, expected):\n '''\n Log and raise an error with a logical formatted message.\n '''\n msg = _error_msg_routes(iface, option, expected)\n log.error(msg)\n raise AttributeError(msg)\n"
] |
# -*- coding: utf-8 -*-
'''
The networking module for Debian-based distros
References:
* http://www.debian.org/doc/manuals/debian-reference/ch05.en.html
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import functools
import logging
import os.path
import os
import re
import time
# Import third party libs
import jinja2
import jinja2.exceptions
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error,no-name-in-module
# Import salt libs
import salt.utils.dns
import salt.utils.files
import salt.utils.odict
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.validate.net
# Set up logging
log = logging.getLogger(__name__)
# Set up template environment
JINJA = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'debian_ip')
)
)
# Define the module's virtual name
__virtualname__ = 'ip'
def __virtual__():
'''
Confine this module to Debian-based distros
'''
if __grains__['os_family'] == 'Debian':
return __virtualname__
return (False, 'The debian_ip module could not be loaded: '
'unsupported OS family')
_ETHTOOL_CONFIG_OPTS = {
'speed': 'link-speed',
'duplex': 'link-duplex',
'autoneg': 'ethernet-autoneg',
'ethernet-port': 'ethernet-port',
'wol': 'ethernet-wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'rx': 'offload-rx',
'tx': 'offload-tx',
'sg': 'offload-sg',
'tso': 'offload-tso',
'ufo': 'offload-ufo',
'gso': 'offload-gso',
'gro': 'offload-gro',
'lro': 'offload-lro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_REV_ETHTOOL_CONFIG_OPTS = {
'link-speed': 'speed',
'link-duplex': 'duplex',
'ethernet-autoneg': 'autoneg',
'ethernet-port': 'ethernet-port',
'ethernet-wol': 'wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'offload-rx': 'rx',
'offload-tx': 'tx',
'offload-sg': 'sg',
'offload-tso': 'tso',
'offload-ufo': 'ufo',
'offload-gso': 'gso',
'offload-lro': 'lro',
'offload-gro': 'gro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_DEB_CONFIG_PPPOE_OPTS = {
'user': 'user',
'password': 'password',
'provider': 'provider',
'pppoe_iface': 'pppoe_iface',
'noipdefault': 'noipdefault',
'usepeerdns': 'usepeerdns',
'defaultroute': 'defaultroute',
'holdoff': 'holdoff',
'maxfail': 'maxfail',
'hide-password': 'hide-password',
'lcp-echo-interval': 'lcp-echo-interval',
'lcp-echo-failure': 'lcp-echo-failure',
'connect': 'connect',
'noauth': 'noauth',
'persist': 'persist',
'mtu': 'mtu',
'noaccomp': 'noaccomp',
'linkname': 'linkname',
}
_DEB_ROUTES_FILE = '/etc/network/routes'
_DEB_NETWORK_FILE = '/etc/network/interfaces'
_DEB_NETWORK_DIR = '/etc/network/interfaces.d/'
_DEB_NETWORK_UP_DIR = '/etc/network/if-up.d/'
_DEB_NETWORK_DOWN_DIR = '/etc/network/if-down.d/'
_DEB_NETWORK_CONF_FILES = '/etc/modprobe.d/'
_DEB_NETWORKING_FILE = '/etc/default/networking'
_DEB_HOSTNAME_FILE = '/etc/hostname'
_DEB_RESOLV_FILE = '/etc/resolv.conf'
_DEB_PPP_DIR = '/etc/ppp/peers/'
_CONFIG_TRUE = ['yes', 'on', 'true', '1', True]
_CONFIG_FALSE = ['no', 'off', 'false', '0', False]
_IFACE_TYPES = [
'eth', 'bond', 'alias', 'clone',
'ipsec', 'dialup', 'bridge', 'slave',
'vlan', 'pppoe', 'source',
]
def _error_msg_iface(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, '|'.join(str(e) for e in expected))
def _error_msg_routes(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, expected)
def _log_default_iface(iface, opt, value):
log.info(
'Using default option -- Interface: %s Option: %s Value: %s',
iface, opt, value
)
def _error_msg_network(option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]'
return msg.format(option, '|'.join(str(e) for e in expected))
def _log_default_network(opt, value):
log.info('Using existing setting -- Setting: %s Value: %s', opt, value)
def _raise_error_iface(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_iface(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_network(option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_network(option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_routes(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_routes(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _read_file(path):
'''
Reads and returns the contents of a text file
'''
try:
with salt.utils.files.flopen(path, 'rb') as contents:
return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]
except (OSError, IOError):
return ''
def _parse_resolve():
'''
Parse /etc/resolv.conf
'''
return salt.utils.dns.parse_resolv(_DEB_RESOLV_FILE)
def _parse_domainname():
'''
Parse /etc/resolv.conf and return domainname
'''
return _parse_resolve().get('domain', '')
def _parse_searchdomain():
'''
Parse /etc/resolv.conf and return searchdomain
'''
return _parse_resolve().get('search', '')
def _parse_hostname():
'''
Parse /etc/hostname and return hostname
'''
contents = _read_file(_DEB_HOSTNAME_FILE)
if contents:
return contents[0].split('\n')[0]
else:
return ''
def _parse_current_network_settings():
'''
Parse /etc/default/networking and return current configuration
'''
opts = salt.utils.odict.OrderedDict()
opts['networking'] = ''
if os.path.isfile(_DEB_NETWORKING_FILE):
with salt.utils.files.fopen(_DEB_NETWORKING_FILE) as contents:
for line in contents:
salt.utils.stringutils.to_unicode(line)
if line.startswith('#'):
continue
elif line.startswith('CONFIGURE_INTERFACES'):
opts['networking'] = line.split('=', 1)[1].strip()
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
opts['hostname'] = hostname
opts['domainname'] = domainname
opts['searchdomain'] = searchdomain
return opts
# def __validator_func(value):
# return (valid: True/False, (transformed) value, error message)
def __ipv4_quad(value):
'''validate an IPv4 address'''
return (salt.utils.validate.net.ipv4_addr(value), value,
'dotted IPv4 address')
def __ipv6(value):
'''validate an IPv6 address'''
return (salt.utils.validate.net.ipv6_addr(value), value,
'IPv6 address')
def __mac(value):
'''validate a mac address'''
return (salt.utils.validate.net.mac(value), value,
'MAC address')
def __anything(value):
return (True, value, None)
def __int(value):
'''validate an integer'''
valid, _value = False, value
try:
_value = int(value)
valid = True
except ValueError:
pass
return (valid, _value, 'integer')
def __float(value):
'''validate a float'''
valid, _value = False, value
try:
_value = float(value)
valid = True
except ValueError:
pass
return (valid, _value, 'float')
def __ipv4_netmask(value):
'''validate an IPv4 dotted quad or integer CIDR netmask'''
valid, errmsg = False, 'dotted quad or integer CIDR (0->32)'
valid, value, _ = __int(value)
if not (valid and 0 <= value <= 32):
valid = salt.utils.validate.net.netmask(value)
return (valid, value, errmsg)
def __ipv6_netmask(value):
'''validate an IPv6 integer netmask'''
valid, errmsg = False, 'IPv6 netmask (0->128)'
valid, value, _ = __int(value)
valid = (valid and 0 <= value <= 128)
return (valid, value, errmsg)
def __within2(value, within=None, errmsg=None, dtype=None):
'''validate that a value is in ``within`` and optionally a ``dtype``'''
valid, _value = False, value
if dtype:
try:
_value = dtype(value) # TODO: this is a bit loose when dtype is a class
valid = _value in within
except ValueError:
pass
else:
valid = _value in within
if errmsg is None:
if dtype:
typename = getattr(dtype, '__name__',
hasattr(dtype, '__class__')
and getattr(dtype.__class__, 'name', dtype))
errmsg = '{0} within \'{1}\''.format(typename, within)
else:
errmsg = 'within \'{0}\''.format(within)
return (valid, _value, errmsg)
def __within(within=None, errmsg=None, dtype=None):
return functools.partial(__within2, within=within,
errmsg=errmsg, dtype=dtype)
def __space_delimited_list(value):
'''validate that a value contains one or more space-delimited values'''
if isinstance(value, six.string_types):
value = value.strip().split()
if hasattr(value, '__iter__') and value != []:
return (True, value, 'space-delimited string')
else:
return (False, value, '{0} is not a valid space-delimited value.\n'.format(value))
SALT_ATTR_TO_DEBIAN_ATTR_MAP = {
'dns': 'dns-nameservers',
'search': 'dns-search',
'hwaddr': 'hwaddress', # TODO: this limits bootp functionality
'ipaddr': 'address',
'ipaddrs': 'addresses',
}
DEBIAN_ATTR_TO_SALT_ATTR_MAP = dict(
(v, k) for (k, v) in six.iteritems(SALT_ATTR_TO_DEBIAN_ATTR_MAP))
# TODO
DEBIAN_ATTR_TO_SALT_ATTR_MAP['address'] = 'address'
DEBIAN_ATTR_TO_SALT_ATTR_MAP['hwaddress'] = 'hwaddress'
IPV4_VALID_PROTO = ['bootp', 'dhcp', 'static', 'manual', 'loopback', 'ppp']
IPV4_ATTR_MAP = {
'proto': __within(IPV4_VALID_PROTO, dtype=six.text_type),
# ipv4 static & manual
'address': __ipv4_quad,
'addresses': __anything,
'netmask': __ipv4_netmask,
'broadcast': __ipv4_quad,
'metric': __int,
'gateway': __ipv4_quad, # supports a colon-delimited list
'pointopoint': __ipv4_quad,
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'link', 'host'], dtype=six.text_type),
# dhcp
'hostname': __anything,
'leasehours': __int,
'leasetime': __int,
'vendor': __anything,
'client': __anything,
# bootp
'bootfile': __anything,
'server': __ipv4_quad,
'hwaddr': __mac,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'dstaddr': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# bond
'slaves': __anything,
# ppp
'provider': __anything,
'unit': __int,
'options': __anything,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
#
'network': __anything, # i don't know what this is
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
IPV6_VALID_PROTO = ['auto', 'loopback', 'static', 'manual',
'dhcp', 'v4tunnel', '6to4']
IPV6_ATTR_MAP = {
'proto': __within(IPV6_VALID_PROTO),
# ipv6 static & manual
'address': __ipv6,
'addresses': __anything,
'netmask': __ipv6_netmask,
'broadcast': __ipv6,
'gateway': __ipv6, # supports a colon-delimited list
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'site', 'link', 'host'], dtype=six.text_type),
# inet6 auto
'privext': __within([0, 1, 2], dtype=int),
'dhcp': __within([0, 1], dtype=int),
# inet6 static & manual & dhcp
'media': __anything,
'accept_ra': __within([0, 1], dtype=int),
'autoconf': __within([0, 1], dtype=int),
'preferred-lifetime': __int,
'dad-attempts': __int, # 0 to disable
'dad-interval': __float,
# bond
'slaves': __anything,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
WIRELESS_ATTR_MAP = {
'wireless-essid': __anything,
'wireless-mode': __anything, # TODO
'wpa-ap-scan': __within([0, 1, 2], dtype=int), # TODO
'wpa-conf': __anything,
'wpa-driver': __anything,
'wpa-group': __anything,
'wpa-key-mgmt': __anything,
'wpa-pairwise': __anything,
'wpa-psk': __anything,
'wpa-proto': __anything, # partial(__within,
'wpa-roam': __anything,
'wpa-ssid': __anything, # TODO
}
ATTRMAPS = {
'inet': [IPV4_ATTR_MAP, WIRELESS_ATTR_MAP],
'inet6': [IPV6_ATTR_MAP, WIRELESS_ATTR_MAP]
}
def _validate_interface_option(attr, value, addrfam='inet'):
'''lookup the validation function for a [addrfam][attr] and
return the results
:param attr: attribute name
:param value: raw setting value
:param addrfam: address family (inet, inet6,
'''
valid, _value, errmsg = False, value, 'Unknown validator'
attrmaps = ATTRMAPS.get(addrfam, [])
for attrmap in attrmaps:
if attr in attrmap:
validate_func = attrmap[attr]
(valid, _value, errmsg) = validate_func(value)
break
return (valid, _value, errmsg)
def _attrmaps_contain_attr(attr):
return (
attr in WIRELESS_ATTR_MAP or
attr in IPV4_ATTR_MAP or
attr in IPV6_ATTR_MAP)
def _parse_interfaces(interface_files=None):
'''
Parse /etc/network/interfaces and return current configured interfaces
'''
if interface_files is None:
interface_files = []
# Add this later.
if os.path.exists(_DEB_NETWORK_DIR):
interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]
if os.path.isfile(_DEB_NETWORK_FILE):
interface_files.insert(0, _DEB_NETWORK_FILE)
adapters = salt.utils.odict.OrderedDict()
method = -1
for interface_file in interface_files:
with salt.utils.files.fopen(interface_file) as interfaces:
# This ensures iface_dict exists, but does not ensure we're not reading a new interface.
iface_dict = {}
for line in interfaces:
line = salt.utils.stringutils.to_unicode(line)
# Identify the clauses by the first word of each line.
# Go to the next line if the current line is a comment
# or all spaces.
if line.lstrip().startswith('#') or line.isspace():
continue
# Parse the iface clause
if line.startswith('iface'):
sline = line.split()
if len(sline) != 4:
msg = 'Interface file malformed: {0}.'
msg = msg.format(sline)
log.error(msg)
raise AttributeError(msg)
iface_name = sline[1]
addrfam = sline[2]
method = sline[3]
# Create item in dict, if not already there
if iface_name not in adapters:
adapters[iface_name] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters[iface_name]:
adapters[iface_name]['data'] = salt.utils.odict.OrderedDict()
if addrfam not in adapters[iface_name]['data']:
adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict()
iface_dict = adapters[iface_name]['data'][addrfam]
iface_dict['addrfam'] = addrfam
iface_dict['proto'] = method
iface_dict['filename'] = interface_file
# Parse the detail clauses.
elif line[0].isspace():
sline = line.split()
# conf file attr: dns-nameservers
# salt states.network attr: dns
attr, valuestr = line.rstrip().split(None, 1)
if _attrmaps_contain_attr(attr):
if '-' in attr:
attrname = attr.replace('-', '_')
else:
attrname = attr
(valid, value, errmsg) = _validate_interface_option(
attr, valuestr, addrfam)
if attrname == 'address' and 'address' in iface_dict:
if 'addresses' not in iface_dict:
iface_dict['addresses'] = []
iface_dict['addresses'].append(value)
else:
iface_dict[attrname] = value
elif attr in _REV_ETHTOOL_CONFIG_OPTS:
if 'ethtool' not in iface_dict:
iface_dict['ethtool'] = salt.utils.odict.OrderedDict()
iface_dict['ethtool'][attr] = valuestr
elif attr.startswith('bond'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bonding' not in iface_dict:
iface_dict['bonding'] = salt.utils.odict.OrderedDict()
iface_dict['bonding'][opt] = valuestr
elif attr.startswith('bridge'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bridging' not in iface_dict:
iface_dict['bridging'] = salt.utils.odict.OrderedDict()
iface_dict['bridging'][opt] = valuestr
elif attr in ['up', 'pre-up', 'post-up',
'down', 'pre-down', 'post-down']:
cmd = valuestr
cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr))
if cmd_key not in iface_dict:
iface_dict[cmd_key] = []
iface_dict[cmd_key].append(cmd)
elif line.startswith('auto'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['enabled'] = True
elif line.startswith('allow-hotplug'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['hotplug'] = True
elif line.startswith('source'):
if 'source' not in adapters:
adapters['source'] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters['source']:
adapters['source']['data'] = salt.utils.odict.OrderedDict()
adapters['source']['data']['sources'] = []
adapters['source']['data']['sources'].append(line.split()[1])
# Return a sorted list of the keys for bond, bridge and ethtool options to
# ensure a consistent order
for iface_name in adapters:
if iface_name == 'source':
continue
if 'data' not in adapters[iface_name]:
msg = 'Interface file malformed for interface: {0}.'.format(iface_name)
log.error(msg)
adapters.pop(iface_name)
continue
for opt in ['ethtool', 'bonding', 'bridging']:
for inet in ['inet', 'inet6']:
if inet in adapters[iface_name]['data']:
if opt in adapters[iface_name]['data'][inet]:
opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys())
adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys
return adapters
def _parse_ethtool_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
if 'autoneg' in opts:
if opts['autoneg'] in _CONFIG_TRUE:
config.update({'autoneg': 'on'})
elif opts['autoneg'] in _CONFIG_FALSE:
config.update({'autoneg': 'off'})
else:
_raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE)
if 'duplex' in opts:
valid = ['full', 'half']
if opts['duplex'] in valid:
config.update({'duplex': opts['duplex']})
else:
_raise_error_iface(iface, 'duplex', valid)
if 'speed' in opts:
valid = ['10', '100', '1000', '10000']
if six.text_type(opts['speed']) in valid:
config.update({'speed': opts['speed']})
else:
_raise_error_iface(iface, opts['speed'], valid)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'on'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'off'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_ethtool_pppoe_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
for opt in _DEB_CONFIG_PPPOE_OPTS:
if opt in opts:
config[opt] = opts[opt]
if 'provider' in opts and not opts['provider']:
_raise_error_iface(iface, 'provider', _CONFIG_TRUE + _CONFIG_FALSE)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('noipdefault', 'usepeerdns', 'defaultroute', 'hide-password', 'noauth', 'persist', 'noaccomp'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'True'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'False'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_settings_bond(opts, iface):
'''
Filters given options and outputs valid settings for requested
operation. If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond_def = {
# 803.ad aggregation selection logic
# 0 for stable (default)
# 1 for bandwidth
# 2 for count
'ad_select': '0',
# Max number of transmit queues (default = 16)
'tx_queues': '16',
# Link monitoring in milliseconds. Most NICs support this
'miimon': '100',
# ARP interval in milliseconds
'arp_interval': '250',
# Delay before considering link down in milliseconds (miimon * 2)
'downdelay': '200',
# lacp_rate 0: Slow - every 30 seconds
# lacp_rate 1: Fast - every 1 second
'lacp_rate': '0',
# Max bonds for this driver
'max_bonds': '1',
# Specifies the time, in milliseconds, to wait before
# enabling a slave after a link recovery has been
# detected. Only used with miimon.
'updelay': '0',
# Used with miimon.
# On: driver sends mii
# Off: ethtool sends mii
'use_carrier': 'on',
# Default. Don't change unless you know what you are doing.
'xmit_hash_policy': 'layer2',
}
if opts['mode'] in ['balance-rr', '0']:
log.info('Device: %s Bonding Mode: load balancing (round-robin)', iface)
return _parse_settings_bond_0(opts, iface, bond_def)
elif opts['mode'] in ['active-backup', '1']:
log.info('Device: %s Bonding Mode: fault-tolerance (active-backup)', iface)
return _parse_settings_bond_1(opts, iface, bond_def)
elif opts['mode'] in ['balance-xor', '2']:
log.info('Device: %s Bonding Mode: load balancing (xor)', iface)
return _parse_settings_bond_2(opts, iface, bond_def)
elif opts['mode'] in ['broadcast', '3']:
log.info('Device: %s Bonding Mode: fault-tolerance (broadcast)', iface)
return _parse_settings_bond_3(opts, iface, bond_def)
elif opts['mode'] in ['802.3ad', '4']:
log.info('Device: %s Bonding Mode: IEEE 802.3ad Dynamic link '
'aggregation', iface)
return _parse_settings_bond_4(opts, iface, bond_def)
elif opts['mode'] in ['balance-tlb', '5']:
log.info('Device: %s Bonding Mode: transmit load balancing', iface)
return _parse_settings_bond_5(opts, iface, bond_def)
elif opts['mode'] in ['balance-alb', '6']:
log.info('Device: %s Bonding Mode: adaptive load balancing', iface)
return _parse_settings_bond_6(opts, iface, bond_def)
else:
valid = [
'0', '1', '2', '3', '4', '5', '6',
'balance-rr', 'active-backup', 'balance-xor',
'broadcast', '802.3ad', 'balance-tlb', 'balance-alb'
]
_raise_error_iface(iface, 'mode', valid)
def _parse_settings_bond_0(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond0.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '0'}
# ARP targets in n.n.n.n form
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
return bond
def _parse_settings_bond_1(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '1'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
if not (__grains__['os'] == "Ubuntu" and __grains__['osrelease_info'][0] >= 16):
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_2(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond2.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '2'}
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_3(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond3.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '3'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_4(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond4.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '4'}
for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']:
if binding in opts:
if binding == 'lacp_rate':
if opts[binding] == 'fast':
opts.update({binding: '1'})
if opts[binding] == 'slow':
opts.update({binding: '0'})
valid = ['fast', '1', 'slow', '0']
else:
valid = ['integer']
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, valid)
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_5(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond5.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '5'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_settings_bond_6(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond6.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '6'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_bridge_opts(opts, iface):
'''
Filters given options and outputs valid settings for BRIDGING_OPTS
If an option has a value that is not expected, this
function will log the Interface, Setting and what was expected.
'''
config = {}
if 'ports' in opts:
if isinstance(opts['ports'], list):
opts['ports'] = ' '.join(opts['ports'])
config.update({'ports': opts['ports']})
for opt in ['ageing', 'fd', 'gcint', 'hello', 'maxage']:
if opt in opts:
try:
float(opts[opt])
config.update({opt: opts[opt]})
except ValueError:
_raise_error_iface(iface, opt, ['float'])
for opt in ['bridgeprio', 'maxwait']:
if opt in opts:
if isinstance(opts[opt], int):
config.update({opt: opts[opt]})
else:
_raise_error_iface(iface, opt, ['integer'])
if 'hw' in opts:
# match 12 hex digits with either : or - as separators between pairs
if re.match('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$',
opts['hw'].lower()):
config.update({'hw': opts['hw']})
else:
_raise_error_iface(iface, 'hw', ['valid MAC address'])
for opt in ['pathcost', 'portprio']:
if opt in opts:
try:
port, cost_or_prio = opts[opt].split()
int(cost_or_prio)
config.update({opt: '{0} {1}'.format(port, cost_or_prio)})
except ValueError:
_raise_error_iface(iface, opt, ['interface integer'])
if 'stp' in opts:
if opts['stp'] in _CONFIG_TRUE:
config.update({'stp': 'on'})
elif opts['stp'] in _CONFIG_FALSE:
config.update({'stp': 'off'})
else:
_raise_error_iface(iface, 'stp', _CONFIG_TRUE + _CONFIG_FALSE)
if 'waitport' in opts:
if isinstance(opts['waitport'], int):
config.update({'waitport': opts['waitport']})
else:
values = opts['waitport'].split()
waitport_time = values.pop(0)
if waitport_time.isdigit() and values:
config.update({
'waitport': '{0} {1}'.format(
waitport_time, ' '.join(values)
)
})
else:
_raise_error_iface(iface, opt, ['integer [interfaces]'])
return config
def _parse_settings_eth(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['inet'] = salt.utils.odict.OrderedDict()
iface_data['inet6'] = salt.utils.odict.OrderedDict()
if enabled:
adapters[iface]['enabled'] = True
if opts.get('hotplug', False):
adapters[iface]['hotplug'] = True
if opts.get('enable_ipv6', None) and opts.get('iface_type', '') == 'vlan':
iface_data['inet6']['vlan_raw_device'] = (
re.sub(r'\.\d*', '', iface))
for addrfam in ['inet', 'inet6']:
if iface_type not in ['bridge']:
tmp_ethtool = _parse_ethtool_opts(opts, iface)
if tmp_ethtool:
ethtool = {}
for item in tmp_ethtool:
ethtool[_ETHTOOL_CONFIG_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['ethtool'] = ethtool
# return a list of sorted keys to ensure consistent order
iface_data[addrfam]['ethtool_keys'] = sorted(ethtool)
if iface_type == 'bridge':
bridging = _parse_bridge_opts(opts, iface)
if bridging:
iface_data[addrfam]['bridging'] = bridging
iface_data[addrfam]['bridging_keys'] = sorted(bridging)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'bond':
bonding = _parse_settings_bond(opts, iface)
if bonding:
iface_data[addrfam]['bonding'] = bonding
iface_data[addrfam]['bonding']['slaves'] = opts['slaves']
iface_data[addrfam]['bonding_keys'] = sorted(bonding)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'slave':
adapters[iface]['master'] = opts['master']
opts['proto'] = 'manual'
iface_data[addrfam]['master'] = adapters[iface]['master']
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'vlan':
iface_data[addrfam]['vlan_raw_device'] = re.sub(r'\.\d*', '', iface)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'pppoe':
tmp_ethtool = _parse_ethtool_pppoe_opts(opts, iface)
if tmp_ethtool:
for item in tmp_ethtool:
adapters[iface]['data'][addrfam][_DEB_CONFIG_PPPOE_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['addrfam'] = addrfam
opts.pop('mode', None)
for opt, val in opts.items():
inet = None
if opt.startswith('ipv4'):
opt = opt[4:]
inet = 'inet'
iface_data['inet']['addrfam'] = 'inet'
elif opt.startswith('ipv6'):
iface_data['inet6']['addrfam'] = 'inet6'
opt = opt[4:]
inet = 'inet6'
elif opt in ['ipaddr', 'address', 'ipaddresses', 'addresses', 'gateway', 'proto']:
iface_data['inet']['addrfam'] = 'inet'
inet = 'inet'
_opt = SALT_ATTR_TO_DEBIAN_ATTR_MAP.get(opt, opt)
_debopt = _opt.replace('-', '_')
for addrfam in ['inet', 'inet6']:
(valid, value, errmsg) = _validate_interface_option(_opt, val, addrfam=addrfam)
if not valid:
continue
if inet is None and _debopt not in iface_data[addrfam]:
iface_data[addrfam][_debopt] = value
elif inet == addrfam:
iface_data[addrfam][_debopt] = value
for opt in ['up_cmds', 'pre_up_cmds', 'post_up_cmds',
'down_cmds', 'pre_down_cmds', 'post_down_cmds']:
if opt in opts:
iface_data['inet'][opt] = opts[opt]
iface_data['inet6'][opt] = opts[opt]
# Remove incomplete/disabled inet blocks
for (addrfam, opt) in [('inet', 'enable_ipv4'), ('inet6', 'enable_ipv6')]:
if opts.get(opt, None) is False:
iface_data.pop(addrfam)
elif iface_data[addrfam].get('addrfam', '') != addrfam:
iface_data.pop(addrfam)
return adapters
def _parse_settings_source(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['sources'] = [opts['source']]
return adapters
def _parse_network_settings(opts, current):
'''
Filters given options and outputs valid settings for
the global network settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
current = dict((k.lower(), v) for (k, v) in six.iteritems(current))
result = {}
valid = _CONFIG_TRUE + _CONFIG_FALSE
if 'enabled' not in opts:
try:
opts['networking'] = current['networking']
_log_default_network('networking', current['networking'])
except ValueError:
_raise_error_network('networking', valid)
else:
opts['networking'] = opts['enabled']
if opts['networking'] in valid:
if opts['networking'] in _CONFIG_TRUE:
result['networking'] = 'yes'
elif opts['networking'] in _CONFIG_FALSE:
result['networking'] = 'no'
else:
_raise_error_network('networking', valid)
if 'hostname' not in opts:
try:
opts['hostname'] = current['hostname']
_log_default_network('hostname', current['hostname'])
except ValueError:
_raise_error_network('hostname', ['server1.example.com'])
if opts['hostname']:
result['hostname'] = opts['hostname']
else:
_raise_error_network('hostname', ['server1.example.com'])
if 'search' in opts:
result['search'] = opts['search']
return result
def _write_file(iface, data, folder, pattern):
'''
Writes a file to disk
'''
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
return filename
def _write_file_routes(iface, data, folder, pattern):
'''
Writes a file to disk
'''
# ifup / ifdown is executing given folder via run-parts.
# according to run-parts man-page, only filenames with this pattern are
# executed: (^[a-zA-Z0-9_-]+$)
# In order to make the routes file work for vlan interfaces
# (default would have been in example /etc/network/if-up.d/route-bond0.12)
# these dots in the iface name need to be replaced by underscores, so it
# can be executed by run-parts
iface = iface.replace('.', '_')
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
__salt__['file.set_mode'](filename, '0755')
return filename
def _write_file_network(data, filename, create=False):
'''
Writes a file to disk
If file does not exist, only create if create
argument is True
'''
if not os.path.exists(filename) and not create:
msg = '{0} cannot be written. {0} does not exist\
and create is set to False'
msg = msg.format(filename)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
def _read_temp(data):
'''
Return what would be written to disk
'''
tout = StringIO()
tout.write(data)
tout.seek(0)
output = tout.readlines()
tout.close()
return output
def _read_temp_ifaces(iface, data):
'''
Return what would be written to disk for interfaces
'''
try:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': data})
# Return as an array so the difflib works
return [item + '\n' for item in ifcfg.split('\n')]
def _write_file_ifaces(iface, data, **settings):
'''
Writes a file to disk
'''
try:
eth_template = JINJA.get_template('debian_eth.jinja')
source_template = JINJA.get_template('debian_source.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
# Read /etc/network/interfaces into a dict
adapters = _parse_interfaces()
# Apply supplied settings over on-disk settings
adapters[iface] = data
ifcfg = ''
for adapter in adapters:
if 'type' in adapters[adapter] and adapters[adapter]['type'] == 'source':
tmp = source_template.render({'name': adapter, 'data': adapters[adapter]})
else:
tmp = eth_template.render({'name': adapter, 'data': adapters[adapter]})
ifcfg = ifcfg + tmp
if adapter == iface:
saved_ifcfg = tmp
_SEPARATE_FILE = False
if 'filename' in settings:
if not settings['filename'].startswith('/'):
filename = '{0}/{1}'.format(_DEB_NETWORK_DIR, settings['filename'])
else:
filename = settings['filename']
_SEPARATE_FILE = True
else:
if 'filename' in adapters[adapter]['data']:
filename = adapters[adapter]['data']
else:
filename = _DEB_NETWORK_FILE
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
if _SEPARATE_FILE:
fout.write(salt.utils.stringutils.to_str(saved_ifcfg))
else:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return saved_ifcfg.split('\n')
def _write_file_ppp_ifaces(iface, data):
'''
Writes a file to disk
'''
try:
template = JINJA.get_template('debian_ppp_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_ppp_eth.jinja')
return ''
adapters = _parse_interfaces()
adapters[iface] = data
ifcfg = ''
tmp = template.render({'data': adapters[iface]})
ifcfg = tmp + ifcfg
filename = _DEB_PPP_DIR + '/' + adapters[iface]['data']['inet']['provider']
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.fopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return filename
def build_bond(iface, **settings):
'''
Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb
'''
deb_major = __grains__['osrelease'][:1]
opts = _parse_settings_bond(settings, iface)
try:
template = JINJA.get_template('conf.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template conf.jinja')
return ''
data = template.render({'name': iface, 'bonding': opts})
if 'test' in settings and settings['test']:
return _read_temp(data)
_write_file(iface, data, _DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
if deb_major == '5':
for line_type in ('alias', 'options'):
cmd = ['sed', '-i', '-e', r'/^{0}\s{1}.*/d'.format(line_type, iface),
'/etc/modprobe.conf']
__salt__['cmd.run'](cmd, python_shell=False)
__salt__['file.append']('/etc/modprobe.conf', path)
# Load kernel module
__salt__['kmod.load']('bonding')
# install ifenslave-2.6
__salt__['pkg.install']('ifenslave-2.6')
return _read_file(path)
def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'vlan':
settings['vlan'] = 'yes'
__salt__['pkg.install']('vlan')
elif iface_type == 'pppoe':
settings['pppoe'] = 'yes'
if not __salt__['pkg.version']('ppp'):
inst = __salt__['pkg.install']('ppp')
elif iface_type == 'bond':
if 'slaves' not in settings:
msg = 'slaves is a required setting for bond interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'bridge':
if 'ports' not in settings:
msg = (
'ports is a required setting for bridge interfaces on Debian '
'or Ubuntu based systems'
)
log.error(msg)
raise AttributeError(msg)
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'pppoe']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
if iface_type in ['source']:
opts = _parse_settings_source(settings, iface_type, enabled, iface)
if 'test' in settings and settings['test']:
return _read_temp_ifaces(iface, opts[iface])
ifcfg = _write_file_ifaces(iface, opts[iface], **settings)
if iface_type == 'pppoe':
_write_file_ppp_ifaces(iface, opts[iface])
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg]
def build_routes(iface, **settings):
'''
Add route scripts for a network interface using up commands.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
'''
opts = _parse_routes(iface, settings)
try:
template = JINJA.get_template('route_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template route_eth.jinja')
return ''
add_routecfg = template.render(route_type='add',
routes=opts['routes'],
iface=iface)
del_routecfg = template.render(route_type='del',
routes=opts['routes'],
iface=iface)
if 'test' in settings and settings['test']:
return _read_temp(add_routecfg + del_routecfg)
filename = _write_file_routes(iface,
add_routecfg,
_DEB_NETWORK_UP_DIR,
'route-{0}')
results = _read_file(filename)
filename = _write_file_routes(iface,
del_routecfg,
_DEB_NETWORK_DOWN_DIR,
'route-{0}')
results += _read_file(filename)
return results
def down(iface, iface_type):
'''
Shutdown a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.down eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought down.
if iface_type not in ['slave', 'source']:
return __salt__['cmd.run'](['ifdown', iface])
return None
def get_bond(iface):
'''
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
'''
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
return _read_file(path)
def get_interface(iface):
'''
Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
adapters = _parse_interfaces()
if iface in adapters:
try:
if iface == 'source':
template = JINJA.get_template('debian_source.jinja')
else:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': adapters[iface]})
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg.split('\n')]
else:
return []
def up(iface, iface_type): # pylint: disable=C0103
'''
Start up a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.up eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought up.
if iface_type not in ('slave', 'source'):
return __salt__['cmd.run'](['ifup', iface])
return None
def get_network_settings():
'''
Return the contents of the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_network_settings
'''
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
settings = {}
if __salt__['service.available']('networking'):
if __salt__['service.status']('networking'):
settings['networking'] = "yes"
else:
settings['networking'] = "no"
else:
settings['networking'] = "no"
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
settings['hostname'] = hostname
settings['domainname'] = domainname
settings['searchdomain'] = searchdomain
else:
settings = _parse_current_network_settings()
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(settings)
return _read_temp(network)
def get_routes(iface):
'''
Return the routes for the interface
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0
'''
filename = os.path.join(_DEB_NETWORK_UP_DIR, 'route-{0}'.format(iface))
results = _read_file(filename)
filename = os.path.join(_DEB_NETWORK_DOWN_DIR, 'route-{0}'.format(iface))
results += _read_file(filename)
return results
def apply_network_settings(**settings):
'''
Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings
'''
if 'require_reboot' not in settings:
settings['require_reboot'] = False
if 'apply_hostname' not in settings:
settings['apply_hostname'] = False
hostname_res = True
if settings['apply_hostname'] in _CONFIG_TRUE:
if 'hostname' in settings:
hostname_res = __salt__['network.mod_hostname'](settings['hostname'])
else:
log.warning(
'The network state sls is trying to apply hostname '
'changes but no hostname is defined.'
)
hostname_res = False
res = True
if settings['require_reboot'] in _CONFIG_TRUE:
log.warning(
'The network state sls is requiring a reboot of the system to '
'properly apply network configuration.'
)
res = True
else:
stop = __salt__['service.stop']('networking')
time.sleep(2)
res = stop and __salt__['service.start']('networking')
return hostname_res and res
def build_network_settings(**settings):
'''
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
'''
changes = []
# Read current configuration and store default values
current_network_settings = _parse_current_network_settings()
# Build settings
opts = _parse_network_settings(settings, current_network_settings)
# Ubuntu has moved away from /etc/default/networking
# beginning with the 12.04 release so we disable or enable
# the networking related services on boot
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
if opts['networking'] == 'yes':
service_cmd = 'service.enable'
else:
service_cmd = 'service.disable'
if __salt__['service.available']('NetworkManager'):
__salt__[service_cmd]('NetworkManager')
if __salt__['service.available']('networking'):
__salt__[service_cmd]('networking')
else:
try:
template = JINJA.get_template('network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template network.jinja')
return ''
network = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(network)
# Write settings
_write_file_network(network, _DEB_NETWORKING_FILE, True)
# Get hostname and domain from opts
sline = opts['hostname'].split('.', 1)
opts['hostname'] = sline[0]
current_domainname = current_network_settings['domainname']
current_searchdomain = current_network_settings['searchdomain']
new_domain = False
if len(sline) > 1:
new_domainname = sline[1]
if new_domainname != current_domainname:
domainname = new_domainname
opts['domainname'] = new_domainname
new_domain = True
else:
domainname = current_domainname
opts['domainname'] = domainname
else:
domainname = current_domainname
opts['domainname'] = domainname
new_search = False
if 'search' in opts:
new_searchdomain = opts['search']
if new_searchdomain != current_searchdomain:
searchdomain = new_searchdomain
opts['searchdomain'] = new_searchdomain
new_search = True
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
# If the domain changes, then we should write the resolv.conf file.
if new_domain or new_search:
# Look for existing domain line and update if necessary
resolve = _parse_resolve()
domain_prog = re.compile(r'domain\s+')
search_prog = re.compile(r'search\s+')
new_contents = []
for item in _read_file(_DEB_RESOLV_FILE):
if domain_prog.match(item):
item = 'domain {0}'.format(domainname)
elif search_prog.match(item):
item = 'search {0}'.format(searchdomain)
new_contents.append(item)
# A domain line didn't exist so we'll add one in
# with the new domainname
if 'domain' not in resolve:
new_contents.insert(0, 'domain {0}' . format(domainname))
# A search line didn't exist so we'll add one in
# with the new search domain
if 'search' not in resolve:
new_contents.insert('domain' in resolve, 'search {0}'.format(searchdomain))
new_resolv = '\n'.join(new_contents)
# Write /etc/resolv.conf
if not ('test' in settings and settings['test']):
_write_file_network(new_resolv, _DEB_RESOLV_FILE)
# used for returning the results back
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(opts)
changes.extend(_read_temp(network))
return changes
|
saltstack/salt
|
salt/modules/debian_ip.py
|
_write_file
|
python
|
def _write_file(iface, data, folder, pattern):
'''
Writes a file to disk
'''
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
return filename
|
Writes a file to disk
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_ip.py#L1395-L1407
|
[
"def to_str(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str, bytes, bytearray, or unicode (py2), return str\n '''\n def _normalize(s):\n try:\n return unicodedata.normalize('NFC', s) if normalize else s\n except TypeError:\n return s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n # This shouldn't be six.string_types because if we're on PY2 and we already\n # have a string, we should just return it.\n if isinstance(s, str):\n return _normalize(s)\n\n exc = None\n if six.PY3:\n if isinstance(s, (bytes, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytes, or bytearray not {}'.format(type(s)))\n else:\n if isinstance(s, bytearray):\n return str(s) # future lint: disable=blacklisted-function\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n for enc in encoding:\n try:\n return _normalize(s).encode(enc, errors)\n except UnicodeEncodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytearray, or unicode')\n"
] |
# -*- coding: utf-8 -*-
'''
The networking module for Debian-based distros
References:
* http://www.debian.org/doc/manuals/debian-reference/ch05.en.html
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import functools
import logging
import os.path
import os
import re
import time
# Import third party libs
import jinja2
import jinja2.exceptions
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error,no-name-in-module
# Import salt libs
import salt.utils.dns
import salt.utils.files
import salt.utils.odict
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.validate.net
# Set up logging
log = logging.getLogger(__name__)
# Set up template environment
JINJA = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'debian_ip')
)
)
# Define the module's virtual name
__virtualname__ = 'ip'
def __virtual__():
'''
Confine this module to Debian-based distros
'''
if __grains__['os_family'] == 'Debian':
return __virtualname__
return (False, 'The debian_ip module could not be loaded: '
'unsupported OS family')
_ETHTOOL_CONFIG_OPTS = {
'speed': 'link-speed',
'duplex': 'link-duplex',
'autoneg': 'ethernet-autoneg',
'ethernet-port': 'ethernet-port',
'wol': 'ethernet-wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'rx': 'offload-rx',
'tx': 'offload-tx',
'sg': 'offload-sg',
'tso': 'offload-tso',
'ufo': 'offload-ufo',
'gso': 'offload-gso',
'gro': 'offload-gro',
'lro': 'offload-lro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_REV_ETHTOOL_CONFIG_OPTS = {
'link-speed': 'speed',
'link-duplex': 'duplex',
'ethernet-autoneg': 'autoneg',
'ethernet-port': 'ethernet-port',
'ethernet-wol': 'wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'offload-rx': 'rx',
'offload-tx': 'tx',
'offload-sg': 'sg',
'offload-tso': 'tso',
'offload-ufo': 'ufo',
'offload-gso': 'gso',
'offload-lro': 'lro',
'offload-gro': 'gro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_DEB_CONFIG_PPPOE_OPTS = {
'user': 'user',
'password': 'password',
'provider': 'provider',
'pppoe_iface': 'pppoe_iface',
'noipdefault': 'noipdefault',
'usepeerdns': 'usepeerdns',
'defaultroute': 'defaultroute',
'holdoff': 'holdoff',
'maxfail': 'maxfail',
'hide-password': 'hide-password',
'lcp-echo-interval': 'lcp-echo-interval',
'lcp-echo-failure': 'lcp-echo-failure',
'connect': 'connect',
'noauth': 'noauth',
'persist': 'persist',
'mtu': 'mtu',
'noaccomp': 'noaccomp',
'linkname': 'linkname',
}
_DEB_ROUTES_FILE = '/etc/network/routes'
_DEB_NETWORK_FILE = '/etc/network/interfaces'
_DEB_NETWORK_DIR = '/etc/network/interfaces.d/'
_DEB_NETWORK_UP_DIR = '/etc/network/if-up.d/'
_DEB_NETWORK_DOWN_DIR = '/etc/network/if-down.d/'
_DEB_NETWORK_CONF_FILES = '/etc/modprobe.d/'
_DEB_NETWORKING_FILE = '/etc/default/networking'
_DEB_HOSTNAME_FILE = '/etc/hostname'
_DEB_RESOLV_FILE = '/etc/resolv.conf'
_DEB_PPP_DIR = '/etc/ppp/peers/'
_CONFIG_TRUE = ['yes', 'on', 'true', '1', True]
_CONFIG_FALSE = ['no', 'off', 'false', '0', False]
_IFACE_TYPES = [
'eth', 'bond', 'alias', 'clone',
'ipsec', 'dialup', 'bridge', 'slave',
'vlan', 'pppoe', 'source',
]
def _error_msg_iface(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, '|'.join(str(e) for e in expected))
def _error_msg_routes(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, expected)
def _log_default_iface(iface, opt, value):
log.info(
'Using default option -- Interface: %s Option: %s Value: %s',
iface, opt, value
)
def _error_msg_network(option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]'
return msg.format(option, '|'.join(str(e) for e in expected))
def _log_default_network(opt, value):
log.info('Using existing setting -- Setting: %s Value: %s', opt, value)
def _raise_error_iface(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_iface(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_network(option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_network(option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_routes(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_routes(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _read_file(path):
'''
Reads and returns the contents of a text file
'''
try:
with salt.utils.files.flopen(path, 'rb') as contents:
return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]
except (OSError, IOError):
return ''
def _parse_resolve():
'''
Parse /etc/resolv.conf
'''
return salt.utils.dns.parse_resolv(_DEB_RESOLV_FILE)
def _parse_domainname():
'''
Parse /etc/resolv.conf and return domainname
'''
return _parse_resolve().get('domain', '')
def _parse_searchdomain():
'''
Parse /etc/resolv.conf and return searchdomain
'''
return _parse_resolve().get('search', '')
def _parse_hostname():
'''
Parse /etc/hostname and return hostname
'''
contents = _read_file(_DEB_HOSTNAME_FILE)
if contents:
return contents[0].split('\n')[0]
else:
return ''
def _parse_current_network_settings():
'''
Parse /etc/default/networking and return current configuration
'''
opts = salt.utils.odict.OrderedDict()
opts['networking'] = ''
if os.path.isfile(_DEB_NETWORKING_FILE):
with salt.utils.files.fopen(_DEB_NETWORKING_FILE) as contents:
for line in contents:
salt.utils.stringutils.to_unicode(line)
if line.startswith('#'):
continue
elif line.startswith('CONFIGURE_INTERFACES'):
opts['networking'] = line.split('=', 1)[1].strip()
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
opts['hostname'] = hostname
opts['domainname'] = domainname
opts['searchdomain'] = searchdomain
return opts
# def __validator_func(value):
# return (valid: True/False, (transformed) value, error message)
def __ipv4_quad(value):
'''validate an IPv4 address'''
return (salt.utils.validate.net.ipv4_addr(value), value,
'dotted IPv4 address')
def __ipv6(value):
'''validate an IPv6 address'''
return (salt.utils.validate.net.ipv6_addr(value), value,
'IPv6 address')
def __mac(value):
'''validate a mac address'''
return (salt.utils.validate.net.mac(value), value,
'MAC address')
def __anything(value):
return (True, value, None)
def __int(value):
'''validate an integer'''
valid, _value = False, value
try:
_value = int(value)
valid = True
except ValueError:
pass
return (valid, _value, 'integer')
def __float(value):
'''validate a float'''
valid, _value = False, value
try:
_value = float(value)
valid = True
except ValueError:
pass
return (valid, _value, 'float')
def __ipv4_netmask(value):
'''validate an IPv4 dotted quad or integer CIDR netmask'''
valid, errmsg = False, 'dotted quad or integer CIDR (0->32)'
valid, value, _ = __int(value)
if not (valid and 0 <= value <= 32):
valid = salt.utils.validate.net.netmask(value)
return (valid, value, errmsg)
def __ipv6_netmask(value):
'''validate an IPv6 integer netmask'''
valid, errmsg = False, 'IPv6 netmask (0->128)'
valid, value, _ = __int(value)
valid = (valid and 0 <= value <= 128)
return (valid, value, errmsg)
def __within2(value, within=None, errmsg=None, dtype=None):
'''validate that a value is in ``within`` and optionally a ``dtype``'''
valid, _value = False, value
if dtype:
try:
_value = dtype(value) # TODO: this is a bit loose when dtype is a class
valid = _value in within
except ValueError:
pass
else:
valid = _value in within
if errmsg is None:
if dtype:
typename = getattr(dtype, '__name__',
hasattr(dtype, '__class__')
and getattr(dtype.__class__, 'name', dtype))
errmsg = '{0} within \'{1}\''.format(typename, within)
else:
errmsg = 'within \'{0}\''.format(within)
return (valid, _value, errmsg)
def __within(within=None, errmsg=None, dtype=None):
return functools.partial(__within2, within=within,
errmsg=errmsg, dtype=dtype)
def __space_delimited_list(value):
'''validate that a value contains one or more space-delimited values'''
if isinstance(value, six.string_types):
value = value.strip().split()
if hasattr(value, '__iter__') and value != []:
return (True, value, 'space-delimited string')
else:
return (False, value, '{0} is not a valid space-delimited value.\n'.format(value))
SALT_ATTR_TO_DEBIAN_ATTR_MAP = {
'dns': 'dns-nameservers',
'search': 'dns-search',
'hwaddr': 'hwaddress', # TODO: this limits bootp functionality
'ipaddr': 'address',
'ipaddrs': 'addresses',
}
DEBIAN_ATTR_TO_SALT_ATTR_MAP = dict(
(v, k) for (k, v) in six.iteritems(SALT_ATTR_TO_DEBIAN_ATTR_MAP))
# TODO
DEBIAN_ATTR_TO_SALT_ATTR_MAP['address'] = 'address'
DEBIAN_ATTR_TO_SALT_ATTR_MAP['hwaddress'] = 'hwaddress'
IPV4_VALID_PROTO = ['bootp', 'dhcp', 'static', 'manual', 'loopback', 'ppp']
IPV4_ATTR_MAP = {
'proto': __within(IPV4_VALID_PROTO, dtype=six.text_type),
# ipv4 static & manual
'address': __ipv4_quad,
'addresses': __anything,
'netmask': __ipv4_netmask,
'broadcast': __ipv4_quad,
'metric': __int,
'gateway': __ipv4_quad, # supports a colon-delimited list
'pointopoint': __ipv4_quad,
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'link', 'host'], dtype=six.text_type),
# dhcp
'hostname': __anything,
'leasehours': __int,
'leasetime': __int,
'vendor': __anything,
'client': __anything,
# bootp
'bootfile': __anything,
'server': __ipv4_quad,
'hwaddr': __mac,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'dstaddr': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# bond
'slaves': __anything,
# ppp
'provider': __anything,
'unit': __int,
'options': __anything,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
#
'network': __anything, # i don't know what this is
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
IPV6_VALID_PROTO = ['auto', 'loopback', 'static', 'manual',
'dhcp', 'v4tunnel', '6to4']
IPV6_ATTR_MAP = {
'proto': __within(IPV6_VALID_PROTO),
# ipv6 static & manual
'address': __ipv6,
'addresses': __anything,
'netmask': __ipv6_netmask,
'broadcast': __ipv6,
'gateway': __ipv6, # supports a colon-delimited list
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'site', 'link', 'host'], dtype=six.text_type),
# inet6 auto
'privext': __within([0, 1, 2], dtype=int),
'dhcp': __within([0, 1], dtype=int),
# inet6 static & manual & dhcp
'media': __anything,
'accept_ra': __within([0, 1], dtype=int),
'autoconf': __within([0, 1], dtype=int),
'preferred-lifetime': __int,
'dad-attempts': __int, # 0 to disable
'dad-interval': __float,
# bond
'slaves': __anything,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
WIRELESS_ATTR_MAP = {
'wireless-essid': __anything,
'wireless-mode': __anything, # TODO
'wpa-ap-scan': __within([0, 1, 2], dtype=int), # TODO
'wpa-conf': __anything,
'wpa-driver': __anything,
'wpa-group': __anything,
'wpa-key-mgmt': __anything,
'wpa-pairwise': __anything,
'wpa-psk': __anything,
'wpa-proto': __anything, # partial(__within,
'wpa-roam': __anything,
'wpa-ssid': __anything, # TODO
}
ATTRMAPS = {
'inet': [IPV4_ATTR_MAP, WIRELESS_ATTR_MAP],
'inet6': [IPV6_ATTR_MAP, WIRELESS_ATTR_MAP]
}
def _validate_interface_option(attr, value, addrfam='inet'):
'''lookup the validation function for a [addrfam][attr] and
return the results
:param attr: attribute name
:param value: raw setting value
:param addrfam: address family (inet, inet6,
'''
valid, _value, errmsg = False, value, 'Unknown validator'
attrmaps = ATTRMAPS.get(addrfam, [])
for attrmap in attrmaps:
if attr in attrmap:
validate_func = attrmap[attr]
(valid, _value, errmsg) = validate_func(value)
break
return (valid, _value, errmsg)
def _attrmaps_contain_attr(attr):
return (
attr in WIRELESS_ATTR_MAP or
attr in IPV4_ATTR_MAP or
attr in IPV6_ATTR_MAP)
def _parse_interfaces(interface_files=None):
'''
Parse /etc/network/interfaces and return current configured interfaces
'''
if interface_files is None:
interface_files = []
# Add this later.
if os.path.exists(_DEB_NETWORK_DIR):
interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]
if os.path.isfile(_DEB_NETWORK_FILE):
interface_files.insert(0, _DEB_NETWORK_FILE)
adapters = salt.utils.odict.OrderedDict()
method = -1
for interface_file in interface_files:
with salt.utils.files.fopen(interface_file) as interfaces:
# This ensures iface_dict exists, but does not ensure we're not reading a new interface.
iface_dict = {}
for line in interfaces:
line = salt.utils.stringutils.to_unicode(line)
# Identify the clauses by the first word of each line.
# Go to the next line if the current line is a comment
# or all spaces.
if line.lstrip().startswith('#') or line.isspace():
continue
# Parse the iface clause
if line.startswith('iface'):
sline = line.split()
if len(sline) != 4:
msg = 'Interface file malformed: {0}.'
msg = msg.format(sline)
log.error(msg)
raise AttributeError(msg)
iface_name = sline[1]
addrfam = sline[2]
method = sline[3]
# Create item in dict, if not already there
if iface_name not in adapters:
adapters[iface_name] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters[iface_name]:
adapters[iface_name]['data'] = salt.utils.odict.OrderedDict()
if addrfam not in adapters[iface_name]['data']:
adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict()
iface_dict = adapters[iface_name]['data'][addrfam]
iface_dict['addrfam'] = addrfam
iface_dict['proto'] = method
iface_dict['filename'] = interface_file
# Parse the detail clauses.
elif line[0].isspace():
sline = line.split()
# conf file attr: dns-nameservers
# salt states.network attr: dns
attr, valuestr = line.rstrip().split(None, 1)
if _attrmaps_contain_attr(attr):
if '-' in attr:
attrname = attr.replace('-', '_')
else:
attrname = attr
(valid, value, errmsg) = _validate_interface_option(
attr, valuestr, addrfam)
if attrname == 'address' and 'address' in iface_dict:
if 'addresses' not in iface_dict:
iface_dict['addresses'] = []
iface_dict['addresses'].append(value)
else:
iface_dict[attrname] = value
elif attr in _REV_ETHTOOL_CONFIG_OPTS:
if 'ethtool' not in iface_dict:
iface_dict['ethtool'] = salt.utils.odict.OrderedDict()
iface_dict['ethtool'][attr] = valuestr
elif attr.startswith('bond'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bonding' not in iface_dict:
iface_dict['bonding'] = salt.utils.odict.OrderedDict()
iface_dict['bonding'][opt] = valuestr
elif attr.startswith('bridge'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bridging' not in iface_dict:
iface_dict['bridging'] = salt.utils.odict.OrderedDict()
iface_dict['bridging'][opt] = valuestr
elif attr in ['up', 'pre-up', 'post-up',
'down', 'pre-down', 'post-down']:
cmd = valuestr
cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr))
if cmd_key not in iface_dict:
iface_dict[cmd_key] = []
iface_dict[cmd_key].append(cmd)
elif line.startswith('auto'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['enabled'] = True
elif line.startswith('allow-hotplug'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['hotplug'] = True
elif line.startswith('source'):
if 'source' not in adapters:
adapters['source'] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters['source']:
adapters['source']['data'] = salt.utils.odict.OrderedDict()
adapters['source']['data']['sources'] = []
adapters['source']['data']['sources'].append(line.split()[1])
# Return a sorted list of the keys for bond, bridge and ethtool options to
# ensure a consistent order
for iface_name in adapters:
if iface_name == 'source':
continue
if 'data' not in adapters[iface_name]:
msg = 'Interface file malformed for interface: {0}.'.format(iface_name)
log.error(msg)
adapters.pop(iface_name)
continue
for opt in ['ethtool', 'bonding', 'bridging']:
for inet in ['inet', 'inet6']:
if inet in adapters[iface_name]['data']:
if opt in adapters[iface_name]['data'][inet]:
opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys())
adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys
return adapters
def _parse_ethtool_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
if 'autoneg' in opts:
if opts['autoneg'] in _CONFIG_TRUE:
config.update({'autoneg': 'on'})
elif opts['autoneg'] in _CONFIG_FALSE:
config.update({'autoneg': 'off'})
else:
_raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE)
if 'duplex' in opts:
valid = ['full', 'half']
if opts['duplex'] in valid:
config.update({'duplex': opts['duplex']})
else:
_raise_error_iface(iface, 'duplex', valid)
if 'speed' in opts:
valid = ['10', '100', '1000', '10000']
if six.text_type(opts['speed']) in valid:
config.update({'speed': opts['speed']})
else:
_raise_error_iface(iface, opts['speed'], valid)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'on'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'off'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_ethtool_pppoe_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
for opt in _DEB_CONFIG_PPPOE_OPTS:
if opt in opts:
config[opt] = opts[opt]
if 'provider' in opts and not opts['provider']:
_raise_error_iface(iface, 'provider', _CONFIG_TRUE + _CONFIG_FALSE)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('noipdefault', 'usepeerdns', 'defaultroute', 'hide-password', 'noauth', 'persist', 'noaccomp'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'True'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'False'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_settings_bond(opts, iface):
'''
Filters given options and outputs valid settings for requested
operation. If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond_def = {
# 803.ad aggregation selection logic
# 0 for stable (default)
# 1 for bandwidth
# 2 for count
'ad_select': '0',
# Max number of transmit queues (default = 16)
'tx_queues': '16',
# Link monitoring in milliseconds. Most NICs support this
'miimon': '100',
# ARP interval in milliseconds
'arp_interval': '250',
# Delay before considering link down in milliseconds (miimon * 2)
'downdelay': '200',
# lacp_rate 0: Slow - every 30 seconds
# lacp_rate 1: Fast - every 1 second
'lacp_rate': '0',
# Max bonds for this driver
'max_bonds': '1',
# Specifies the time, in milliseconds, to wait before
# enabling a slave after a link recovery has been
# detected. Only used with miimon.
'updelay': '0',
# Used with miimon.
# On: driver sends mii
# Off: ethtool sends mii
'use_carrier': 'on',
# Default. Don't change unless you know what you are doing.
'xmit_hash_policy': 'layer2',
}
if opts['mode'] in ['balance-rr', '0']:
log.info('Device: %s Bonding Mode: load balancing (round-robin)', iface)
return _parse_settings_bond_0(opts, iface, bond_def)
elif opts['mode'] in ['active-backup', '1']:
log.info('Device: %s Bonding Mode: fault-tolerance (active-backup)', iface)
return _parse_settings_bond_1(opts, iface, bond_def)
elif opts['mode'] in ['balance-xor', '2']:
log.info('Device: %s Bonding Mode: load balancing (xor)', iface)
return _parse_settings_bond_2(opts, iface, bond_def)
elif opts['mode'] in ['broadcast', '3']:
log.info('Device: %s Bonding Mode: fault-tolerance (broadcast)', iface)
return _parse_settings_bond_3(opts, iface, bond_def)
elif opts['mode'] in ['802.3ad', '4']:
log.info('Device: %s Bonding Mode: IEEE 802.3ad Dynamic link '
'aggregation', iface)
return _parse_settings_bond_4(opts, iface, bond_def)
elif opts['mode'] in ['balance-tlb', '5']:
log.info('Device: %s Bonding Mode: transmit load balancing', iface)
return _parse_settings_bond_5(opts, iface, bond_def)
elif opts['mode'] in ['balance-alb', '6']:
log.info('Device: %s Bonding Mode: adaptive load balancing', iface)
return _parse_settings_bond_6(opts, iface, bond_def)
else:
valid = [
'0', '1', '2', '3', '4', '5', '6',
'balance-rr', 'active-backup', 'balance-xor',
'broadcast', '802.3ad', 'balance-tlb', 'balance-alb'
]
_raise_error_iface(iface, 'mode', valid)
def _parse_settings_bond_0(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond0.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '0'}
# ARP targets in n.n.n.n form
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
return bond
def _parse_settings_bond_1(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '1'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
if not (__grains__['os'] == "Ubuntu" and __grains__['osrelease_info'][0] >= 16):
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_2(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond2.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '2'}
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_3(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond3.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '3'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_4(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond4.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '4'}
for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']:
if binding in opts:
if binding == 'lacp_rate':
if opts[binding] == 'fast':
opts.update({binding: '1'})
if opts[binding] == 'slow':
opts.update({binding: '0'})
valid = ['fast', '1', 'slow', '0']
else:
valid = ['integer']
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, valid)
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_5(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond5.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '5'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_settings_bond_6(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond6.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '6'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_bridge_opts(opts, iface):
'''
Filters given options and outputs valid settings for BRIDGING_OPTS
If an option has a value that is not expected, this
function will log the Interface, Setting and what was expected.
'''
config = {}
if 'ports' in opts:
if isinstance(opts['ports'], list):
opts['ports'] = ' '.join(opts['ports'])
config.update({'ports': opts['ports']})
for opt in ['ageing', 'fd', 'gcint', 'hello', 'maxage']:
if opt in opts:
try:
float(opts[opt])
config.update({opt: opts[opt]})
except ValueError:
_raise_error_iface(iface, opt, ['float'])
for opt in ['bridgeprio', 'maxwait']:
if opt in opts:
if isinstance(opts[opt], int):
config.update({opt: opts[opt]})
else:
_raise_error_iface(iface, opt, ['integer'])
if 'hw' in opts:
# match 12 hex digits with either : or - as separators between pairs
if re.match('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$',
opts['hw'].lower()):
config.update({'hw': opts['hw']})
else:
_raise_error_iface(iface, 'hw', ['valid MAC address'])
for opt in ['pathcost', 'portprio']:
if opt in opts:
try:
port, cost_or_prio = opts[opt].split()
int(cost_or_prio)
config.update({opt: '{0} {1}'.format(port, cost_or_prio)})
except ValueError:
_raise_error_iface(iface, opt, ['interface integer'])
if 'stp' in opts:
if opts['stp'] in _CONFIG_TRUE:
config.update({'stp': 'on'})
elif opts['stp'] in _CONFIG_FALSE:
config.update({'stp': 'off'})
else:
_raise_error_iface(iface, 'stp', _CONFIG_TRUE + _CONFIG_FALSE)
if 'waitport' in opts:
if isinstance(opts['waitport'], int):
config.update({'waitport': opts['waitport']})
else:
values = opts['waitport'].split()
waitport_time = values.pop(0)
if waitport_time.isdigit() and values:
config.update({
'waitport': '{0} {1}'.format(
waitport_time, ' '.join(values)
)
})
else:
_raise_error_iface(iface, opt, ['integer [interfaces]'])
return config
def _parse_settings_eth(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['inet'] = salt.utils.odict.OrderedDict()
iface_data['inet6'] = salt.utils.odict.OrderedDict()
if enabled:
adapters[iface]['enabled'] = True
if opts.get('hotplug', False):
adapters[iface]['hotplug'] = True
if opts.get('enable_ipv6', None) and opts.get('iface_type', '') == 'vlan':
iface_data['inet6']['vlan_raw_device'] = (
re.sub(r'\.\d*', '', iface))
for addrfam in ['inet', 'inet6']:
if iface_type not in ['bridge']:
tmp_ethtool = _parse_ethtool_opts(opts, iface)
if tmp_ethtool:
ethtool = {}
for item in tmp_ethtool:
ethtool[_ETHTOOL_CONFIG_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['ethtool'] = ethtool
# return a list of sorted keys to ensure consistent order
iface_data[addrfam]['ethtool_keys'] = sorted(ethtool)
if iface_type == 'bridge':
bridging = _parse_bridge_opts(opts, iface)
if bridging:
iface_data[addrfam]['bridging'] = bridging
iface_data[addrfam]['bridging_keys'] = sorted(bridging)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'bond':
bonding = _parse_settings_bond(opts, iface)
if bonding:
iface_data[addrfam]['bonding'] = bonding
iface_data[addrfam]['bonding']['slaves'] = opts['slaves']
iface_data[addrfam]['bonding_keys'] = sorted(bonding)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'slave':
adapters[iface]['master'] = opts['master']
opts['proto'] = 'manual'
iface_data[addrfam]['master'] = adapters[iface]['master']
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'vlan':
iface_data[addrfam]['vlan_raw_device'] = re.sub(r'\.\d*', '', iface)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'pppoe':
tmp_ethtool = _parse_ethtool_pppoe_opts(opts, iface)
if tmp_ethtool:
for item in tmp_ethtool:
adapters[iface]['data'][addrfam][_DEB_CONFIG_PPPOE_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['addrfam'] = addrfam
opts.pop('mode', None)
for opt, val in opts.items():
inet = None
if opt.startswith('ipv4'):
opt = opt[4:]
inet = 'inet'
iface_data['inet']['addrfam'] = 'inet'
elif opt.startswith('ipv6'):
iface_data['inet6']['addrfam'] = 'inet6'
opt = opt[4:]
inet = 'inet6'
elif opt in ['ipaddr', 'address', 'ipaddresses', 'addresses', 'gateway', 'proto']:
iface_data['inet']['addrfam'] = 'inet'
inet = 'inet'
_opt = SALT_ATTR_TO_DEBIAN_ATTR_MAP.get(opt, opt)
_debopt = _opt.replace('-', '_')
for addrfam in ['inet', 'inet6']:
(valid, value, errmsg) = _validate_interface_option(_opt, val, addrfam=addrfam)
if not valid:
continue
if inet is None and _debopt not in iface_data[addrfam]:
iface_data[addrfam][_debopt] = value
elif inet == addrfam:
iface_data[addrfam][_debopt] = value
for opt in ['up_cmds', 'pre_up_cmds', 'post_up_cmds',
'down_cmds', 'pre_down_cmds', 'post_down_cmds']:
if opt in opts:
iface_data['inet'][opt] = opts[opt]
iface_data['inet6'][opt] = opts[opt]
# Remove incomplete/disabled inet blocks
for (addrfam, opt) in [('inet', 'enable_ipv4'), ('inet6', 'enable_ipv6')]:
if opts.get(opt, None) is False:
iface_data.pop(addrfam)
elif iface_data[addrfam].get('addrfam', '') != addrfam:
iface_data.pop(addrfam)
return adapters
def _parse_settings_source(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['sources'] = [opts['source']]
return adapters
def _parse_network_settings(opts, current):
'''
Filters given options and outputs valid settings for
the global network settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
current = dict((k.lower(), v) for (k, v) in six.iteritems(current))
result = {}
valid = _CONFIG_TRUE + _CONFIG_FALSE
if 'enabled' not in opts:
try:
opts['networking'] = current['networking']
_log_default_network('networking', current['networking'])
except ValueError:
_raise_error_network('networking', valid)
else:
opts['networking'] = opts['enabled']
if opts['networking'] in valid:
if opts['networking'] in _CONFIG_TRUE:
result['networking'] = 'yes'
elif opts['networking'] in _CONFIG_FALSE:
result['networking'] = 'no'
else:
_raise_error_network('networking', valid)
if 'hostname' not in opts:
try:
opts['hostname'] = current['hostname']
_log_default_network('hostname', current['hostname'])
except ValueError:
_raise_error_network('hostname', ['server1.example.com'])
if opts['hostname']:
result['hostname'] = opts['hostname']
else:
_raise_error_network('hostname', ['server1.example.com'])
if 'search' in opts:
result['search'] = opts['search']
return result
def _parse_routes(iface, opts):
'''
Filters given options and outputs valid settings for
the route settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
result = {}
if 'routes' not in opts:
_raise_error_routes(iface, 'routes', 'List of routes')
for opt in opts:
result[opt] = opts[opt]
return result
def _write_file_routes(iface, data, folder, pattern):
'''
Writes a file to disk
'''
# ifup / ifdown is executing given folder via run-parts.
# according to run-parts man-page, only filenames with this pattern are
# executed: (^[a-zA-Z0-9_-]+$)
# In order to make the routes file work for vlan interfaces
# (default would have been in example /etc/network/if-up.d/route-bond0.12)
# these dots in the iface name need to be replaced by underscores, so it
# can be executed by run-parts
iface = iface.replace('.', '_')
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
__salt__['file.set_mode'](filename, '0755')
return filename
def _write_file_network(data, filename, create=False):
'''
Writes a file to disk
If file does not exist, only create if create
argument is True
'''
if not os.path.exists(filename) and not create:
msg = '{0} cannot be written. {0} does not exist\
and create is set to False'
msg = msg.format(filename)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
def _read_temp(data):
'''
Return what would be written to disk
'''
tout = StringIO()
tout.write(data)
tout.seek(0)
output = tout.readlines()
tout.close()
return output
def _read_temp_ifaces(iface, data):
'''
Return what would be written to disk for interfaces
'''
try:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': data})
# Return as an array so the difflib works
return [item + '\n' for item in ifcfg.split('\n')]
def _write_file_ifaces(iface, data, **settings):
'''
Writes a file to disk
'''
try:
eth_template = JINJA.get_template('debian_eth.jinja')
source_template = JINJA.get_template('debian_source.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
# Read /etc/network/interfaces into a dict
adapters = _parse_interfaces()
# Apply supplied settings over on-disk settings
adapters[iface] = data
ifcfg = ''
for adapter in adapters:
if 'type' in adapters[adapter] and adapters[adapter]['type'] == 'source':
tmp = source_template.render({'name': adapter, 'data': adapters[adapter]})
else:
tmp = eth_template.render({'name': adapter, 'data': adapters[adapter]})
ifcfg = ifcfg + tmp
if adapter == iface:
saved_ifcfg = tmp
_SEPARATE_FILE = False
if 'filename' in settings:
if not settings['filename'].startswith('/'):
filename = '{0}/{1}'.format(_DEB_NETWORK_DIR, settings['filename'])
else:
filename = settings['filename']
_SEPARATE_FILE = True
else:
if 'filename' in adapters[adapter]['data']:
filename = adapters[adapter]['data']
else:
filename = _DEB_NETWORK_FILE
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
if _SEPARATE_FILE:
fout.write(salt.utils.stringutils.to_str(saved_ifcfg))
else:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return saved_ifcfg.split('\n')
def _write_file_ppp_ifaces(iface, data):
'''
Writes a file to disk
'''
try:
template = JINJA.get_template('debian_ppp_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_ppp_eth.jinja')
return ''
adapters = _parse_interfaces()
adapters[iface] = data
ifcfg = ''
tmp = template.render({'data': adapters[iface]})
ifcfg = tmp + ifcfg
filename = _DEB_PPP_DIR + '/' + adapters[iface]['data']['inet']['provider']
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.fopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return filename
def build_bond(iface, **settings):
'''
Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb
'''
deb_major = __grains__['osrelease'][:1]
opts = _parse_settings_bond(settings, iface)
try:
template = JINJA.get_template('conf.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template conf.jinja')
return ''
data = template.render({'name': iface, 'bonding': opts})
if 'test' in settings and settings['test']:
return _read_temp(data)
_write_file(iface, data, _DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
if deb_major == '5':
for line_type in ('alias', 'options'):
cmd = ['sed', '-i', '-e', r'/^{0}\s{1}.*/d'.format(line_type, iface),
'/etc/modprobe.conf']
__salt__['cmd.run'](cmd, python_shell=False)
__salt__['file.append']('/etc/modprobe.conf', path)
# Load kernel module
__salt__['kmod.load']('bonding')
# install ifenslave-2.6
__salt__['pkg.install']('ifenslave-2.6')
return _read_file(path)
def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'vlan':
settings['vlan'] = 'yes'
__salt__['pkg.install']('vlan')
elif iface_type == 'pppoe':
settings['pppoe'] = 'yes'
if not __salt__['pkg.version']('ppp'):
inst = __salt__['pkg.install']('ppp')
elif iface_type == 'bond':
if 'slaves' not in settings:
msg = 'slaves is a required setting for bond interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'bridge':
if 'ports' not in settings:
msg = (
'ports is a required setting for bridge interfaces on Debian '
'or Ubuntu based systems'
)
log.error(msg)
raise AttributeError(msg)
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'pppoe']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
if iface_type in ['source']:
opts = _parse_settings_source(settings, iface_type, enabled, iface)
if 'test' in settings and settings['test']:
return _read_temp_ifaces(iface, opts[iface])
ifcfg = _write_file_ifaces(iface, opts[iface], **settings)
if iface_type == 'pppoe':
_write_file_ppp_ifaces(iface, opts[iface])
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg]
def build_routes(iface, **settings):
'''
Add route scripts for a network interface using up commands.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
'''
opts = _parse_routes(iface, settings)
try:
template = JINJA.get_template('route_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template route_eth.jinja')
return ''
add_routecfg = template.render(route_type='add',
routes=opts['routes'],
iface=iface)
del_routecfg = template.render(route_type='del',
routes=opts['routes'],
iface=iface)
if 'test' in settings and settings['test']:
return _read_temp(add_routecfg + del_routecfg)
filename = _write_file_routes(iface,
add_routecfg,
_DEB_NETWORK_UP_DIR,
'route-{0}')
results = _read_file(filename)
filename = _write_file_routes(iface,
del_routecfg,
_DEB_NETWORK_DOWN_DIR,
'route-{0}')
results += _read_file(filename)
return results
def down(iface, iface_type):
'''
Shutdown a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.down eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought down.
if iface_type not in ['slave', 'source']:
return __salt__['cmd.run'](['ifdown', iface])
return None
def get_bond(iface):
'''
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
'''
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
return _read_file(path)
def get_interface(iface):
'''
Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
adapters = _parse_interfaces()
if iface in adapters:
try:
if iface == 'source':
template = JINJA.get_template('debian_source.jinja')
else:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': adapters[iface]})
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg.split('\n')]
else:
return []
def up(iface, iface_type): # pylint: disable=C0103
'''
Start up a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.up eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought up.
if iface_type not in ('slave', 'source'):
return __salt__['cmd.run'](['ifup', iface])
return None
def get_network_settings():
'''
Return the contents of the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_network_settings
'''
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
settings = {}
if __salt__['service.available']('networking'):
if __salt__['service.status']('networking'):
settings['networking'] = "yes"
else:
settings['networking'] = "no"
else:
settings['networking'] = "no"
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
settings['hostname'] = hostname
settings['domainname'] = domainname
settings['searchdomain'] = searchdomain
else:
settings = _parse_current_network_settings()
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(settings)
return _read_temp(network)
def get_routes(iface):
'''
Return the routes for the interface
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0
'''
filename = os.path.join(_DEB_NETWORK_UP_DIR, 'route-{0}'.format(iface))
results = _read_file(filename)
filename = os.path.join(_DEB_NETWORK_DOWN_DIR, 'route-{0}'.format(iface))
results += _read_file(filename)
return results
def apply_network_settings(**settings):
'''
Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings
'''
if 'require_reboot' not in settings:
settings['require_reboot'] = False
if 'apply_hostname' not in settings:
settings['apply_hostname'] = False
hostname_res = True
if settings['apply_hostname'] in _CONFIG_TRUE:
if 'hostname' in settings:
hostname_res = __salt__['network.mod_hostname'](settings['hostname'])
else:
log.warning(
'The network state sls is trying to apply hostname '
'changes but no hostname is defined.'
)
hostname_res = False
res = True
if settings['require_reboot'] in _CONFIG_TRUE:
log.warning(
'The network state sls is requiring a reboot of the system to '
'properly apply network configuration.'
)
res = True
else:
stop = __salt__['service.stop']('networking')
time.sleep(2)
res = stop and __salt__['service.start']('networking')
return hostname_res and res
def build_network_settings(**settings):
'''
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
'''
changes = []
# Read current configuration and store default values
current_network_settings = _parse_current_network_settings()
# Build settings
opts = _parse_network_settings(settings, current_network_settings)
# Ubuntu has moved away from /etc/default/networking
# beginning with the 12.04 release so we disable or enable
# the networking related services on boot
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
if opts['networking'] == 'yes':
service_cmd = 'service.enable'
else:
service_cmd = 'service.disable'
if __salt__['service.available']('NetworkManager'):
__salt__[service_cmd]('NetworkManager')
if __salt__['service.available']('networking'):
__salt__[service_cmd]('networking')
else:
try:
template = JINJA.get_template('network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template network.jinja')
return ''
network = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(network)
# Write settings
_write_file_network(network, _DEB_NETWORKING_FILE, True)
# Get hostname and domain from opts
sline = opts['hostname'].split('.', 1)
opts['hostname'] = sline[0]
current_domainname = current_network_settings['domainname']
current_searchdomain = current_network_settings['searchdomain']
new_domain = False
if len(sline) > 1:
new_domainname = sline[1]
if new_domainname != current_domainname:
domainname = new_domainname
opts['domainname'] = new_domainname
new_domain = True
else:
domainname = current_domainname
opts['domainname'] = domainname
else:
domainname = current_domainname
opts['domainname'] = domainname
new_search = False
if 'search' in opts:
new_searchdomain = opts['search']
if new_searchdomain != current_searchdomain:
searchdomain = new_searchdomain
opts['searchdomain'] = new_searchdomain
new_search = True
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
# If the domain changes, then we should write the resolv.conf file.
if new_domain or new_search:
# Look for existing domain line and update if necessary
resolve = _parse_resolve()
domain_prog = re.compile(r'domain\s+')
search_prog = re.compile(r'search\s+')
new_contents = []
for item in _read_file(_DEB_RESOLV_FILE):
if domain_prog.match(item):
item = 'domain {0}'.format(domainname)
elif search_prog.match(item):
item = 'search {0}'.format(searchdomain)
new_contents.append(item)
# A domain line didn't exist so we'll add one in
# with the new domainname
if 'domain' not in resolve:
new_contents.insert(0, 'domain {0}' . format(domainname))
# A search line didn't exist so we'll add one in
# with the new search domain
if 'search' not in resolve:
new_contents.insert('domain' in resolve, 'search {0}'.format(searchdomain))
new_resolv = '\n'.join(new_contents)
# Write /etc/resolv.conf
if not ('test' in settings and settings['test']):
_write_file_network(new_resolv, _DEB_RESOLV_FILE)
# used for returning the results back
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(opts)
changes.extend(_read_temp(network))
return changes
|
saltstack/salt
|
salt/modules/debian_ip.py
|
_write_file_network
|
python
|
def _write_file_network(data, filename, create=False):
'''
Writes a file to disk
If file does not exist, only create if create
argument is True
'''
if not os.path.exists(filename) and not create:
msg = '{0} cannot be written. {0} does not exist\
and create is set to False'
msg = msg.format(filename)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
|
Writes a file to disk
If file does not exist, only create if create
argument is True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_ip.py#L1437-L1450
| null |
# -*- coding: utf-8 -*-
'''
The networking module for Debian-based distros
References:
* http://www.debian.org/doc/manuals/debian-reference/ch05.en.html
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import functools
import logging
import os.path
import os
import re
import time
# Import third party libs
import jinja2
import jinja2.exceptions
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error,no-name-in-module
# Import salt libs
import salt.utils.dns
import salt.utils.files
import salt.utils.odict
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.validate.net
# Set up logging
log = logging.getLogger(__name__)
# Set up template environment
JINJA = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'debian_ip')
)
)
# Define the module's virtual name
__virtualname__ = 'ip'
def __virtual__():
'''
Confine this module to Debian-based distros
'''
if __grains__['os_family'] == 'Debian':
return __virtualname__
return (False, 'The debian_ip module could not be loaded: '
'unsupported OS family')
_ETHTOOL_CONFIG_OPTS = {
'speed': 'link-speed',
'duplex': 'link-duplex',
'autoneg': 'ethernet-autoneg',
'ethernet-port': 'ethernet-port',
'wol': 'ethernet-wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'rx': 'offload-rx',
'tx': 'offload-tx',
'sg': 'offload-sg',
'tso': 'offload-tso',
'ufo': 'offload-ufo',
'gso': 'offload-gso',
'gro': 'offload-gro',
'lro': 'offload-lro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_REV_ETHTOOL_CONFIG_OPTS = {
'link-speed': 'speed',
'link-duplex': 'duplex',
'ethernet-autoneg': 'autoneg',
'ethernet-port': 'ethernet-port',
'ethernet-wol': 'wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'offload-rx': 'rx',
'offload-tx': 'tx',
'offload-sg': 'sg',
'offload-tso': 'tso',
'offload-ufo': 'ufo',
'offload-gso': 'gso',
'offload-lro': 'lro',
'offload-gro': 'gro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_DEB_CONFIG_PPPOE_OPTS = {
'user': 'user',
'password': 'password',
'provider': 'provider',
'pppoe_iface': 'pppoe_iface',
'noipdefault': 'noipdefault',
'usepeerdns': 'usepeerdns',
'defaultroute': 'defaultroute',
'holdoff': 'holdoff',
'maxfail': 'maxfail',
'hide-password': 'hide-password',
'lcp-echo-interval': 'lcp-echo-interval',
'lcp-echo-failure': 'lcp-echo-failure',
'connect': 'connect',
'noauth': 'noauth',
'persist': 'persist',
'mtu': 'mtu',
'noaccomp': 'noaccomp',
'linkname': 'linkname',
}
_DEB_ROUTES_FILE = '/etc/network/routes'
_DEB_NETWORK_FILE = '/etc/network/interfaces'
_DEB_NETWORK_DIR = '/etc/network/interfaces.d/'
_DEB_NETWORK_UP_DIR = '/etc/network/if-up.d/'
_DEB_NETWORK_DOWN_DIR = '/etc/network/if-down.d/'
_DEB_NETWORK_CONF_FILES = '/etc/modprobe.d/'
_DEB_NETWORKING_FILE = '/etc/default/networking'
_DEB_HOSTNAME_FILE = '/etc/hostname'
_DEB_RESOLV_FILE = '/etc/resolv.conf'
_DEB_PPP_DIR = '/etc/ppp/peers/'
_CONFIG_TRUE = ['yes', 'on', 'true', '1', True]
_CONFIG_FALSE = ['no', 'off', 'false', '0', False]
_IFACE_TYPES = [
'eth', 'bond', 'alias', 'clone',
'ipsec', 'dialup', 'bridge', 'slave',
'vlan', 'pppoe', 'source',
]
def _error_msg_iface(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, '|'.join(str(e) for e in expected))
def _error_msg_routes(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, expected)
def _log_default_iface(iface, opt, value):
log.info(
'Using default option -- Interface: %s Option: %s Value: %s',
iface, opt, value
)
def _error_msg_network(option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]'
return msg.format(option, '|'.join(str(e) for e in expected))
def _log_default_network(opt, value):
log.info('Using existing setting -- Setting: %s Value: %s', opt, value)
def _raise_error_iface(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_iface(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_network(option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_network(option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_routes(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_routes(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _read_file(path):
'''
Reads and returns the contents of a text file
'''
try:
with salt.utils.files.flopen(path, 'rb') as contents:
return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]
except (OSError, IOError):
return ''
def _parse_resolve():
'''
Parse /etc/resolv.conf
'''
return salt.utils.dns.parse_resolv(_DEB_RESOLV_FILE)
def _parse_domainname():
'''
Parse /etc/resolv.conf and return domainname
'''
return _parse_resolve().get('domain', '')
def _parse_searchdomain():
'''
Parse /etc/resolv.conf and return searchdomain
'''
return _parse_resolve().get('search', '')
def _parse_hostname():
'''
Parse /etc/hostname and return hostname
'''
contents = _read_file(_DEB_HOSTNAME_FILE)
if contents:
return contents[0].split('\n')[0]
else:
return ''
def _parse_current_network_settings():
'''
Parse /etc/default/networking and return current configuration
'''
opts = salt.utils.odict.OrderedDict()
opts['networking'] = ''
if os.path.isfile(_DEB_NETWORKING_FILE):
with salt.utils.files.fopen(_DEB_NETWORKING_FILE) as contents:
for line in contents:
salt.utils.stringutils.to_unicode(line)
if line.startswith('#'):
continue
elif line.startswith('CONFIGURE_INTERFACES'):
opts['networking'] = line.split('=', 1)[1].strip()
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
opts['hostname'] = hostname
opts['domainname'] = domainname
opts['searchdomain'] = searchdomain
return opts
# def __validator_func(value):
# return (valid: True/False, (transformed) value, error message)
def __ipv4_quad(value):
'''validate an IPv4 address'''
return (salt.utils.validate.net.ipv4_addr(value), value,
'dotted IPv4 address')
def __ipv6(value):
'''validate an IPv6 address'''
return (salt.utils.validate.net.ipv6_addr(value), value,
'IPv6 address')
def __mac(value):
'''validate a mac address'''
return (salt.utils.validate.net.mac(value), value,
'MAC address')
def __anything(value):
return (True, value, None)
def __int(value):
'''validate an integer'''
valid, _value = False, value
try:
_value = int(value)
valid = True
except ValueError:
pass
return (valid, _value, 'integer')
def __float(value):
'''validate a float'''
valid, _value = False, value
try:
_value = float(value)
valid = True
except ValueError:
pass
return (valid, _value, 'float')
def __ipv4_netmask(value):
'''validate an IPv4 dotted quad or integer CIDR netmask'''
valid, errmsg = False, 'dotted quad or integer CIDR (0->32)'
valid, value, _ = __int(value)
if not (valid and 0 <= value <= 32):
valid = salt.utils.validate.net.netmask(value)
return (valid, value, errmsg)
def __ipv6_netmask(value):
'''validate an IPv6 integer netmask'''
valid, errmsg = False, 'IPv6 netmask (0->128)'
valid, value, _ = __int(value)
valid = (valid and 0 <= value <= 128)
return (valid, value, errmsg)
def __within2(value, within=None, errmsg=None, dtype=None):
'''validate that a value is in ``within`` and optionally a ``dtype``'''
valid, _value = False, value
if dtype:
try:
_value = dtype(value) # TODO: this is a bit loose when dtype is a class
valid = _value in within
except ValueError:
pass
else:
valid = _value in within
if errmsg is None:
if dtype:
typename = getattr(dtype, '__name__',
hasattr(dtype, '__class__')
and getattr(dtype.__class__, 'name', dtype))
errmsg = '{0} within \'{1}\''.format(typename, within)
else:
errmsg = 'within \'{0}\''.format(within)
return (valid, _value, errmsg)
def __within(within=None, errmsg=None, dtype=None):
return functools.partial(__within2, within=within,
errmsg=errmsg, dtype=dtype)
def __space_delimited_list(value):
'''validate that a value contains one or more space-delimited values'''
if isinstance(value, six.string_types):
value = value.strip().split()
if hasattr(value, '__iter__') and value != []:
return (True, value, 'space-delimited string')
else:
return (False, value, '{0} is not a valid space-delimited value.\n'.format(value))
SALT_ATTR_TO_DEBIAN_ATTR_MAP = {
'dns': 'dns-nameservers',
'search': 'dns-search',
'hwaddr': 'hwaddress', # TODO: this limits bootp functionality
'ipaddr': 'address',
'ipaddrs': 'addresses',
}
DEBIAN_ATTR_TO_SALT_ATTR_MAP = dict(
(v, k) for (k, v) in six.iteritems(SALT_ATTR_TO_DEBIAN_ATTR_MAP))
# TODO
DEBIAN_ATTR_TO_SALT_ATTR_MAP['address'] = 'address'
DEBIAN_ATTR_TO_SALT_ATTR_MAP['hwaddress'] = 'hwaddress'
IPV4_VALID_PROTO = ['bootp', 'dhcp', 'static', 'manual', 'loopback', 'ppp']
IPV4_ATTR_MAP = {
'proto': __within(IPV4_VALID_PROTO, dtype=six.text_type),
# ipv4 static & manual
'address': __ipv4_quad,
'addresses': __anything,
'netmask': __ipv4_netmask,
'broadcast': __ipv4_quad,
'metric': __int,
'gateway': __ipv4_quad, # supports a colon-delimited list
'pointopoint': __ipv4_quad,
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'link', 'host'], dtype=six.text_type),
# dhcp
'hostname': __anything,
'leasehours': __int,
'leasetime': __int,
'vendor': __anything,
'client': __anything,
# bootp
'bootfile': __anything,
'server': __ipv4_quad,
'hwaddr': __mac,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'dstaddr': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# bond
'slaves': __anything,
# ppp
'provider': __anything,
'unit': __int,
'options': __anything,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
#
'network': __anything, # i don't know what this is
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
IPV6_VALID_PROTO = ['auto', 'loopback', 'static', 'manual',
'dhcp', 'v4tunnel', '6to4']
IPV6_ATTR_MAP = {
'proto': __within(IPV6_VALID_PROTO),
# ipv6 static & manual
'address': __ipv6,
'addresses': __anything,
'netmask': __ipv6_netmask,
'broadcast': __ipv6,
'gateway': __ipv6, # supports a colon-delimited list
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'site', 'link', 'host'], dtype=six.text_type),
# inet6 auto
'privext': __within([0, 1, 2], dtype=int),
'dhcp': __within([0, 1], dtype=int),
# inet6 static & manual & dhcp
'media': __anything,
'accept_ra': __within([0, 1], dtype=int),
'autoconf': __within([0, 1], dtype=int),
'preferred-lifetime': __int,
'dad-attempts': __int, # 0 to disable
'dad-interval': __float,
# bond
'slaves': __anything,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
WIRELESS_ATTR_MAP = {
'wireless-essid': __anything,
'wireless-mode': __anything, # TODO
'wpa-ap-scan': __within([0, 1, 2], dtype=int), # TODO
'wpa-conf': __anything,
'wpa-driver': __anything,
'wpa-group': __anything,
'wpa-key-mgmt': __anything,
'wpa-pairwise': __anything,
'wpa-psk': __anything,
'wpa-proto': __anything, # partial(__within,
'wpa-roam': __anything,
'wpa-ssid': __anything, # TODO
}
ATTRMAPS = {
'inet': [IPV4_ATTR_MAP, WIRELESS_ATTR_MAP],
'inet6': [IPV6_ATTR_MAP, WIRELESS_ATTR_MAP]
}
def _validate_interface_option(attr, value, addrfam='inet'):
'''lookup the validation function for a [addrfam][attr] and
return the results
:param attr: attribute name
:param value: raw setting value
:param addrfam: address family (inet, inet6,
'''
valid, _value, errmsg = False, value, 'Unknown validator'
attrmaps = ATTRMAPS.get(addrfam, [])
for attrmap in attrmaps:
if attr in attrmap:
validate_func = attrmap[attr]
(valid, _value, errmsg) = validate_func(value)
break
return (valid, _value, errmsg)
def _attrmaps_contain_attr(attr):
return (
attr in WIRELESS_ATTR_MAP or
attr in IPV4_ATTR_MAP or
attr in IPV6_ATTR_MAP)
def _parse_interfaces(interface_files=None):
'''
Parse /etc/network/interfaces and return current configured interfaces
'''
if interface_files is None:
interface_files = []
# Add this later.
if os.path.exists(_DEB_NETWORK_DIR):
interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]
if os.path.isfile(_DEB_NETWORK_FILE):
interface_files.insert(0, _DEB_NETWORK_FILE)
adapters = salt.utils.odict.OrderedDict()
method = -1
for interface_file in interface_files:
with salt.utils.files.fopen(interface_file) as interfaces:
# This ensures iface_dict exists, but does not ensure we're not reading a new interface.
iface_dict = {}
for line in interfaces:
line = salt.utils.stringutils.to_unicode(line)
# Identify the clauses by the first word of each line.
# Go to the next line if the current line is a comment
# or all spaces.
if line.lstrip().startswith('#') or line.isspace():
continue
# Parse the iface clause
if line.startswith('iface'):
sline = line.split()
if len(sline) != 4:
msg = 'Interface file malformed: {0}.'
msg = msg.format(sline)
log.error(msg)
raise AttributeError(msg)
iface_name = sline[1]
addrfam = sline[2]
method = sline[3]
# Create item in dict, if not already there
if iface_name not in adapters:
adapters[iface_name] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters[iface_name]:
adapters[iface_name]['data'] = salt.utils.odict.OrderedDict()
if addrfam not in adapters[iface_name]['data']:
adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict()
iface_dict = adapters[iface_name]['data'][addrfam]
iface_dict['addrfam'] = addrfam
iface_dict['proto'] = method
iface_dict['filename'] = interface_file
# Parse the detail clauses.
elif line[0].isspace():
sline = line.split()
# conf file attr: dns-nameservers
# salt states.network attr: dns
attr, valuestr = line.rstrip().split(None, 1)
if _attrmaps_contain_attr(attr):
if '-' in attr:
attrname = attr.replace('-', '_')
else:
attrname = attr
(valid, value, errmsg) = _validate_interface_option(
attr, valuestr, addrfam)
if attrname == 'address' and 'address' in iface_dict:
if 'addresses' not in iface_dict:
iface_dict['addresses'] = []
iface_dict['addresses'].append(value)
else:
iface_dict[attrname] = value
elif attr in _REV_ETHTOOL_CONFIG_OPTS:
if 'ethtool' not in iface_dict:
iface_dict['ethtool'] = salt.utils.odict.OrderedDict()
iface_dict['ethtool'][attr] = valuestr
elif attr.startswith('bond'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bonding' not in iface_dict:
iface_dict['bonding'] = salt.utils.odict.OrderedDict()
iface_dict['bonding'][opt] = valuestr
elif attr.startswith('bridge'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bridging' not in iface_dict:
iface_dict['bridging'] = salt.utils.odict.OrderedDict()
iface_dict['bridging'][opt] = valuestr
elif attr in ['up', 'pre-up', 'post-up',
'down', 'pre-down', 'post-down']:
cmd = valuestr
cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr))
if cmd_key not in iface_dict:
iface_dict[cmd_key] = []
iface_dict[cmd_key].append(cmd)
elif line.startswith('auto'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['enabled'] = True
elif line.startswith('allow-hotplug'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['hotplug'] = True
elif line.startswith('source'):
if 'source' not in adapters:
adapters['source'] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters['source']:
adapters['source']['data'] = salt.utils.odict.OrderedDict()
adapters['source']['data']['sources'] = []
adapters['source']['data']['sources'].append(line.split()[1])
# Return a sorted list of the keys for bond, bridge and ethtool options to
# ensure a consistent order
for iface_name in adapters:
if iface_name == 'source':
continue
if 'data' not in adapters[iface_name]:
msg = 'Interface file malformed for interface: {0}.'.format(iface_name)
log.error(msg)
adapters.pop(iface_name)
continue
for opt in ['ethtool', 'bonding', 'bridging']:
for inet in ['inet', 'inet6']:
if inet in adapters[iface_name]['data']:
if opt in adapters[iface_name]['data'][inet]:
opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys())
adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys
return adapters
def _parse_ethtool_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
if 'autoneg' in opts:
if opts['autoneg'] in _CONFIG_TRUE:
config.update({'autoneg': 'on'})
elif opts['autoneg'] in _CONFIG_FALSE:
config.update({'autoneg': 'off'})
else:
_raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE)
if 'duplex' in opts:
valid = ['full', 'half']
if opts['duplex'] in valid:
config.update({'duplex': opts['duplex']})
else:
_raise_error_iface(iface, 'duplex', valid)
if 'speed' in opts:
valid = ['10', '100', '1000', '10000']
if six.text_type(opts['speed']) in valid:
config.update({'speed': opts['speed']})
else:
_raise_error_iface(iface, opts['speed'], valid)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'on'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'off'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_ethtool_pppoe_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
for opt in _DEB_CONFIG_PPPOE_OPTS:
if opt in opts:
config[opt] = opts[opt]
if 'provider' in opts and not opts['provider']:
_raise_error_iface(iface, 'provider', _CONFIG_TRUE + _CONFIG_FALSE)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('noipdefault', 'usepeerdns', 'defaultroute', 'hide-password', 'noauth', 'persist', 'noaccomp'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'True'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'False'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_settings_bond(opts, iface):
'''
Filters given options and outputs valid settings for requested
operation. If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond_def = {
# 803.ad aggregation selection logic
# 0 for stable (default)
# 1 for bandwidth
# 2 for count
'ad_select': '0',
# Max number of transmit queues (default = 16)
'tx_queues': '16',
# Link monitoring in milliseconds. Most NICs support this
'miimon': '100',
# ARP interval in milliseconds
'arp_interval': '250',
# Delay before considering link down in milliseconds (miimon * 2)
'downdelay': '200',
# lacp_rate 0: Slow - every 30 seconds
# lacp_rate 1: Fast - every 1 second
'lacp_rate': '0',
# Max bonds for this driver
'max_bonds': '1',
# Specifies the time, in milliseconds, to wait before
# enabling a slave after a link recovery has been
# detected. Only used with miimon.
'updelay': '0',
# Used with miimon.
# On: driver sends mii
# Off: ethtool sends mii
'use_carrier': 'on',
# Default. Don't change unless you know what you are doing.
'xmit_hash_policy': 'layer2',
}
if opts['mode'] in ['balance-rr', '0']:
log.info('Device: %s Bonding Mode: load balancing (round-robin)', iface)
return _parse_settings_bond_0(opts, iface, bond_def)
elif opts['mode'] in ['active-backup', '1']:
log.info('Device: %s Bonding Mode: fault-tolerance (active-backup)', iface)
return _parse_settings_bond_1(opts, iface, bond_def)
elif opts['mode'] in ['balance-xor', '2']:
log.info('Device: %s Bonding Mode: load balancing (xor)', iface)
return _parse_settings_bond_2(opts, iface, bond_def)
elif opts['mode'] in ['broadcast', '3']:
log.info('Device: %s Bonding Mode: fault-tolerance (broadcast)', iface)
return _parse_settings_bond_3(opts, iface, bond_def)
elif opts['mode'] in ['802.3ad', '4']:
log.info('Device: %s Bonding Mode: IEEE 802.3ad Dynamic link '
'aggregation', iface)
return _parse_settings_bond_4(opts, iface, bond_def)
elif opts['mode'] in ['balance-tlb', '5']:
log.info('Device: %s Bonding Mode: transmit load balancing', iface)
return _parse_settings_bond_5(opts, iface, bond_def)
elif opts['mode'] in ['balance-alb', '6']:
log.info('Device: %s Bonding Mode: adaptive load balancing', iface)
return _parse_settings_bond_6(opts, iface, bond_def)
else:
valid = [
'0', '1', '2', '3', '4', '5', '6',
'balance-rr', 'active-backup', 'balance-xor',
'broadcast', '802.3ad', 'balance-tlb', 'balance-alb'
]
_raise_error_iface(iface, 'mode', valid)
def _parse_settings_bond_0(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond0.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '0'}
# ARP targets in n.n.n.n form
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
return bond
def _parse_settings_bond_1(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '1'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
if not (__grains__['os'] == "Ubuntu" and __grains__['osrelease_info'][0] >= 16):
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_2(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond2.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '2'}
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_3(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond3.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '3'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_4(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond4.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '4'}
for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']:
if binding in opts:
if binding == 'lacp_rate':
if opts[binding] == 'fast':
opts.update({binding: '1'})
if opts[binding] == 'slow':
opts.update({binding: '0'})
valid = ['fast', '1', 'slow', '0']
else:
valid = ['integer']
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, valid)
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_5(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond5.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '5'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_settings_bond_6(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond6.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '6'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_bridge_opts(opts, iface):
'''
Filters given options and outputs valid settings for BRIDGING_OPTS
If an option has a value that is not expected, this
function will log the Interface, Setting and what was expected.
'''
config = {}
if 'ports' in opts:
if isinstance(opts['ports'], list):
opts['ports'] = ' '.join(opts['ports'])
config.update({'ports': opts['ports']})
for opt in ['ageing', 'fd', 'gcint', 'hello', 'maxage']:
if opt in opts:
try:
float(opts[opt])
config.update({opt: opts[opt]})
except ValueError:
_raise_error_iface(iface, opt, ['float'])
for opt in ['bridgeprio', 'maxwait']:
if opt in opts:
if isinstance(opts[opt], int):
config.update({opt: opts[opt]})
else:
_raise_error_iface(iface, opt, ['integer'])
if 'hw' in opts:
# match 12 hex digits with either : or - as separators between pairs
if re.match('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$',
opts['hw'].lower()):
config.update({'hw': opts['hw']})
else:
_raise_error_iface(iface, 'hw', ['valid MAC address'])
for opt in ['pathcost', 'portprio']:
if opt in opts:
try:
port, cost_or_prio = opts[opt].split()
int(cost_or_prio)
config.update({opt: '{0} {1}'.format(port, cost_or_prio)})
except ValueError:
_raise_error_iface(iface, opt, ['interface integer'])
if 'stp' in opts:
if opts['stp'] in _CONFIG_TRUE:
config.update({'stp': 'on'})
elif opts['stp'] in _CONFIG_FALSE:
config.update({'stp': 'off'})
else:
_raise_error_iface(iface, 'stp', _CONFIG_TRUE + _CONFIG_FALSE)
if 'waitport' in opts:
if isinstance(opts['waitport'], int):
config.update({'waitport': opts['waitport']})
else:
values = opts['waitport'].split()
waitport_time = values.pop(0)
if waitport_time.isdigit() and values:
config.update({
'waitport': '{0} {1}'.format(
waitport_time, ' '.join(values)
)
})
else:
_raise_error_iface(iface, opt, ['integer [interfaces]'])
return config
def _parse_settings_eth(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['inet'] = salt.utils.odict.OrderedDict()
iface_data['inet6'] = salt.utils.odict.OrderedDict()
if enabled:
adapters[iface]['enabled'] = True
if opts.get('hotplug', False):
adapters[iface]['hotplug'] = True
if opts.get('enable_ipv6', None) and opts.get('iface_type', '') == 'vlan':
iface_data['inet6']['vlan_raw_device'] = (
re.sub(r'\.\d*', '', iface))
for addrfam in ['inet', 'inet6']:
if iface_type not in ['bridge']:
tmp_ethtool = _parse_ethtool_opts(opts, iface)
if tmp_ethtool:
ethtool = {}
for item in tmp_ethtool:
ethtool[_ETHTOOL_CONFIG_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['ethtool'] = ethtool
# return a list of sorted keys to ensure consistent order
iface_data[addrfam]['ethtool_keys'] = sorted(ethtool)
if iface_type == 'bridge':
bridging = _parse_bridge_opts(opts, iface)
if bridging:
iface_data[addrfam]['bridging'] = bridging
iface_data[addrfam]['bridging_keys'] = sorted(bridging)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'bond':
bonding = _parse_settings_bond(opts, iface)
if bonding:
iface_data[addrfam]['bonding'] = bonding
iface_data[addrfam]['bonding']['slaves'] = opts['slaves']
iface_data[addrfam]['bonding_keys'] = sorted(bonding)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'slave':
adapters[iface]['master'] = opts['master']
opts['proto'] = 'manual'
iface_data[addrfam]['master'] = adapters[iface]['master']
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'vlan':
iface_data[addrfam]['vlan_raw_device'] = re.sub(r'\.\d*', '', iface)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'pppoe':
tmp_ethtool = _parse_ethtool_pppoe_opts(opts, iface)
if tmp_ethtool:
for item in tmp_ethtool:
adapters[iface]['data'][addrfam][_DEB_CONFIG_PPPOE_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['addrfam'] = addrfam
opts.pop('mode', None)
for opt, val in opts.items():
inet = None
if opt.startswith('ipv4'):
opt = opt[4:]
inet = 'inet'
iface_data['inet']['addrfam'] = 'inet'
elif opt.startswith('ipv6'):
iface_data['inet6']['addrfam'] = 'inet6'
opt = opt[4:]
inet = 'inet6'
elif opt in ['ipaddr', 'address', 'ipaddresses', 'addresses', 'gateway', 'proto']:
iface_data['inet']['addrfam'] = 'inet'
inet = 'inet'
_opt = SALT_ATTR_TO_DEBIAN_ATTR_MAP.get(opt, opt)
_debopt = _opt.replace('-', '_')
for addrfam in ['inet', 'inet6']:
(valid, value, errmsg) = _validate_interface_option(_opt, val, addrfam=addrfam)
if not valid:
continue
if inet is None and _debopt not in iface_data[addrfam]:
iface_data[addrfam][_debopt] = value
elif inet == addrfam:
iface_data[addrfam][_debopt] = value
for opt in ['up_cmds', 'pre_up_cmds', 'post_up_cmds',
'down_cmds', 'pre_down_cmds', 'post_down_cmds']:
if opt in opts:
iface_data['inet'][opt] = opts[opt]
iface_data['inet6'][opt] = opts[opt]
# Remove incomplete/disabled inet blocks
for (addrfam, opt) in [('inet', 'enable_ipv4'), ('inet6', 'enable_ipv6')]:
if opts.get(opt, None) is False:
iface_data.pop(addrfam)
elif iface_data[addrfam].get('addrfam', '') != addrfam:
iface_data.pop(addrfam)
return adapters
def _parse_settings_source(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['sources'] = [opts['source']]
return adapters
def _parse_network_settings(opts, current):
'''
Filters given options and outputs valid settings for
the global network settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
current = dict((k.lower(), v) for (k, v) in six.iteritems(current))
result = {}
valid = _CONFIG_TRUE + _CONFIG_FALSE
if 'enabled' not in opts:
try:
opts['networking'] = current['networking']
_log_default_network('networking', current['networking'])
except ValueError:
_raise_error_network('networking', valid)
else:
opts['networking'] = opts['enabled']
if opts['networking'] in valid:
if opts['networking'] in _CONFIG_TRUE:
result['networking'] = 'yes'
elif opts['networking'] in _CONFIG_FALSE:
result['networking'] = 'no'
else:
_raise_error_network('networking', valid)
if 'hostname' not in opts:
try:
opts['hostname'] = current['hostname']
_log_default_network('hostname', current['hostname'])
except ValueError:
_raise_error_network('hostname', ['server1.example.com'])
if opts['hostname']:
result['hostname'] = opts['hostname']
else:
_raise_error_network('hostname', ['server1.example.com'])
if 'search' in opts:
result['search'] = opts['search']
return result
def _parse_routes(iface, opts):
'''
Filters given options and outputs valid settings for
the route settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
result = {}
if 'routes' not in opts:
_raise_error_routes(iface, 'routes', 'List of routes')
for opt in opts:
result[opt] = opts[opt]
return result
def _write_file(iface, data, folder, pattern):
'''
Writes a file to disk
'''
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
return filename
def _write_file_routes(iface, data, folder, pattern):
'''
Writes a file to disk
'''
# ifup / ifdown is executing given folder via run-parts.
# according to run-parts man-page, only filenames with this pattern are
# executed: (^[a-zA-Z0-9_-]+$)
# In order to make the routes file work for vlan interfaces
# (default would have been in example /etc/network/if-up.d/route-bond0.12)
# these dots in the iface name need to be replaced by underscores, so it
# can be executed by run-parts
iface = iface.replace('.', '_')
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
__salt__['file.set_mode'](filename, '0755')
return filename
def _read_temp(data):
'''
Return what would be written to disk
'''
tout = StringIO()
tout.write(data)
tout.seek(0)
output = tout.readlines()
tout.close()
return output
def _read_temp_ifaces(iface, data):
'''
Return what would be written to disk for interfaces
'''
try:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': data})
# Return as an array so the difflib works
return [item + '\n' for item in ifcfg.split('\n')]
def _write_file_ifaces(iface, data, **settings):
'''
Writes a file to disk
'''
try:
eth_template = JINJA.get_template('debian_eth.jinja')
source_template = JINJA.get_template('debian_source.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
# Read /etc/network/interfaces into a dict
adapters = _parse_interfaces()
# Apply supplied settings over on-disk settings
adapters[iface] = data
ifcfg = ''
for adapter in adapters:
if 'type' in adapters[adapter] and adapters[adapter]['type'] == 'source':
tmp = source_template.render({'name': adapter, 'data': adapters[adapter]})
else:
tmp = eth_template.render({'name': adapter, 'data': adapters[adapter]})
ifcfg = ifcfg + tmp
if adapter == iface:
saved_ifcfg = tmp
_SEPARATE_FILE = False
if 'filename' in settings:
if not settings['filename'].startswith('/'):
filename = '{0}/{1}'.format(_DEB_NETWORK_DIR, settings['filename'])
else:
filename = settings['filename']
_SEPARATE_FILE = True
else:
if 'filename' in adapters[adapter]['data']:
filename = adapters[adapter]['data']
else:
filename = _DEB_NETWORK_FILE
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
if _SEPARATE_FILE:
fout.write(salt.utils.stringutils.to_str(saved_ifcfg))
else:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return saved_ifcfg.split('\n')
def _write_file_ppp_ifaces(iface, data):
'''
Writes a file to disk
'''
try:
template = JINJA.get_template('debian_ppp_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_ppp_eth.jinja')
return ''
adapters = _parse_interfaces()
adapters[iface] = data
ifcfg = ''
tmp = template.render({'data': adapters[iface]})
ifcfg = tmp + ifcfg
filename = _DEB_PPP_DIR + '/' + adapters[iface]['data']['inet']['provider']
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.fopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return filename
def build_bond(iface, **settings):
'''
Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb
'''
deb_major = __grains__['osrelease'][:1]
opts = _parse_settings_bond(settings, iface)
try:
template = JINJA.get_template('conf.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template conf.jinja')
return ''
data = template.render({'name': iface, 'bonding': opts})
if 'test' in settings and settings['test']:
return _read_temp(data)
_write_file(iface, data, _DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
if deb_major == '5':
for line_type in ('alias', 'options'):
cmd = ['sed', '-i', '-e', r'/^{0}\s{1}.*/d'.format(line_type, iface),
'/etc/modprobe.conf']
__salt__['cmd.run'](cmd, python_shell=False)
__salt__['file.append']('/etc/modprobe.conf', path)
# Load kernel module
__salt__['kmod.load']('bonding')
# install ifenslave-2.6
__salt__['pkg.install']('ifenslave-2.6')
return _read_file(path)
def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'vlan':
settings['vlan'] = 'yes'
__salt__['pkg.install']('vlan')
elif iface_type == 'pppoe':
settings['pppoe'] = 'yes'
if not __salt__['pkg.version']('ppp'):
inst = __salt__['pkg.install']('ppp')
elif iface_type == 'bond':
if 'slaves' not in settings:
msg = 'slaves is a required setting for bond interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'bridge':
if 'ports' not in settings:
msg = (
'ports is a required setting for bridge interfaces on Debian '
'or Ubuntu based systems'
)
log.error(msg)
raise AttributeError(msg)
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'pppoe']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
if iface_type in ['source']:
opts = _parse_settings_source(settings, iface_type, enabled, iface)
if 'test' in settings and settings['test']:
return _read_temp_ifaces(iface, opts[iface])
ifcfg = _write_file_ifaces(iface, opts[iface], **settings)
if iface_type == 'pppoe':
_write_file_ppp_ifaces(iface, opts[iface])
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg]
def build_routes(iface, **settings):
'''
Add route scripts for a network interface using up commands.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
'''
opts = _parse_routes(iface, settings)
try:
template = JINJA.get_template('route_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template route_eth.jinja')
return ''
add_routecfg = template.render(route_type='add',
routes=opts['routes'],
iface=iface)
del_routecfg = template.render(route_type='del',
routes=opts['routes'],
iface=iface)
if 'test' in settings and settings['test']:
return _read_temp(add_routecfg + del_routecfg)
filename = _write_file_routes(iface,
add_routecfg,
_DEB_NETWORK_UP_DIR,
'route-{0}')
results = _read_file(filename)
filename = _write_file_routes(iface,
del_routecfg,
_DEB_NETWORK_DOWN_DIR,
'route-{0}')
results += _read_file(filename)
return results
def down(iface, iface_type):
'''
Shutdown a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.down eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought down.
if iface_type not in ['slave', 'source']:
return __salt__['cmd.run'](['ifdown', iface])
return None
def get_bond(iface):
'''
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
'''
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
return _read_file(path)
def get_interface(iface):
'''
Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
adapters = _parse_interfaces()
if iface in adapters:
try:
if iface == 'source':
template = JINJA.get_template('debian_source.jinja')
else:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': adapters[iface]})
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg.split('\n')]
else:
return []
def up(iface, iface_type): # pylint: disable=C0103
'''
Start up a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.up eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought up.
if iface_type not in ('slave', 'source'):
return __salt__['cmd.run'](['ifup', iface])
return None
def get_network_settings():
'''
Return the contents of the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_network_settings
'''
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
settings = {}
if __salt__['service.available']('networking'):
if __salt__['service.status']('networking'):
settings['networking'] = "yes"
else:
settings['networking'] = "no"
else:
settings['networking'] = "no"
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
settings['hostname'] = hostname
settings['domainname'] = domainname
settings['searchdomain'] = searchdomain
else:
settings = _parse_current_network_settings()
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(settings)
return _read_temp(network)
def get_routes(iface):
'''
Return the routes for the interface
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0
'''
filename = os.path.join(_DEB_NETWORK_UP_DIR, 'route-{0}'.format(iface))
results = _read_file(filename)
filename = os.path.join(_DEB_NETWORK_DOWN_DIR, 'route-{0}'.format(iface))
results += _read_file(filename)
return results
def apply_network_settings(**settings):
'''
Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings
'''
if 'require_reboot' not in settings:
settings['require_reboot'] = False
if 'apply_hostname' not in settings:
settings['apply_hostname'] = False
hostname_res = True
if settings['apply_hostname'] in _CONFIG_TRUE:
if 'hostname' in settings:
hostname_res = __salt__['network.mod_hostname'](settings['hostname'])
else:
log.warning(
'The network state sls is trying to apply hostname '
'changes but no hostname is defined.'
)
hostname_res = False
res = True
if settings['require_reboot'] in _CONFIG_TRUE:
log.warning(
'The network state sls is requiring a reboot of the system to '
'properly apply network configuration.'
)
res = True
else:
stop = __salt__['service.stop']('networking')
time.sleep(2)
res = stop and __salt__['service.start']('networking')
return hostname_res and res
def build_network_settings(**settings):
'''
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
'''
changes = []
# Read current configuration and store default values
current_network_settings = _parse_current_network_settings()
# Build settings
opts = _parse_network_settings(settings, current_network_settings)
# Ubuntu has moved away from /etc/default/networking
# beginning with the 12.04 release so we disable or enable
# the networking related services on boot
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
if opts['networking'] == 'yes':
service_cmd = 'service.enable'
else:
service_cmd = 'service.disable'
if __salt__['service.available']('NetworkManager'):
__salt__[service_cmd]('NetworkManager')
if __salt__['service.available']('networking'):
__salt__[service_cmd]('networking')
else:
try:
template = JINJA.get_template('network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template network.jinja')
return ''
network = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(network)
# Write settings
_write_file_network(network, _DEB_NETWORKING_FILE, True)
# Get hostname and domain from opts
sline = opts['hostname'].split('.', 1)
opts['hostname'] = sline[0]
current_domainname = current_network_settings['domainname']
current_searchdomain = current_network_settings['searchdomain']
new_domain = False
if len(sline) > 1:
new_domainname = sline[1]
if new_domainname != current_domainname:
domainname = new_domainname
opts['domainname'] = new_domainname
new_domain = True
else:
domainname = current_domainname
opts['domainname'] = domainname
else:
domainname = current_domainname
opts['domainname'] = domainname
new_search = False
if 'search' in opts:
new_searchdomain = opts['search']
if new_searchdomain != current_searchdomain:
searchdomain = new_searchdomain
opts['searchdomain'] = new_searchdomain
new_search = True
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
# If the domain changes, then we should write the resolv.conf file.
if new_domain or new_search:
# Look for existing domain line and update if necessary
resolve = _parse_resolve()
domain_prog = re.compile(r'domain\s+')
search_prog = re.compile(r'search\s+')
new_contents = []
for item in _read_file(_DEB_RESOLV_FILE):
if domain_prog.match(item):
item = 'domain {0}'.format(domainname)
elif search_prog.match(item):
item = 'search {0}'.format(searchdomain)
new_contents.append(item)
# A domain line didn't exist so we'll add one in
# with the new domainname
if 'domain' not in resolve:
new_contents.insert(0, 'domain {0}' . format(domainname))
# A search line didn't exist so we'll add one in
# with the new search domain
if 'search' not in resolve:
new_contents.insert('domain' in resolve, 'search {0}'.format(searchdomain))
new_resolv = '\n'.join(new_contents)
# Write /etc/resolv.conf
if not ('test' in settings and settings['test']):
_write_file_network(new_resolv, _DEB_RESOLV_FILE)
# used for returning the results back
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(opts)
changes.extend(_read_temp(network))
return changes
|
saltstack/salt
|
salt/modules/debian_ip.py
|
_read_temp
|
python
|
def _read_temp(data):
'''
Return what would be written to disk
'''
tout = StringIO()
tout.write(data)
tout.seek(0)
output = tout.readlines()
tout.close()
return output
|
Return what would be written to disk
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_ip.py#L1453-L1463
| null |
# -*- coding: utf-8 -*-
'''
The networking module for Debian-based distros
References:
* http://www.debian.org/doc/manuals/debian-reference/ch05.en.html
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import functools
import logging
import os.path
import os
import re
import time
# Import third party libs
import jinja2
import jinja2.exceptions
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error,no-name-in-module
# Import salt libs
import salt.utils.dns
import salt.utils.files
import salt.utils.odict
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.validate.net
# Set up logging
log = logging.getLogger(__name__)
# Set up template environment
JINJA = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'debian_ip')
)
)
# Define the module's virtual name
__virtualname__ = 'ip'
def __virtual__():
'''
Confine this module to Debian-based distros
'''
if __grains__['os_family'] == 'Debian':
return __virtualname__
return (False, 'The debian_ip module could not be loaded: '
'unsupported OS family')
_ETHTOOL_CONFIG_OPTS = {
'speed': 'link-speed',
'duplex': 'link-duplex',
'autoneg': 'ethernet-autoneg',
'ethernet-port': 'ethernet-port',
'wol': 'ethernet-wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'rx': 'offload-rx',
'tx': 'offload-tx',
'sg': 'offload-sg',
'tso': 'offload-tso',
'ufo': 'offload-ufo',
'gso': 'offload-gso',
'gro': 'offload-gro',
'lro': 'offload-lro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_REV_ETHTOOL_CONFIG_OPTS = {
'link-speed': 'speed',
'link-duplex': 'duplex',
'ethernet-autoneg': 'autoneg',
'ethernet-port': 'ethernet-port',
'ethernet-wol': 'wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'offload-rx': 'rx',
'offload-tx': 'tx',
'offload-sg': 'sg',
'offload-tso': 'tso',
'offload-ufo': 'ufo',
'offload-gso': 'gso',
'offload-lro': 'lro',
'offload-gro': 'gro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_DEB_CONFIG_PPPOE_OPTS = {
'user': 'user',
'password': 'password',
'provider': 'provider',
'pppoe_iface': 'pppoe_iface',
'noipdefault': 'noipdefault',
'usepeerdns': 'usepeerdns',
'defaultroute': 'defaultroute',
'holdoff': 'holdoff',
'maxfail': 'maxfail',
'hide-password': 'hide-password',
'lcp-echo-interval': 'lcp-echo-interval',
'lcp-echo-failure': 'lcp-echo-failure',
'connect': 'connect',
'noauth': 'noauth',
'persist': 'persist',
'mtu': 'mtu',
'noaccomp': 'noaccomp',
'linkname': 'linkname',
}
_DEB_ROUTES_FILE = '/etc/network/routes'
_DEB_NETWORK_FILE = '/etc/network/interfaces'
_DEB_NETWORK_DIR = '/etc/network/interfaces.d/'
_DEB_NETWORK_UP_DIR = '/etc/network/if-up.d/'
_DEB_NETWORK_DOWN_DIR = '/etc/network/if-down.d/'
_DEB_NETWORK_CONF_FILES = '/etc/modprobe.d/'
_DEB_NETWORKING_FILE = '/etc/default/networking'
_DEB_HOSTNAME_FILE = '/etc/hostname'
_DEB_RESOLV_FILE = '/etc/resolv.conf'
_DEB_PPP_DIR = '/etc/ppp/peers/'
_CONFIG_TRUE = ['yes', 'on', 'true', '1', True]
_CONFIG_FALSE = ['no', 'off', 'false', '0', False]
_IFACE_TYPES = [
'eth', 'bond', 'alias', 'clone',
'ipsec', 'dialup', 'bridge', 'slave',
'vlan', 'pppoe', 'source',
]
def _error_msg_iface(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, '|'.join(str(e) for e in expected))
def _error_msg_routes(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, expected)
def _log_default_iface(iface, opt, value):
log.info(
'Using default option -- Interface: %s Option: %s Value: %s',
iface, opt, value
)
def _error_msg_network(option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]'
return msg.format(option, '|'.join(str(e) for e in expected))
def _log_default_network(opt, value):
log.info('Using existing setting -- Setting: %s Value: %s', opt, value)
def _raise_error_iface(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_iface(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_network(option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_network(option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_routes(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_routes(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _read_file(path):
'''
Reads and returns the contents of a text file
'''
try:
with salt.utils.files.flopen(path, 'rb') as contents:
return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]
except (OSError, IOError):
return ''
def _parse_resolve():
'''
Parse /etc/resolv.conf
'''
return salt.utils.dns.parse_resolv(_DEB_RESOLV_FILE)
def _parse_domainname():
'''
Parse /etc/resolv.conf and return domainname
'''
return _parse_resolve().get('domain', '')
def _parse_searchdomain():
'''
Parse /etc/resolv.conf and return searchdomain
'''
return _parse_resolve().get('search', '')
def _parse_hostname():
'''
Parse /etc/hostname and return hostname
'''
contents = _read_file(_DEB_HOSTNAME_FILE)
if contents:
return contents[0].split('\n')[0]
else:
return ''
def _parse_current_network_settings():
'''
Parse /etc/default/networking and return current configuration
'''
opts = salt.utils.odict.OrderedDict()
opts['networking'] = ''
if os.path.isfile(_DEB_NETWORKING_FILE):
with salt.utils.files.fopen(_DEB_NETWORKING_FILE) as contents:
for line in contents:
salt.utils.stringutils.to_unicode(line)
if line.startswith('#'):
continue
elif line.startswith('CONFIGURE_INTERFACES'):
opts['networking'] = line.split('=', 1)[1].strip()
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
opts['hostname'] = hostname
opts['domainname'] = domainname
opts['searchdomain'] = searchdomain
return opts
# def __validator_func(value):
# return (valid: True/False, (transformed) value, error message)
def __ipv4_quad(value):
'''validate an IPv4 address'''
return (salt.utils.validate.net.ipv4_addr(value), value,
'dotted IPv4 address')
def __ipv6(value):
'''validate an IPv6 address'''
return (salt.utils.validate.net.ipv6_addr(value), value,
'IPv6 address')
def __mac(value):
'''validate a mac address'''
return (salt.utils.validate.net.mac(value), value,
'MAC address')
def __anything(value):
return (True, value, None)
def __int(value):
'''validate an integer'''
valid, _value = False, value
try:
_value = int(value)
valid = True
except ValueError:
pass
return (valid, _value, 'integer')
def __float(value):
'''validate a float'''
valid, _value = False, value
try:
_value = float(value)
valid = True
except ValueError:
pass
return (valid, _value, 'float')
def __ipv4_netmask(value):
'''validate an IPv4 dotted quad or integer CIDR netmask'''
valid, errmsg = False, 'dotted quad or integer CIDR (0->32)'
valid, value, _ = __int(value)
if not (valid and 0 <= value <= 32):
valid = salt.utils.validate.net.netmask(value)
return (valid, value, errmsg)
def __ipv6_netmask(value):
'''validate an IPv6 integer netmask'''
valid, errmsg = False, 'IPv6 netmask (0->128)'
valid, value, _ = __int(value)
valid = (valid and 0 <= value <= 128)
return (valid, value, errmsg)
def __within2(value, within=None, errmsg=None, dtype=None):
'''validate that a value is in ``within`` and optionally a ``dtype``'''
valid, _value = False, value
if dtype:
try:
_value = dtype(value) # TODO: this is a bit loose when dtype is a class
valid = _value in within
except ValueError:
pass
else:
valid = _value in within
if errmsg is None:
if dtype:
typename = getattr(dtype, '__name__',
hasattr(dtype, '__class__')
and getattr(dtype.__class__, 'name', dtype))
errmsg = '{0} within \'{1}\''.format(typename, within)
else:
errmsg = 'within \'{0}\''.format(within)
return (valid, _value, errmsg)
def __within(within=None, errmsg=None, dtype=None):
return functools.partial(__within2, within=within,
errmsg=errmsg, dtype=dtype)
def __space_delimited_list(value):
'''validate that a value contains one or more space-delimited values'''
if isinstance(value, six.string_types):
value = value.strip().split()
if hasattr(value, '__iter__') and value != []:
return (True, value, 'space-delimited string')
else:
return (False, value, '{0} is not a valid space-delimited value.\n'.format(value))
SALT_ATTR_TO_DEBIAN_ATTR_MAP = {
'dns': 'dns-nameservers',
'search': 'dns-search',
'hwaddr': 'hwaddress', # TODO: this limits bootp functionality
'ipaddr': 'address',
'ipaddrs': 'addresses',
}
DEBIAN_ATTR_TO_SALT_ATTR_MAP = dict(
(v, k) for (k, v) in six.iteritems(SALT_ATTR_TO_DEBIAN_ATTR_MAP))
# TODO
DEBIAN_ATTR_TO_SALT_ATTR_MAP['address'] = 'address'
DEBIAN_ATTR_TO_SALT_ATTR_MAP['hwaddress'] = 'hwaddress'
IPV4_VALID_PROTO = ['bootp', 'dhcp', 'static', 'manual', 'loopback', 'ppp']
IPV4_ATTR_MAP = {
'proto': __within(IPV4_VALID_PROTO, dtype=six.text_type),
# ipv4 static & manual
'address': __ipv4_quad,
'addresses': __anything,
'netmask': __ipv4_netmask,
'broadcast': __ipv4_quad,
'metric': __int,
'gateway': __ipv4_quad, # supports a colon-delimited list
'pointopoint': __ipv4_quad,
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'link', 'host'], dtype=six.text_type),
# dhcp
'hostname': __anything,
'leasehours': __int,
'leasetime': __int,
'vendor': __anything,
'client': __anything,
# bootp
'bootfile': __anything,
'server': __ipv4_quad,
'hwaddr': __mac,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'dstaddr': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# bond
'slaves': __anything,
# ppp
'provider': __anything,
'unit': __int,
'options': __anything,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
#
'network': __anything, # i don't know what this is
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
IPV6_VALID_PROTO = ['auto', 'loopback', 'static', 'manual',
'dhcp', 'v4tunnel', '6to4']
IPV6_ATTR_MAP = {
'proto': __within(IPV6_VALID_PROTO),
# ipv6 static & manual
'address': __ipv6,
'addresses': __anything,
'netmask': __ipv6_netmask,
'broadcast': __ipv6,
'gateway': __ipv6, # supports a colon-delimited list
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'site', 'link', 'host'], dtype=six.text_type),
# inet6 auto
'privext': __within([0, 1, 2], dtype=int),
'dhcp': __within([0, 1], dtype=int),
# inet6 static & manual & dhcp
'media': __anything,
'accept_ra': __within([0, 1], dtype=int),
'autoconf': __within([0, 1], dtype=int),
'preferred-lifetime': __int,
'dad-attempts': __int, # 0 to disable
'dad-interval': __float,
# bond
'slaves': __anything,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
WIRELESS_ATTR_MAP = {
'wireless-essid': __anything,
'wireless-mode': __anything, # TODO
'wpa-ap-scan': __within([0, 1, 2], dtype=int), # TODO
'wpa-conf': __anything,
'wpa-driver': __anything,
'wpa-group': __anything,
'wpa-key-mgmt': __anything,
'wpa-pairwise': __anything,
'wpa-psk': __anything,
'wpa-proto': __anything, # partial(__within,
'wpa-roam': __anything,
'wpa-ssid': __anything, # TODO
}
ATTRMAPS = {
'inet': [IPV4_ATTR_MAP, WIRELESS_ATTR_MAP],
'inet6': [IPV6_ATTR_MAP, WIRELESS_ATTR_MAP]
}
def _validate_interface_option(attr, value, addrfam='inet'):
'''lookup the validation function for a [addrfam][attr] and
return the results
:param attr: attribute name
:param value: raw setting value
:param addrfam: address family (inet, inet6,
'''
valid, _value, errmsg = False, value, 'Unknown validator'
attrmaps = ATTRMAPS.get(addrfam, [])
for attrmap in attrmaps:
if attr in attrmap:
validate_func = attrmap[attr]
(valid, _value, errmsg) = validate_func(value)
break
return (valid, _value, errmsg)
def _attrmaps_contain_attr(attr):
return (
attr in WIRELESS_ATTR_MAP or
attr in IPV4_ATTR_MAP or
attr in IPV6_ATTR_MAP)
def _parse_interfaces(interface_files=None):
'''
Parse /etc/network/interfaces and return current configured interfaces
'''
if interface_files is None:
interface_files = []
# Add this later.
if os.path.exists(_DEB_NETWORK_DIR):
interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]
if os.path.isfile(_DEB_NETWORK_FILE):
interface_files.insert(0, _DEB_NETWORK_FILE)
adapters = salt.utils.odict.OrderedDict()
method = -1
for interface_file in interface_files:
with salt.utils.files.fopen(interface_file) as interfaces:
# This ensures iface_dict exists, but does not ensure we're not reading a new interface.
iface_dict = {}
for line in interfaces:
line = salt.utils.stringutils.to_unicode(line)
# Identify the clauses by the first word of each line.
# Go to the next line if the current line is a comment
# or all spaces.
if line.lstrip().startswith('#') or line.isspace():
continue
# Parse the iface clause
if line.startswith('iface'):
sline = line.split()
if len(sline) != 4:
msg = 'Interface file malformed: {0}.'
msg = msg.format(sline)
log.error(msg)
raise AttributeError(msg)
iface_name = sline[1]
addrfam = sline[2]
method = sline[3]
# Create item in dict, if not already there
if iface_name not in adapters:
adapters[iface_name] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters[iface_name]:
adapters[iface_name]['data'] = salt.utils.odict.OrderedDict()
if addrfam not in adapters[iface_name]['data']:
adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict()
iface_dict = adapters[iface_name]['data'][addrfam]
iface_dict['addrfam'] = addrfam
iface_dict['proto'] = method
iface_dict['filename'] = interface_file
# Parse the detail clauses.
elif line[0].isspace():
sline = line.split()
# conf file attr: dns-nameservers
# salt states.network attr: dns
attr, valuestr = line.rstrip().split(None, 1)
if _attrmaps_contain_attr(attr):
if '-' in attr:
attrname = attr.replace('-', '_')
else:
attrname = attr
(valid, value, errmsg) = _validate_interface_option(
attr, valuestr, addrfam)
if attrname == 'address' and 'address' in iface_dict:
if 'addresses' not in iface_dict:
iface_dict['addresses'] = []
iface_dict['addresses'].append(value)
else:
iface_dict[attrname] = value
elif attr in _REV_ETHTOOL_CONFIG_OPTS:
if 'ethtool' not in iface_dict:
iface_dict['ethtool'] = salt.utils.odict.OrderedDict()
iface_dict['ethtool'][attr] = valuestr
elif attr.startswith('bond'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bonding' not in iface_dict:
iface_dict['bonding'] = salt.utils.odict.OrderedDict()
iface_dict['bonding'][opt] = valuestr
elif attr.startswith('bridge'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bridging' not in iface_dict:
iface_dict['bridging'] = salt.utils.odict.OrderedDict()
iface_dict['bridging'][opt] = valuestr
elif attr in ['up', 'pre-up', 'post-up',
'down', 'pre-down', 'post-down']:
cmd = valuestr
cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr))
if cmd_key not in iface_dict:
iface_dict[cmd_key] = []
iface_dict[cmd_key].append(cmd)
elif line.startswith('auto'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['enabled'] = True
elif line.startswith('allow-hotplug'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['hotplug'] = True
elif line.startswith('source'):
if 'source' not in adapters:
adapters['source'] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters['source']:
adapters['source']['data'] = salt.utils.odict.OrderedDict()
adapters['source']['data']['sources'] = []
adapters['source']['data']['sources'].append(line.split()[1])
# Return a sorted list of the keys for bond, bridge and ethtool options to
# ensure a consistent order
for iface_name in adapters:
if iface_name == 'source':
continue
if 'data' not in adapters[iface_name]:
msg = 'Interface file malformed for interface: {0}.'.format(iface_name)
log.error(msg)
adapters.pop(iface_name)
continue
for opt in ['ethtool', 'bonding', 'bridging']:
for inet in ['inet', 'inet6']:
if inet in adapters[iface_name]['data']:
if opt in adapters[iface_name]['data'][inet]:
opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys())
adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys
return adapters
def _parse_ethtool_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
if 'autoneg' in opts:
if opts['autoneg'] in _CONFIG_TRUE:
config.update({'autoneg': 'on'})
elif opts['autoneg'] in _CONFIG_FALSE:
config.update({'autoneg': 'off'})
else:
_raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE)
if 'duplex' in opts:
valid = ['full', 'half']
if opts['duplex'] in valid:
config.update({'duplex': opts['duplex']})
else:
_raise_error_iface(iface, 'duplex', valid)
if 'speed' in opts:
valid = ['10', '100', '1000', '10000']
if six.text_type(opts['speed']) in valid:
config.update({'speed': opts['speed']})
else:
_raise_error_iface(iface, opts['speed'], valid)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'on'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'off'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_ethtool_pppoe_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
for opt in _DEB_CONFIG_PPPOE_OPTS:
if opt in opts:
config[opt] = opts[opt]
if 'provider' in opts and not opts['provider']:
_raise_error_iface(iface, 'provider', _CONFIG_TRUE + _CONFIG_FALSE)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('noipdefault', 'usepeerdns', 'defaultroute', 'hide-password', 'noauth', 'persist', 'noaccomp'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'True'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'False'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_settings_bond(opts, iface):
'''
Filters given options and outputs valid settings for requested
operation. If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond_def = {
# 803.ad aggregation selection logic
# 0 for stable (default)
# 1 for bandwidth
# 2 for count
'ad_select': '0',
# Max number of transmit queues (default = 16)
'tx_queues': '16',
# Link monitoring in milliseconds. Most NICs support this
'miimon': '100',
# ARP interval in milliseconds
'arp_interval': '250',
# Delay before considering link down in milliseconds (miimon * 2)
'downdelay': '200',
# lacp_rate 0: Slow - every 30 seconds
# lacp_rate 1: Fast - every 1 second
'lacp_rate': '0',
# Max bonds for this driver
'max_bonds': '1',
# Specifies the time, in milliseconds, to wait before
# enabling a slave after a link recovery has been
# detected. Only used with miimon.
'updelay': '0',
# Used with miimon.
# On: driver sends mii
# Off: ethtool sends mii
'use_carrier': 'on',
# Default. Don't change unless you know what you are doing.
'xmit_hash_policy': 'layer2',
}
if opts['mode'] in ['balance-rr', '0']:
log.info('Device: %s Bonding Mode: load balancing (round-robin)', iface)
return _parse_settings_bond_0(opts, iface, bond_def)
elif opts['mode'] in ['active-backup', '1']:
log.info('Device: %s Bonding Mode: fault-tolerance (active-backup)', iface)
return _parse_settings_bond_1(opts, iface, bond_def)
elif opts['mode'] in ['balance-xor', '2']:
log.info('Device: %s Bonding Mode: load balancing (xor)', iface)
return _parse_settings_bond_2(opts, iface, bond_def)
elif opts['mode'] in ['broadcast', '3']:
log.info('Device: %s Bonding Mode: fault-tolerance (broadcast)', iface)
return _parse_settings_bond_3(opts, iface, bond_def)
elif opts['mode'] in ['802.3ad', '4']:
log.info('Device: %s Bonding Mode: IEEE 802.3ad Dynamic link '
'aggregation', iface)
return _parse_settings_bond_4(opts, iface, bond_def)
elif opts['mode'] in ['balance-tlb', '5']:
log.info('Device: %s Bonding Mode: transmit load balancing', iface)
return _parse_settings_bond_5(opts, iface, bond_def)
elif opts['mode'] in ['balance-alb', '6']:
log.info('Device: %s Bonding Mode: adaptive load balancing', iface)
return _parse_settings_bond_6(opts, iface, bond_def)
else:
valid = [
'0', '1', '2', '3', '4', '5', '6',
'balance-rr', 'active-backup', 'balance-xor',
'broadcast', '802.3ad', 'balance-tlb', 'balance-alb'
]
_raise_error_iface(iface, 'mode', valid)
def _parse_settings_bond_0(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond0.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '0'}
# ARP targets in n.n.n.n form
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
return bond
def _parse_settings_bond_1(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '1'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
if not (__grains__['os'] == "Ubuntu" and __grains__['osrelease_info'][0] >= 16):
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_2(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond2.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '2'}
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_3(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond3.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '3'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_4(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond4.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '4'}
for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']:
if binding in opts:
if binding == 'lacp_rate':
if opts[binding] == 'fast':
opts.update({binding: '1'})
if opts[binding] == 'slow':
opts.update({binding: '0'})
valid = ['fast', '1', 'slow', '0']
else:
valid = ['integer']
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, valid)
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_5(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond5.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '5'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_settings_bond_6(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond6.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '6'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_bridge_opts(opts, iface):
'''
Filters given options and outputs valid settings for BRIDGING_OPTS
If an option has a value that is not expected, this
function will log the Interface, Setting and what was expected.
'''
config = {}
if 'ports' in opts:
if isinstance(opts['ports'], list):
opts['ports'] = ' '.join(opts['ports'])
config.update({'ports': opts['ports']})
for opt in ['ageing', 'fd', 'gcint', 'hello', 'maxage']:
if opt in opts:
try:
float(opts[opt])
config.update({opt: opts[opt]})
except ValueError:
_raise_error_iface(iface, opt, ['float'])
for opt in ['bridgeprio', 'maxwait']:
if opt in opts:
if isinstance(opts[opt], int):
config.update({opt: opts[opt]})
else:
_raise_error_iface(iface, opt, ['integer'])
if 'hw' in opts:
# match 12 hex digits with either : or - as separators between pairs
if re.match('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$',
opts['hw'].lower()):
config.update({'hw': opts['hw']})
else:
_raise_error_iface(iface, 'hw', ['valid MAC address'])
for opt in ['pathcost', 'portprio']:
if opt in opts:
try:
port, cost_or_prio = opts[opt].split()
int(cost_or_prio)
config.update({opt: '{0} {1}'.format(port, cost_or_prio)})
except ValueError:
_raise_error_iface(iface, opt, ['interface integer'])
if 'stp' in opts:
if opts['stp'] in _CONFIG_TRUE:
config.update({'stp': 'on'})
elif opts['stp'] in _CONFIG_FALSE:
config.update({'stp': 'off'})
else:
_raise_error_iface(iface, 'stp', _CONFIG_TRUE + _CONFIG_FALSE)
if 'waitport' in opts:
if isinstance(opts['waitport'], int):
config.update({'waitport': opts['waitport']})
else:
values = opts['waitport'].split()
waitport_time = values.pop(0)
if waitport_time.isdigit() and values:
config.update({
'waitport': '{0} {1}'.format(
waitport_time, ' '.join(values)
)
})
else:
_raise_error_iface(iface, opt, ['integer [interfaces]'])
return config
def _parse_settings_eth(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['inet'] = salt.utils.odict.OrderedDict()
iface_data['inet6'] = salt.utils.odict.OrderedDict()
if enabled:
adapters[iface]['enabled'] = True
if opts.get('hotplug', False):
adapters[iface]['hotplug'] = True
if opts.get('enable_ipv6', None) and opts.get('iface_type', '') == 'vlan':
iface_data['inet6']['vlan_raw_device'] = (
re.sub(r'\.\d*', '', iface))
for addrfam in ['inet', 'inet6']:
if iface_type not in ['bridge']:
tmp_ethtool = _parse_ethtool_opts(opts, iface)
if tmp_ethtool:
ethtool = {}
for item in tmp_ethtool:
ethtool[_ETHTOOL_CONFIG_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['ethtool'] = ethtool
# return a list of sorted keys to ensure consistent order
iface_data[addrfam]['ethtool_keys'] = sorted(ethtool)
if iface_type == 'bridge':
bridging = _parse_bridge_opts(opts, iface)
if bridging:
iface_data[addrfam]['bridging'] = bridging
iface_data[addrfam]['bridging_keys'] = sorted(bridging)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'bond':
bonding = _parse_settings_bond(opts, iface)
if bonding:
iface_data[addrfam]['bonding'] = bonding
iface_data[addrfam]['bonding']['slaves'] = opts['slaves']
iface_data[addrfam]['bonding_keys'] = sorted(bonding)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'slave':
adapters[iface]['master'] = opts['master']
opts['proto'] = 'manual'
iface_data[addrfam]['master'] = adapters[iface]['master']
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'vlan':
iface_data[addrfam]['vlan_raw_device'] = re.sub(r'\.\d*', '', iface)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'pppoe':
tmp_ethtool = _parse_ethtool_pppoe_opts(opts, iface)
if tmp_ethtool:
for item in tmp_ethtool:
adapters[iface]['data'][addrfam][_DEB_CONFIG_PPPOE_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['addrfam'] = addrfam
opts.pop('mode', None)
for opt, val in opts.items():
inet = None
if opt.startswith('ipv4'):
opt = opt[4:]
inet = 'inet'
iface_data['inet']['addrfam'] = 'inet'
elif opt.startswith('ipv6'):
iface_data['inet6']['addrfam'] = 'inet6'
opt = opt[4:]
inet = 'inet6'
elif opt in ['ipaddr', 'address', 'ipaddresses', 'addresses', 'gateway', 'proto']:
iface_data['inet']['addrfam'] = 'inet'
inet = 'inet'
_opt = SALT_ATTR_TO_DEBIAN_ATTR_MAP.get(opt, opt)
_debopt = _opt.replace('-', '_')
for addrfam in ['inet', 'inet6']:
(valid, value, errmsg) = _validate_interface_option(_opt, val, addrfam=addrfam)
if not valid:
continue
if inet is None and _debopt not in iface_data[addrfam]:
iface_data[addrfam][_debopt] = value
elif inet == addrfam:
iface_data[addrfam][_debopt] = value
for opt in ['up_cmds', 'pre_up_cmds', 'post_up_cmds',
'down_cmds', 'pre_down_cmds', 'post_down_cmds']:
if opt in opts:
iface_data['inet'][opt] = opts[opt]
iface_data['inet6'][opt] = opts[opt]
# Remove incomplete/disabled inet blocks
for (addrfam, opt) in [('inet', 'enable_ipv4'), ('inet6', 'enable_ipv6')]:
if opts.get(opt, None) is False:
iface_data.pop(addrfam)
elif iface_data[addrfam].get('addrfam', '') != addrfam:
iface_data.pop(addrfam)
return adapters
def _parse_settings_source(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['sources'] = [opts['source']]
return adapters
def _parse_network_settings(opts, current):
'''
Filters given options and outputs valid settings for
the global network settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
current = dict((k.lower(), v) for (k, v) in six.iteritems(current))
result = {}
valid = _CONFIG_TRUE + _CONFIG_FALSE
if 'enabled' not in opts:
try:
opts['networking'] = current['networking']
_log_default_network('networking', current['networking'])
except ValueError:
_raise_error_network('networking', valid)
else:
opts['networking'] = opts['enabled']
if opts['networking'] in valid:
if opts['networking'] in _CONFIG_TRUE:
result['networking'] = 'yes'
elif opts['networking'] in _CONFIG_FALSE:
result['networking'] = 'no'
else:
_raise_error_network('networking', valid)
if 'hostname' not in opts:
try:
opts['hostname'] = current['hostname']
_log_default_network('hostname', current['hostname'])
except ValueError:
_raise_error_network('hostname', ['server1.example.com'])
if opts['hostname']:
result['hostname'] = opts['hostname']
else:
_raise_error_network('hostname', ['server1.example.com'])
if 'search' in opts:
result['search'] = opts['search']
return result
def _parse_routes(iface, opts):
'''
Filters given options and outputs valid settings for
the route settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
result = {}
if 'routes' not in opts:
_raise_error_routes(iface, 'routes', 'List of routes')
for opt in opts:
result[opt] = opts[opt]
return result
def _write_file(iface, data, folder, pattern):
'''
Writes a file to disk
'''
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
return filename
def _write_file_routes(iface, data, folder, pattern):
'''
Writes a file to disk
'''
# ifup / ifdown is executing given folder via run-parts.
# according to run-parts man-page, only filenames with this pattern are
# executed: (^[a-zA-Z0-9_-]+$)
# In order to make the routes file work for vlan interfaces
# (default would have been in example /etc/network/if-up.d/route-bond0.12)
# these dots in the iface name need to be replaced by underscores, so it
# can be executed by run-parts
iface = iface.replace('.', '_')
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
__salt__['file.set_mode'](filename, '0755')
return filename
def _write_file_network(data, filename, create=False):
'''
Writes a file to disk
If file does not exist, only create if create
argument is True
'''
if not os.path.exists(filename) and not create:
msg = '{0} cannot be written. {0} does not exist\
and create is set to False'
msg = msg.format(filename)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
def _read_temp_ifaces(iface, data):
'''
Return what would be written to disk for interfaces
'''
try:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': data})
# Return as an array so the difflib works
return [item + '\n' for item in ifcfg.split('\n')]
def _write_file_ifaces(iface, data, **settings):
'''
Writes a file to disk
'''
try:
eth_template = JINJA.get_template('debian_eth.jinja')
source_template = JINJA.get_template('debian_source.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
# Read /etc/network/interfaces into a dict
adapters = _parse_interfaces()
# Apply supplied settings over on-disk settings
adapters[iface] = data
ifcfg = ''
for adapter in adapters:
if 'type' in adapters[adapter] and adapters[adapter]['type'] == 'source':
tmp = source_template.render({'name': adapter, 'data': adapters[adapter]})
else:
tmp = eth_template.render({'name': adapter, 'data': adapters[adapter]})
ifcfg = ifcfg + tmp
if adapter == iface:
saved_ifcfg = tmp
_SEPARATE_FILE = False
if 'filename' in settings:
if not settings['filename'].startswith('/'):
filename = '{0}/{1}'.format(_DEB_NETWORK_DIR, settings['filename'])
else:
filename = settings['filename']
_SEPARATE_FILE = True
else:
if 'filename' in adapters[adapter]['data']:
filename = adapters[adapter]['data']
else:
filename = _DEB_NETWORK_FILE
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
if _SEPARATE_FILE:
fout.write(salt.utils.stringutils.to_str(saved_ifcfg))
else:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return saved_ifcfg.split('\n')
def _write_file_ppp_ifaces(iface, data):
'''
Writes a file to disk
'''
try:
template = JINJA.get_template('debian_ppp_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_ppp_eth.jinja')
return ''
adapters = _parse_interfaces()
adapters[iface] = data
ifcfg = ''
tmp = template.render({'data': adapters[iface]})
ifcfg = tmp + ifcfg
filename = _DEB_PPP_DIR + '/' + adapters[iface]['data']['inet']['provider']
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.fopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return filename
def build_bond(iface, **settings):
'''
Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb
'''
deb_major = __grains__['osrelease'][:1]
opts = _parse_settings_bond(settings, iface)
try:
template = JINJA.get_template('conf.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template conf.jinja')
return ''
data = template.render({'name': iface, 'bonding': opts})
if 'test' in settings and settings['test']:
return _read_temp(data)
_write_file(iface, data, _DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
if deb_major == '5':
for line_type in ('alias', 'options'):
cmd = ['sed', '-i', '-e', r'/^{0}\s{1}.*/d'.format(line_type, iface),
'/etc/modprobe.conf']
__salt__['cmd.run'](cmd, python_shell=False)
__salt__['file.append']('/etc/modprobe.conf', path)
# Load kernel module
__salt__['kmod.load']('bonding')
# install ifenslave-2.6
__salt__['pkg.install']('ifenslave-2.6')
return _read_file(path)
def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'vlan':
settings['vlan'] = 'yes'
__salt__['pkg.install']('vlan')
elif iface_type == 'pppoe':
settings['pppoe'] = 'yes'
if not __salt__['pkg.version']('ppp'):
inst = __salt__['pkg.install']('ppp')
elif iface_type == 'bond':
if 'slaves' not in settings:
msg = 'slaves is a required setting for bond interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'bridge':
if 'ports' not in settings:
msg = (
'ports is a required setting for bridge interfaces on Debian '
'or Ubuntu based systems'
)
log.error(msg)
raise AttributeError(msg)
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'pppoe']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
if iface_type in ['source']:
opts = _parse_settings_source(settings, iface_type, enabled, iface)
if 'test' in settings and settings['test']:
return _read_temp_ifaces(iface, opts[iface])
ifcfg = _write_file_ifaces(iface, opts[iface], **settings)
if iface_type == 'pppoe':
_write_file_ppp_ifaces(iface, opts[iface])
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg]
def build_routes(iface, **settings):
'''
Add route scripts for a network interface using up commands.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
'''
opts = _parse_routes(iface, settings)
try:
template = JINJA.get_template('route_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template route_eth.jinja')
return ''
add_routecfg = template.render(route_type='add',
routes=opts['routes'],
iface=iface)
del_routecfg = template.render(route_type='del',
routes=opts['routes'],
iface=iface)
if 'test' in settings and settings['test']:
return _read_temp(add_routecfg + del_routecfg)
filename = _write_file_routes(iface,
add_routecfg,
_DEB_NETWORK_UP_DIR,
'route-{0}')
results = _read_file(filename)
filename = _write_file_routes(iface,
del_routecfg,
_DEB_NETWORK_DOWN_DIR,
'route-{0}')
results += _read_file(filename)
return results
def down(iface, iface_type):
'''
Shutdown a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.down eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought down.
if iface_type not in ['slave', 'source']:
return __salt__['cmd.run'](['ifdown', iface])
return None
def get_bond(iface):
'''
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
'''
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
return _read_file(path)
def get_interface(iface):
'''
Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
adapters = _parse_interfaces()
if iface in adapters:
try:
if iface == 'source':
template = JINJA.get_template('debian_source.jinja')
else:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': adapters[iface]})
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg.split('\n')]
else:
return []
def up(iface, iface_type): # pylint: disable=C0103
'''
Start up a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.up eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought up.
if iface_type not in ('slave', 'source'):
return __salt__['cmd.run'](['ifup', iface])
return None
def get_network_settings():
'''
Return the contents of the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_network_settings
'''
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
settings = {}
if __salt__['service.available']('networking'):
if __salt__['service.status']('networking'):
settings['networking'] = "yes"
else:
settings['networking'] = "no"
else:
settings['networking'] = "no"
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
settings['hostname'] = hostname
settings['domainname'] = domainname
settings['searchdomain'] = searchdomain
else:
settings = _parse_current_network_settings()
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(settings)
return _read_temp(network)
def get_routes(iface):
'''
Return the routes for the interface
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0
'''
filename = os.path.join(_DEB_NETWORK_UP_DIR, 'route-{0}'.format(iface))
results = _read_file(filename)
filename = os.path.join(_DEB_NETWORK_DOWN_DIR, 'route-{0}'.format(iface))
results += _read_file(filename)
return results
def apply_network_settings(**settings):
'''
Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings
'''
if 'require_reboot' not in settings:
settings['require_reboot'] = False
if 'apply_hostname' not in settings:
settings['apply_hostname'] = False
hostname_res = True
if settings['apply_hostname'] in _CONFIG_TRUE:
if 'hostname' in settings:
hostname_res = __salt__['network.mod_hostname'](settings['hostname'])
else:
log.warning(
'The network state sls is trying to apply hostname '
'changes but no hostname is defined.'
)
hostname_res = False
res = True
if settings['require_reboot'] in _CONFIG_TRUE:
log.warning(
'The network state sls is requiring a reboot of the system to '
'properly apply network configuration.'
)
res = True
else:
stop = __salt__['service.stop']('networking')
time.sleep(2)
res = stop and __salt__['service.start']('networking')
return hostname_res and res
def build_network_settings(**settings):
'''
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
'''
changes = []
# Read current configuration and store default values
current_network_settings = _parse_current_network_settings()
# Build settings
opts = _parse_network_settings(settings, current_network_settings)
# Ubuntu has moved away from /etc/default/networking
# beginning with the 12.04 release so we disable or enable
# the networking related services on boot
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
if opts['networking'] == 'yes':
service_cmd = 'service.enable'
else:
service_cmd = 'service.disable'
if __salt__['service.available']('NetworkManager'):
__salt__[service_cmd]('NetworkManager')
if __salt__['service.available']('networking'):
__salt__[service_cmd]('networking')
else:
try:
template = JINJA.get_template('network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template network.jinja')
return ''
network = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(network)
# Write settings
_write_file_network(network, _DEB_NETWORKING_FILE, True)
# Get hostname and domain from opts
sline = opts['hostname'].split('.', 1)
opts['hostname'] = sline[0]
current_domainname = current_network_settings['domainname']
current_searchdomain = current_network_settings['searchdomain']
new_domain = False
if len(sline) > 1:
new_domainname = sline[1]
if new_domainname != current_domainname:
domainname = new_domainname
opts['domainname'] = new_domainname
new_domain = True
else:
domainname = current_domainname
opts['domainname'] = domainname
else:
domainname = current_domainname
opts['domainname'] = domainname
new_search = False
if 'search' in opts:
new_searchdomain = opts['search']
if new_searchdomain != current_searchdomain:
searchdomain = new_searchdomain
opts['searchdomain'] = new_searchdomain
new_search = True
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
# If the domain changes, then we should write the resolv.conf file.
if new_domain or new_search:
# Look for existing domain line and update if necessary
resolve = _parse_resolve()
domain_prog = re.compile(r'domain\s+')
search_prog = re.compile(r'search\s+')
new_contents = []
for item in _read_file(_DEB_RESOLV_FILE):
if domain_prog.match(item):
item = 'domain {0}'.format(domainname)
elif search_prog.match(item):
item = 'search {0}'.format(searchdomain)
new_contents.append(item)
# A domain line didn't exist so we'll add one in
# with the new domainname
if 'domain' not in resolve:
new_contents.insert(0, 'domain {0}' . format(domainname))
# A search line didn't exist so we'll add one in
# with the new search domain
if 'search' not in resolve:
new_contents.insert('domain' in resolve, 'search {0}'.format(searchdomain))
new_resolv = '\n'.join(new_contents)
# Write /etc/resolv.conf
if not ('test' in settings and settings['test']):
_write_file_network(new_resolv, _DEB_RESOLV_FILE)
# used for returning the results back
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(opts)
changes.extend(_read_temp(network))
return changes
|
saltstack/salt
|
salt/modules/debian_ip.py
|
_read_temp_ifaces
|
python
|
def _read_temp_ifaces(iface, data):
'''
Return what would be written to disk for interfaces
'''
try:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': data})
# Return as an array so the difflib works
return [item + '\n' for item in ifcfg.split('\n')]
|
Return what would be written to disk for interfaces
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_ip.py#L1466-L1478
| null |
# -*- coding: utf-8 -*-
'''
The networking module for Debian-based distros
References:
* http://www.debian.org/doc/manuals/debian-reference/ch05.en.html
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import functools
import logging
import os.path
import os
import re
import time
# Import third party libs
import jinja2
import jinja2.exceptions
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error,no-name-in-module
# Import salt libs
import salt.utils.dns
import salt.utils.files
import salt.utils.odict
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.validate.net
# Set up logging
log = logging.getLogger(__name__)
# Set up template environment
JINJA = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'debian_ip')
)
)
# Define the module's virtual name
__virtualname__ = 'ip'
def __virtual__():
'''
Confine this module to Debian-based distros
'''
if __grains__['os_family'] == 'Debian':
return __virtualname__
return (False, 'The debian_ip module could not be loaded: '
'unsupported OS family')
_ETHTOOL_CONFIG_OPTS = {
'speed': 'link-speed',
'duplex': 'link-duplex',
'autoneg': 'ethernet-autoneg',
'ethernet-port': 'ethernet-port',
'wol': 'ethernet-wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'rx': 'offload-rx',
'tx': 'offload-tx',
'sg': 'offload-sg',
'tso': 'offload-tso',
'ufo': 'offload-ufo',
'gso': 'offload-gso',
'gro': 'offload-gro',
'lro': 'offload-lro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_REV_ETHTOOL_CONFIG_OPTS = {
'link-speed': 'speed',
'link-duplex': 'duplex',
'ethernet-autoneg': 'autoneg',
'ethernet-port': 'ethernet-port',
'ethernet-wol': 'wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'offload-rx': 'rx',
'offload-tx': 'tx',
'offload-sg': 'sg',
'offload-tso': 'tso',
'offload-ufo': 'ufo',
'offload-gso': 'gso',
'offload-lro': 'lro',
'offload-gro': 'gro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_DEB_CONFIG_PPPOE_OPTS = {
'user': 'user',
'password': 'password',
'provider': 'provider',
'pppoe_iface': 'pppoe_iface',
'noipdefault': 'noipdefault',
'usepeerdns': 'usepeerdns',
'defaultroute': 'defaultroute',
'holdoff': 'holdoff',
'maxfail': 'maxfail',
'hide-password': 'hide-password',
'lcp-echo-interval': 'lcp-echo-interval',
'lcp-echo-failure': 'lcp-echo-failure',
'connect': 'connect',
'noauth': 'noauth',
'persist': 'persist',
'mtu': 'mtu',
'noaccomp': 'noaccomp',
'linkname': 'linkname',
}
_DEB_ROUTES_FILE = '/etc/network/routes'
_DEB_NETWORK_FILE = '/etc/network/interfaces'
_DEB_NETWORK_DIR = '/etc/network/interfaces.d/'
_DEB_NETWORK_UP_DIR = '/etc/network/if-up.d/'
_DEB_NETWORK_DOWN_DIR = '/etc/network/if-down.d/'
_DEB_NETWORK_CONF_FILES = '/etc/modprobe.d/'
_DEB_NETWORKING_FILE = '/etc/default/networking'
_DEB_HOSTNAME_FILE = '/etc/hostname'
_DEB_RESOLV_FILE = '/etc/resolv.conf'
_DEB_PPP_DIR = '/etc/ppp/peers/'
_CONFIG_TRUE = ['yes', 'on', 'true', '1', True]
_CONFIG_FALSE = ['no', 'off', 'false', '0', False]
_IFACE_TYPES = [
'eth', 'bond', 'alias', 'clone',
'ipsec', 'dialup', 'bridge', 'slave',
'vlan', 'pppoe', 'source',
]
def _error_msg_iface(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, '|'.join(str(e) for e in expected))
def _error_msg_routes(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, expected)
def _log_default_iface(iface, opt, value):
log.info(
'Using default option -- Interface: %s Option: %s Value: %s',
iface, opt, value
)
def _error_msg_network(option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]'
return msg.format(option, '|'.join(str(e) for e in expected))
def _log_default_network(opt, value):
log.info('Using existing setting -- Setting: %s Value: %s', opt, value)
def _raise_error_iface(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_iface(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_network(option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_network(option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_routes(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_routes(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _read_file(path):
'''
Reads and returns the contents of a text file
'''
try:
with salt.utils.files.flopen(path, 'rb') as contents:
return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]
except (OSError, IOError):
return ''
def _parse_resolve():
'''
Parse /etc/resolv.conf
'''
return salt.utils.dns.parse_resolv(_DEB_RESOLV_FILE)
def _parse_domainname():
'''
Parse /etc/resolv.conf and return domainname
'''
return _parse_resolve().get('domain', '')
def _parse_searchdomain():
'''
Parse /etc/resolv.conf and return searchdomain
'''
return _parse_resolve().get('search', '')
def _parse_hostname():
'''
Parse /etc/hostname and return hostname
'''
contents = _read_file(_DEB_HOSTNAME_FILE)
if contents:
return contents[0].split('\n')[0]
else:
return ''
def _parse_current_network_settings():
'''
Parse /etc/default/networking and return current configuration
'''
opts = salt.utils.odict.OrderedDict()
opts['networking'] = ''
if os.path.isfile(_DEB_NETWORKING_FILE):
with salt.utils.files.fopen(_DEB_NETWORKING_FILE) as contents:
for line in contents:
salt.utils.stringutils.to_unicode(line)
if line.startswith('#'):
continue
elif line.startswith('CONFIGURE_INTERFACES'):
opts['networking'] = line.split('=', 1)[1].strip()
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
opts['hostname'] = hostname
opts['domainname'] = domainname
opts['searchdomain'] = searchdomain
return opts
# def __validator_func(value):
# return (valid: True/False, (transformed) value, error message)
def __ipv4_quad(value):
'''validate an IPv4 address'''
return (salt.utils.validate.net.ipv4_addr(value), value,
'dotted IPv4 address')
def __ipv6(value):
'''validate an IPv6 address'''
return (salt.utils.validate.net.ipv6_addr(value), value,
'IPv6 address')
def __mac(value):
'''validate a mac address'''
return (salt.utils.validate.net.mac(value), value,
'MAC address')
def __anything(value):
return (True, value, None)
def __int(value):
'''validate an integer'''
valid, _value = False, value
try:
_value = int(value)
valid = True
except ValueError:
pass
return (valid, _value, 'integer')
def __float(value):
'''validate a float'''
valid, _value = False, value
try:
_value = float(value)
valid = True
except ValueError:
pass
return (valid, _value, 'float')
def __ipv4_netmask(value):
'''validate an IPv4 dotted quad or integer CIDR netmask'''
valid, errmsg = False, 'dotted quad or integer CIDR (0->32)'
valid, value, _ = __int(value)
if not (valid and 0 <= value <= 32):
valid = salt.utils.validate.net.netmask(value)
return (valid, value, errmsg)
def __ipv6_netmask(value):
'''validate an IPv6 integer netmask'''
valid, errmsg = False, 'IPv6 netmask (0->128)'
valid, value, _ = __int(value)
valid = (valid and 0 <= value <= 128)
return (valid, value, errmsg)
def __within2(value, within=None, errmsg=None, dtype=None):
'''validate that a value is in ``within`` and optionally a ``dtype``'''
valid, _value = False, value
if dtype:
try:
_value = dtype(value) # TODO: this is a bit loose when dtype is a class
valid = _value in within
except ValueError:
pass
else:
valid = _value in within
if errmsg is None:
if dtype:
typename = getattr(dtype, '__name__',
hasattr(dtype, '__class__')
and getattr(dtype.__class__, 'name', dtype))
errmsg = '{0} within \'{1}\''.format(typename, within)
else:
errmsg = 'within \'{0}\''.format(within)
return (valid, _value, errmsg)
def __within(within=None, errmsg=None, dtype=None):
return functools.partial(__within2, within=within,
errmsg=errmsg, dtype=dtype)
def __space_delimited_list(value):
'''validate that a value contains one or more space-delimited values'''
if isinstance(value, six.string_types):
value = value.strip().split()
if hasattr(value, '__iter__') and value != []:
return (True, value, 'space-delimited string')
else:
return (False, value, '{0} is not a valid space-delimited value.\n'.format(value))
SALT_ATTR_TO_DEBIAN_ATTR_MAP = {
'dns': 'dns-nameservers',
'search': 'dns-search',
'hwaddr': 'hwaddress', # TODO: this limits bootp functionality
'ipaddr': 'address',
'ipaddrs': 'addresses',
}
DEBIAN_ATTR_TO_SALT_ATTR_MAP = dict(
(v, k) for (k, v) in six.iteritems(SALT_ATTR_TO_DEBIAN_ATTR_MAP))
# TODO
DEBIAN_ATTR_TO_SALT_ATTR_MAP['address'] = 'address'
DEBIAN_ATTR_TO_SALT_ATTR_MAP['hwaddress'] = 'hwaddress'
IPV4_VALID_PROTO = ['bootp', 'dhcp', 'static', 'manual', 'loopback', 'ppp']
IPV4_ATTR_MAP = {
'proto': __within(IPV4_VALID_PROTO, dtype=six.text_type),
# ipv4 static & manual
'address': __ipv4_quad,
'addresses': __anything,
'netmask': __ipv4_netmask,
'broadcast': __ipv4_quad,
'metric': __int,
'gateway': __ipv4_quad, # supports a colon-delimited list
'pointopoint': __ipv4_quad,
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'link', 'host'], dtype=six.text_type),
# dhcp
'hostname': __anything,
'leasehours': __int,
'leasetime': __int,
'vendor': __anything,
'client': __anything,
# bootp
'bootfile': __anything,
'server': __ipv4_quad,
'hwaddr': __mac,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'dstaddr': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# bond
'slaves': __anything,
# ppp
'provider': __anything,
'unit': __int,
'options': __anything,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
#
'network': __anything, # i don't know what this is
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
IPV6_VALID_PROTO = ['auto', 'loopback', 'static', 'manual',
'dhcp', 'v4tunnel', '6to4']
IPV6_ATTR_MAP = {
'proto': __within(IPV6_VALID_PROTO),
# ipv6 static & manual
'address': __ipv6,
'addresses': __anything,
'netmask': __ipv6_netmask,
'broadcast': __ipv6,
'gateway': __ipv6, # supports a colon-delimited list
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'site', 'link', 'host'], dtype=six.text_type),
# inet6 auto
'privext': __within([0, 1, 2], dtype=int),
'dhcp': __within([0, 1], dtype=int),
# inet6 static & manual & dhcp
'media': __anything,
'accept_ra': __within([0, 1], dtype=int),
'autoconf': __within([0, 1], dtype=int),
'preferred-lifetime': __int,
'dad-attempts': __int, # 0 to disable
'dad-interval': __float,
# bond
'slaves': __anything,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
WIRELESS_ATTR_MAP = {
'wireless-essid': __anything,
'wireless-mode': __anything, # TODO
'wpa-ap-scan': __within([0, 1, 2], dtype=int), # TODO
'wpa-conf': __anything,
'wpa-driver': __anything,
'wpa-group': __anything,
'wpa-key-mgmt': __anything,
'wpa-pairwise': __anything,
'wpa-psk': __anything,
'wpa-proto': __anything, # partial(__within,
'wpa-roam': __anything,
'wpa-ssid': __anything, # TODO
}
ATTRMAPS = {
'inet': [IPV4_ATTR_MAP, WIRELESS_ATTR_MAP],
'inet6': [IPV6_ATTR_MAP, WIRELESS_ATTR_MAP]
}
def _validate_interface_option(attr, value, addrfam='inet'):
'''lookup the validation function for a [addrfam][attr] and
return the results
:param attr: attribute name
:param value: raw setting value
:param addrfam: address family (inet, inet6,
'''
valid, _value, errmsg = False, value, 'Unknown validator'
attrmaps = ATTRMAPS.get(addrfam, [])
for attrmap in attrmaps:
if attr in attrmap:
validate_func = attrmap[attr]
(valid, _value, errmsg) = validate_func(value)
break
return (valid, _value, errmsg)
def _attrmaps_contain_attr(attr):
return (
attr in WIRELESS_ATTR_MAP or
attr in IPV4_ATTR_MAP or
attr in IPV6_ATTR_MAP)
def _parse_interfaces(interface_files=None):
'''
Parse /etc/network/interfaces and return current configured interfaces
'''
if interface_files is None:
interface_files = []
# Add this later.
if os.path.exists(_DEB_NETWORK_DIR):
interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]
if os.path.isfile(_DEB_NETWORK_FILE):
interface_files.insert(0, _DEB_NETWORK_FILE)
adapters = salt.utils.odict.OrderedDict()
method = -1
for interface_file in interface_files:
with salt.utils.files.fopen(interface_file) as interfaces:
# This ensures iface_dict exists, but does not ensure we're not reading a new interface.
iface_dict = {}
for line in interfaces:
line = salt.utils.stringutils.to_unicode(line)
# Identify the clauses by the first word of each line.
# Go to the next line if the current line is a comment
# or all spaces.
if line.lstrip().startswith('#') or line.isspace():
continue
# Parse the iface clause
if line.startswith('iface'):
sline = line.split()
if len(sline) != 4:
msg = 'Interface file malformed: {0}.'
msg = msg.format(sline)
log.error(msg)
raise AttributeError(msg)
iface_name = sline[1]
addrfam = sline[2]
method = sline[3]
# Create item in dict, if not already there
if iface_name not in adapters:
adapters[iface_name] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters[iface_name]:
adapters[iface_name]['data'] = salt.utils.odict.OrderedDict()
if addrfam not in adapters[iface_name]['data']:
adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict()
iface_dict = adapters[iface_name]['data'][addrfam]
iface_dict['addrfam'] = addrfam
iface_dict['proto'] = method
iface_dict['filename'] = interface_file
# Parse the detail clauses.
elif line[0].isspace():
sline = line.split()
# conf file attr: dns-nameservers
# salt states.network attr: dns
attr, valuestr = line.rstrip().split(None, 1)
if _attrmaps_contain_attr(attr):
if '-' in attr:
attrname = attr.replace('-', '_')
else:
attrname = attr
(valid, value, errmsg) = _validate_interface_option(
attr, valuestr, addrfam)
if attrname == 'address' and 'address' in iface_dict:
if 'addresses' not in iface_dict:
iface_dict['addresses'] = []
iface_dict['addresses'].append(value)
else:
iface_dict[attrname] = value
elif attr in _REV_ETHTOOL_CONFIG_OPTS:
if 'ethtool' not in iface_dict:
iface_dict['ethtool'] = salt.utils.odict.OrderedDict()
iface_dict['ethtool'][attr] = valuestr
elif attr.startswith('bond'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bonding' not in iface_dict:
iface_dict['bonding'] = salt.utils.odict.OrderedDict()
iface_dict['bonding'][opt] = valuestr
elif attr.startswith('bridge'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bridging' not in iface_dict:
iface_dict['bridging'] = salt.utils.odict.OrderedDict()
iface_dict['bridging'][opt] = valuestr
elif attr in ['up', 'pre-up', 'post-up',
'down', 'pre-down', 'post-down']:
cmd = valuestr
cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr))
if cmd_key not in iface_dict:
iface_dict[cmd_key] = []
iface_dict[cmd_key].append(cmd)
elif line.startswith('auto'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['enabled'] = True
elif line.startswith('allow-hotplug'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['hotplug'] = True
elif line.startswith('source'):
if 'source' not in adapters:
adapters['source'] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters['source']:
adapters['source']['data'] = salt.utils.odict.OrderedDict()
adapters['source']['data']['sources'] = []
adapters['source']['data']['sources'].append(line.split()[1])
# Return a sorted list of the keys for bond, bridge and ethtool options to
# ensure a consistent order
for iface_name in adapters:
if iface_name == 'source':
continue
if 'data' not in adapters[iface_name]:
msg = 'Interface file malformed for interface: {0}.'.format(iface_name)
log.error(msg)
adapters.pop(iface_name)
continue
for opt in ['ethtool', 'bonding', 'bridging']:
for inet in ['inet', 'inet6']:
if inet in adapters[iface_name]['data']:
if opt in adapters[iface_name]['data'][inet]:
opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys())
adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys
return adapters
def _parse_ethtool_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
if 'autoneg' in opts:
if opts['autoneg'] in _CONFIG_TRUE:
config.update({'autoneg': 'on'})
elif opts['autoneg'] in _CONFIG_FALSE:
config.update({'autoneg': 'off'})
else:
_raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE)
if 'duplex' in opts:
valid = ['full', 'half']
if opts['duplex'] in valid:
config.update({'duplex': opts['duplex']})
else:
_raise_error_iface(iface, 'duplex', valid)
if 'speed' in opts:
valid = ['10', '100', '1000', '10000']
if six.text_type(opts['speed']) in valid:
config.update({'speed': opts['speed']})
else:
_raise_error_iface(iface, opts['speed'], valid)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'on'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'off'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_ethtool_pppoe_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
for opt in _DEB_CONFIG_PPPOE_OPTS:
if opt in opts:
config[opt] = opts[opt]
if 'provider' in opts and not opts['provider']:
_raise_error_iface(iface, 'provider', _CONFIG_TRUE + _CONFIG_FALSE)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('noipdefault', 'usepeerdns', 'defaultroute', 'hide-password', 'noauth', 'persist', 'noaccomp'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'True'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'False'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_settings_bond(opts, iface):
'''
Filters given options and outputs valid settings for requested
operation. If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond_def = {
# 803.ad aggregation selection logic
# 0 for stable (default)
# 1 for bandwidth
# 2 for count
'ad_select': '0',
# Max number of transmit queues (default = 16)
'tx_queues': '16',
# Link monitoring in milliseconds. Most NICs support this
'miimon': '100',
# ARP interval in milliseconds
'arp_interval': '250',
# Delay before considering link down in milliseconds (miimon * 2)
'downdelay': '200',
# lacp_rate 0: Slow - every 30 seconds
# lacp_rate 1: Fast - every 1 second
'lacp_rate': '0',
# Max bonds for this driver
'max_bonds': '1',
# Specifies the time, in milliseconds, to wait before
# enabling a slave after a link recovery has been
# detected. Only used with miimon.
'updelay': '0',
# Used with miimon.
# On: driver sends mii
# Off: ethtool sends mii
'use_carrier': 'on',
# Default. Don't change unless you know what you are doing.
'xmit_hash_policy': 'layer2',
}
if opts['mode'] in ['balance-rr', '0']:
log.info('Device: %s Bonding Mode: load balancing (round-robin)', iface)
return _parse_settings_bond_0(opts, iface, bond_def)
elif opts['mode'] in ['active-backup', '1']:
log.info('Device: %s Bonding Mode: fault-tolerance (active-backup)', iface)
return _parse_settings_bond_1(opts, iface, bond_def)
elif opts['mode'] in ['balance-xor', '2']:
log.info('Device: %s Bonding Mode: load balancing (xor)', iface)
return _parse_settings_bond_2(opts, iface, bond_def)
elif opts['mode'] in ['broadcast', '3']:
log.info('Device: %s Bonding Mode: fault-tolerance (broadcast)', iface)
return _parse_settings_bond_3(opts, iface, bond_def)
elif opts['mode'] in ['802.3ad', '4']:
log.info('Device: %s Bonding Mode: IEEE 802.3ad Dynamic link '
'aggregation', iface)
return _parse_settings_bond_4(opts, iface, bond_def)
elif opts['mode'] in ['balance-tlb', '5']:
log.info('Device: %s Bonding Mode: transmit load balancing', iface)
return _parse_settings_bond_5(opts, iface, bond_def)
elif opts['mode'] in ['balance-alb', '6']:
log.info('Device: %s Bonding Mode: adaptive load balancing', iface)
return _parse_settings_bond_6(opts, iface, bond_def)
else:
valid = [
'0', '1', '2', '3', '4', '5', '6',
'balance-rr', 'active-backup', 'balance-xor',
'broadcast', '802.3ad', 'balance-tlb', 'balance-alb'
]
_raise_error_iface(iface, 'mode', valid)
def _parse_settings_bond_0(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond0.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '0'}
# ARP targets in n.n.n.n form
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
return bond
def _parse_settings_bond_1(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '1'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
if not (__grains__['os'] == "Ubuntu" and __grains__['osrelease_info'][0] >= 16):
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_2(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond2.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '2'}
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_3(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond3.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '3'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_4(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond4.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '4'}
for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']:
if binding in opts:
if binding == 'lacp_rate':
if opts[binding] == 'fast':
opts.update({binding: '1'})
if opts[binding] == 'slow':
opts.update({binding: '0'})
valid = ['fast', '1', 'slow', '0']
else:
valid = ['integer']
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, valid)
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_5(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond5.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '5'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_settings_bond_6(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond6.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '6'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_bridge_opts(opts, iface):
'''
Filters given options and outputs valid settings for BRIDGING_OPTS
If an option has a value that is not expected, this
function will log the Interface, Setting and what was expected.
'''
config = {}
if 'ports' in opts:
if isinstance(opts['ports'], list):
opts['ports'] = ' '.join(opts['ports'])
config.update({'ports': opts['ports']})
for opt in ['ageing', 'fd', 'gcint', 'hello', 'maxage']:
if opt in opts:
try:
float(opts[opt])
config.update({opt: opts[opt]})
except ValueError:
_raise_error_iface(iface, opt, ['float'])
for opt in ['bridgeprio', 'maxwait']:
if opt in opts:
if isinstance(opts[opt], int):
config.update({opt: opts[opt]})
else:
_raise_error_iface(iface, opt, ['integer'])
if 'hw' in opts:
# match 12 hex digits with either : or - as separators between pairs
if re.match('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$',
opts['hw'].lower()):
config.update({'hw': opts['hw']})
else:
_raise_error_iface(iface, 'hw', ['valid MAC address'])
for opt in ['pathcost', 'portprio']:
if opt in opts:
try:
port, cost_or_prio = opts[opt].split()
int(cost_or_prio)
config.update({opt: '{0} {1}'.format(port, cost_or_prio)})
except ValueError:
_raise_error_iface(iface, opt, ['interface integer'])
if 'stp' in opts:
if opts['stp'] in _CONFIG_TRUE:
config.update({'stp': 'on'})
elif opts['stp'] in _CONFIG_FALSE:
config.update({'stp': 'off'})
else:
_raise_error_iface(iface, 'stp', _CONFIG_TRUE + _CONFIG_FALSE)
if 'waitport' in opts:
if isinstance(opts['waitport'], int):
config.update({'waitport': opts['waitport']})
else:
values = opts['waitport'].split()
waitport_time = values.pop(0)
if waitport_time.isdigit() and values:
config.update({
'waitport': '{0} {1}'.format(
waitport_time, ' '.join(values)
)
})
else:
_raise_error_iface(iface, opt, ['integer [interfaces]'])
return config
def _parse_settings_eth(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['inet'] = salt.utils.odict.OrderedDict()
iface_data['inet6'] = salt.utils.odict.OrderedDict()
if enabled:
adapters[iface]['enabled'] = True
if opts.get('hotplug', False):
adapters[iface]['hotplug'] = True
if opts.get('enable_ipv6', None) and opts.get('iface_type', '') == 'vlan':
iface_data['inet6']['vlan_raw_device'] = (
re.sub(r'\.\d*', '', iface))
for addrfam in ['inet', 'inet6']:
if iface_type not in ['bridge']:
tmp_ethtool = _parse_ethtool_opts(opts, iface)
if tmp_ethtool:
ethtool = {}
for item in tmp_ethtool:
ethtool[_ETHTOOL_CONFIG_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['ethtool'] = ethtool
# return a list of sorted keys to ensure consistent order
iface_data[addrfam]['ethtool_keys'] = sorted(ethtool)
if iface_type == 'bridge':
bridging = _parse_bridge_opts(opts, iface)
if bridging:
iface_data[addrfam]['bridging'] = bridging
iface_data[addrfam]['bridging_keys'] = sorted(bridging)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'bond':
bonding = _parse_settings_bond(opts, iface)
if bonding:
iface_data[addrfam]['bonding'] = bonding
iface_data[addrfam]['bonding']['slaves'] = opts['slaves']
iface_data[addrfam]['bonding_keys'] = sorted(bonding)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'slave':
adapters[iface]['master'] = opts['master']
opts['proto'] = 'manual'
iface_data[addrfam]['master'] = adapters[iface]['master']
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'vlan':
iface_data[addrfam]['vlan_raw_device'] = re.sub(r'\.\d*', '', iface)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'pppoe':
tmp_ethtool = _parse_ethtool_pppoe_opts(opts, iface)
if tmp_ethtool:
for item in tmp_ethtool:
adapters[iface]['data'][addrfam][_DEB_CONFIG_PPPOE_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['addrfam'] = addrfam
opts.pop('mode', None)
for opt, val in opts.items():
inet = None
if opt.startswith('ipv4'):
opt = opt[4:]
inet = 'inet'
iface_data['inet']['addrfam'] = 'inet'
elif opt.startswith('ipv6'):
iface_data['inet6']['addrfam'] = 'inet6'
opt = opt[4:]
inet = 'inet6'
elif opt in ['ipaddr', 'address', 'ipaddresses', 'addresses', 'gateway', 'proto']:
iface_data['inet']['addrfam'] = 'inet'
inet = 'inet'
_opt = SALT_ATTR_TO_DEBIAN_ATTR_MAP.get(opt, opt)
_debopt = _opt.replace('-', '_')
for addrfam in ['inet', 'inet6']:
(valid, value, errmsg) = _validate_interface_option(_opt, val, addrfam=addrfam)
if not valid:
continue
if inet is None and _debopt not in iface_data[addrfam]:
iface_data[addrfam][_debopt] = value
elif inet == addrfam:
iface_data[addrfam][_debopt] = value
for opt in ['up_cmds', 'pre_up_cmds', 'post_up_cmds',
'down_cmds', 'pre_down_cmds', 'post_down_cmds']:
if opt in opts:
iface_data['inet'][opt] = opts[opt]
iface_data['inet6'][opt] = opts[opt]
# Remove incomplete/disabled inet blocks
for (addrfam, opt) in [('inet', 'enable_ipv4'), ('inet6', 'enable_ipv6')]:
if opts.get(opt, None) is False:
iface_data.pop(addrfam)
elif iface_data[addrfam].get('addrfam', '') != addrfam:
iface_data.pop(addrfam)
return adapters
def _parse_settings_source(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['sources'] = [opts['source']]
return adapters
def _parse_network_settings(opts, current):
'''
Filters given options and outputs valid settings for
the global network settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
current = dict((k.lower(), v) for (k, v) in six.iteritems(current))
result = {}
valid = _CONFIG_TRUE + _CONFIG_FALSE
if 'enabled' not in opts:
try:
opts['networking'] = current['networking']
_log_default_network('networking', current['networking'])
except ValueError:
_raise_error_network('networking', valid)
else:
opts['networking'] = opts['enabled']
if opts['networking'] in valid:
if opts['networking'] in _CONFIG_TRUE:
result['networking'] = 'yes'
elif opts['networking'] in _CONFIG_FALSE:
result['networking'] = 'no'
else:
_raise_error_network('networking', valid)
if 'hostname' not in opts:
try:
opts['hostname'] = current['hostname']
_log_default_network('hostname', current['hostname'])
except ValueError:
_raise_error_network('hostname', ['server1.example.com'])
if opts['hostname']:
result['hostname'] = opts['hostname']
else:
_raise_error_network('hostname', ['server1.example.com'])
if 'search' in opts:
result['search'] = opts['search']
return result
def _parse_routes(iface, opts):
'''
Filters given options and outputs valid settings for
the route settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
result = {}
if 'routes' not in opts:
_raise_error_routes(iface, 'routes', 'List of routes')
for opt in opts:
result[opt] = opts[opt]
return result
def _write_file(iface, data, folder, pattern):
'''
Writes a file to disk
'''
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
return filename
def _write_file_routes(iface, data, folder, pattern):
'''
Writes a file to disk
'''
# ifup / ifdown is executing given folder via run-parts.
# according to run-parts man-page, only filenames with this pattern are
# executed: (^[a-zA-Z0-9_-]+$)
# In order to make the routes file work for vlan interfaces
# (default would have been in example /etc/network/if-up.d/route-bond0.12)
# these dots in the iface name need to be replaced by underscores, so it
# can be executed by run-parts
iface = iface.replace('.', '_')
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
__salt__['file.set_mode'](filename, '0755')
return filename
def _write_file_network(data, filename, create=False):
'''
Writes a file to disk
If file does not exist, only create if create
argument is True
'''
if not os.path.exists(filename) and not create:
msg = '{0} cannot be written. {0} does not exist\
and create is set to False'
msg = msg.format(filename)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
def _read_temp(data):
'''
Return what would be written to disk
'''
tout = StringIO()
tout.write(data)
tout.seek(0)
output = tout.readlines()
tout.close()
return output
def _write_file_ifaces(iface, data, **settings):
'''
Writes a file to disk
'''
try:
eth_template = JINJA.get_template('debian_eth.jinja')
source_template = JINJA.get_template('debian_source.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
# Read /etc/network/interfaces into a dict
adapters = _parse_interfaces()
# Apply supplied settings over on-disk settings
adapters[iface] = data
ifcfg = ''
for adapter in adapters:
if 'type' in adapters[adapter] and adapters[adapter]['type'] == 'source':
tmp = source_template.render({'name': adapter, 'data': adapters[adapter]})
else:
tmp = eth_template.render({'name': adapter, 'data': adapters[adapter]})
ifcfg = ifcfg + tmp
if adapter == iface:
saved_ifcfg = tmp
_SEPARATE_FILE = False
if 'filename' in settings:
if not settings['filename'].startswith('/'):
filename = '{0}/{1}'.format(_DEB_NETWORK_DIR, settings['filename'])
else:
filename = settings['filename']
_SEPARATE_FILE = True
else:
if 'filename' in adapters[adapter]['data']:
filename = adapters[adapter]['data']
else:
filename = _DEB_NETWORK_FILE
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
if _SEPARATE_FILE:
fout.write(salt.utils.stringutils.to_str(saved_ifcfg))
else:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return saved_ifcfg.split('\n')
def _write_file_ppp_ifaces(iface, data):
'''
Writes a file to disk
'''
try:
template = JINJA.get_template('debian_ppp_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_ppp_eth.jinja')
return ''
adapters = _parse_interfaces()
adapters[iface] = data
ifcfg = ''
tmp = template.render({'data': adapters[iface]})
ifcfg = tmp + ifcfg
filename = _DEB_PPP_DIR + '/' + adapters[iface]['data']['inet']['provider']
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.fopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return filename
def build_bond(iface, **settings):
'''
Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb
'''
deb_major = __grains__['osrelease'][:1]
opts = _parse_settings_bond(settings, iface)
try:
template = JINJA.get_template('conf.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template conf.jinja')
return ''
data = template.render({'name': iface, 'bonding': opts})
if 'test' in settings and settings['test']:
return _read_temp(data)
_write_file(iface, data, _DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
if deb_major == '5':
for line_type in ('alias', 'options'):
cmd = ['sed', '-i', '-e', r'/^{0}\s{1}.*/d'.format(line_type, iface),
'/etc/modprobe.conf']
__salt__['cmd.run'](cmd, python_shell=False)
__salt__['file.append']('/etc/modprobe.conf', path)
# Load kernel module
__salt__['kmod.load']('bonding')
# install ifenslave-2.6
__salt__['pkg.install']('ifenslave-2.6')
return _read_file(path)
def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'vlan':
settings['vlan'] = 'yes'
__salt__['pkg.install']('vlan')
elif iface_type == 'pppoe':
settings['pppoe'] = 'yes'
if not __salt__['pkg.version']('ppp'):
inst = __salt__['pkg.install']('ppp')
elif iface_type == 'bond':
if 'slaves' not in settings:
msg = 'slaves is a required setting for bond interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'bridge':
if 'ports' not in settings:
msg = (
'ports is a required setting for bridge interfaces on Debian '
'or Ubuntu based systems'
)
log.error(msg)
raise AttributeError(msg)
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'pppoe']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
if iface_type in ['source']:
opts = _parse_settings_source(settings, iface_type, enabled, iface)
if 'test' in settings and settings['test']:
return _read_temp_ifaces(iface, opts[iface])
ifcfg = _write_file_ifaces(iface, opts[iface], **settings)
if iface_type == 'pppoe':
_write_file_ppp_ifaces(iface, opts[iface])
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg]
def build_routes(iface, **settings):
'''
Add route scripts for a network interface using up commands.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
'''
opts = _parse_routes(iface, settings)
try:
template = JINJA.get_template('route_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template route_eth.jinja')
return ''
add_routecfg = template.render(route_type='add',
routes=opts['routes'],
iface=iface)
del_routecfg = template.render(route_type='del',
routes=opts['routes'],
iface=iface)
if 'test' in settings and settings['test']:
return _read_temp(add_routecfg + del_routecfg)
filename = _write_file_routes(iface,
add_routecfg,
_DEB_NETWORK_UP_DIR,
'route-{0}')
results = _read_file(filename)
filename = _write_file_routes(iface,
del_routecfg,
_DEB_NETWORK_DOWN_DIR,
'route-{0}')
results += _read_file(filename)
return results
def down(iface, iface_type):
'''
Shutdown a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.down eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought down.
if iface_type not in ['slave', 'source']:
return __salt__['cmd.run'](['ifdown', iface])
return None
def get_bond(iface):
'''
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
'''
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
return _read_file(path)
def get_interface(iface):
'''
Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
adapters = _parse_interfaces()
if iface in adapters:
try:
if iface == 'source':
template = JINJA.get_template('debian_source.jinja')
else:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': adapters[iface]})
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg.split('\n')]
else:
return []
def up(iface, iface_type): # pylint: disable=C0103
'''
Start up a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.up eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought up.
if iface_type not in ('slave', 'source'):
return __salt__['cmd.run'](['ifup', iface])
return None
def get_network_settings():
'''
Return the contents of the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_network_settings
'''
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
settings = {}
if __salt__['service.available']('networking'):
if __salt__['service.status']('networking'):
settings['networking'] = "yes"
else:
settings['networking'] = "no"
else:
settings['networking'] = "no"
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
settings['hostname'] = hostname
settings['domainname'] = domainname
settings['searchdomain'] = searchdomain
else:
settings = _parse_current_network_settings()
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(settings)
return _read_temp(network)
def get_routes(iface):
'''
Return the routes for the interface
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0
'''
filename = os.path.join(_DEB_NETWORK_UP_DIR, 'route-{0}'.format(iface))
results = _read_file(filename)
filename = os.path.join(_DEB_NETWORK_DOWN_DIR, 'route-{0}'.format(iface))
results += _read_file(filename)
return results
def apply_network_settings(**settings):
'''
Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings
'''
if 'require_reboot' not in settings:
settings['require_reboot'] = False
if 'apply_hostname' not in settings:
settings['apply_hostname'] = False
hostname_res = True
if settings['apply_hostname'] in _CONFIG_TRUE:
if 'hostname' in settings:
hostname_res = __salt__['network.mod_hostname'](settings['hostname'])
else:
log.warning(
'The network state sls is trying to apply hostname '
'changes but no hostname is defined.'
)
hostname_res = False
res = True
if settings['require_reboot'] in _CONFIG_TRUE:
log.warning(
'The network state sls is requiring a reboot of the system to '
'properly apply network configuration.'
)
res = True
else:
stop = __salt__['service.stop']('networking')
time.sleep(2)
res = stop and __salt__['service.start']('networking')
return hostname_res and res
def build_network_settings(**settings):
'''
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
'''
changes = []
# Read current configuration and store default values
current_network_settings = _parse_current_network_settings()
# Build settings
opts = _parse_network_settings(settings, current_network_settings)
# Ubuntu has moved away from /etc/default/networking
# beginning with the 12.04 release so we disable or enable
# the networking related services on boot
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
if opts['networking'] == 'yes':
service_cmd = 'service.enable'
else:
service_cmd = 'service.disable'
if __salt__['service.available']('NetworkManager'):
__salt__[service_cmd]('NetworkManager')
if __salt__['service.available']('networking'):
__salt__[service_cmd]('networking')
else:
try:
template = JINJA.get_template('network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template network.jinja')
return ''
network = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(network)
# Write settings
_write_file_network(network, _DEB_NETWORKING_FILE, True)
# Get hostname and domain from opts
sline = opts['hostname'].split('.', 1)
opts['hostname'] = sline[0]
current_domainname = current_network_settings['domainname']
current_searchdomain = current_network_settings['searchdomain']
new_domain = False
if len(sline) > 1:
new_domainname = sline[1]
if new_domainname != current_domainname:
domainname = new_domainname
opts['domainname'] = new_domainname
new_domain = True
else:
domainname = current_domainname
opts['domainname'] = domainname
else:
domainname = current_domainname
opts['domainname'] = domainname
new_search = False
if 'search' in opts:
new_searchdomain = opts['search']
if new_searchdomain != current_searchdomain:
searchdomain = new_searchdomain
opts['searchdomain'] = new_searchdomain
new_search = True
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
# If the domain changes, then we should write the resolv.conf file.
if new_domain or new_search:
# Look for existing domain line and update if necessary
resolve = _parse_resolve()
domain_prog = re.compile(r'domain\s+')
search_prog = re.compile(r'search\s+')
new_contents = []
for item in _read_file(_DEB_RESOLV_FILE):
if domain_prog.match(item):
item = 'domain {0}'.format(domainname)
elif search_prog.match(item):
item = 'search {0}'.format(searchdomain)
new_contents.append(item)
# A domain line didn't exist so we'll add one in
# with the new domainname
if 'domain' not in resolve:
new_contents.insert(0, 'domain {0}' . format(domainname))
# A search line didn't exist so we'll add one in
# with the new search domain
if 'search' not in resolve:
new_contents.insert('domain' in resolve, 'search {0}'.format(searchdomain))
new_resolv = '\n'.join(new_contents)
# Write /etc/resolv.conf
if not ('test' in settings and settings['test']):
_write_file_network(new_resolv, _DEB_RESOLV_FILE)
# used for returning the results back
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(opts)
changes.extend(_read_temp(network))
return changes
|
saltstack/salt
|
salt/modules/debian_ip.py
|
_write_file_ifaces
|
python
|
def _write_file_ifaces(iface, data, **settings):
'''
Writes a file to disk
'''
try:
eth_template = JINJA.get_template('debian_eth.jinja')
source_template = JINJA.get_template('debian_source.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
# Read /etc/network/interfaces into a dict
adapters = _parse_interfaces()
# Apply supplied settings over on-disk settings
adapters[iface] = data
ifcfg = ''
for adapter in adapters:
if 'type' in adapters[adapter] and adapters[adapter]['type'] == 'source':
tmp = source_template.render({'name': adapter, 'data': adapters[adapter]})
else:
tmp = eth_template.render({'name': adapter, 'data': adapters[adapter]})
ifcfg = ifcfg + tmp
if adapter == iface:
saved_ifcfg = tmp
_SEPARATE_FILE = False
if 'filename' in settings:
if not settings['filename'].startswith('/'):
filename = '{0}/{1}'.format(_DEB_NETWORK_DIR, settings['filename'])
else:
filename = settings['filename']
_SEPARATE_FILE = True
else:
if 'filename' in adapters[adapter]['data']:
filename = adapters[adapter]['data']
else:
filename = _DEB_NETWORK_FILE
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
if _SEPARATE_FILE:
fout.write(salt.utils.stringutils.to_str(saved_ifcfg))
else:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return saved_ifcfg.split('\n')
|
Writes a file to disk
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_ip.py#L1481-L1532
|
[
"def to_str(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str, bytes, bytearray, or unicode (py2), return str\n '''\n def _normalize(s):\n try:\n return unicodedata.normalize('NFC', s) if normalize else s\n except TypeError:\n return s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n # This shouldn't be six.string_types because if we're on PY2 and we already\n # have a string, we should just return it.\n if isinstance(s, str):\n return _normalize(s)\n\n exc = None\n if six.PY3:\n if isinstance(s, (bytes, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytes, or bytearray not {}'.format(type(s)))\n else:\n if isinstance(s, bytearray):\n return str(s) # future lint: disable=blacklisted-function\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n for enc in encoding:\n try:\n return _normalize(s).encode(enc, errors)\n except UnicodeEncodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytearray, or unicode')\n",
"def _parse_interfaces(interface_files=None):\n '''\n Parse /etc/network/interfaces and return current configured interfaces\n '''\n if interface_files is None:\n interface_files = []\n # Add this later.\n if os.path.exists(_DEB_NETWORK_DIR):\n interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]\n\n if os.path.isfile(_DEB_NETWORK_FILE):\n interface_files.insert(0, _DEB_NETWORK_FILE)\n\n adapters = salt.utils.odict.OrderedDict()\n method = -1\n\n for interface_file in interface_files:\n with salt.utils.files.fopen(interface_file) as interfaces:\n # This ensures iface_dict exists, but does not ensure we're not reading a new interface.\n iface_dict = {}\n for line in interfaces:\n line = salt.utils.stringutils.to_unicode(line)\n # Identify the clauses by the first word of each line.\n # Go to the next line if the current line is a comment\n # or all spaces.\n if line.lstrip().startswith('#') or line.isspace():\n continue\n # Parse the iface clause\n if line.startswith('iface'):\n sline = line.split()\n\n if len(sline) != 4:\n msg = 'Interface file malformed: {0}.'\n msg = msg.format(sline)\n log.error(msg)\n raise AttributeError(msg)\n\n iface_name = sline[1]\n addrfam = sline[2]\n method = sline[3]\n\n # Create item in dict, if not already there\n if iface_name not in adapters:\n adapters[iface_name] = salt.utils.odict.OrderedDict()\n\n # Create item in dict, if not already there\n if 'data' not in adapters[iface_name]:\n adapters[iface_name]['data'] = salt.utils.odict.OrderedDict()\n\n if addrfam not in adapters[iface_name]['data']:\n adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict()\n\n iface_dict = adapters[iface_name]['data'][addrfam]\n\n iface_dict['addrfam'] = addrfam\n iface_dict['proto'] = method\n iface_dict['filename'] = interface_file\n\n # Parse the detail clauses.\n elif line[0].isspace():\n sline = line.split()\n\n # conf file attr: dns-nameservers\n # salt states.network attr: dns\n\n attr, valuestr = line.rstrip().split(None, 1)\n if _attrmaps_contain_attr(attr):\n if '-' in attr:\n attrname = attr.replace('-', '_')\n else:\n attrname = attr\n (valid, value, errmsg) = _validate_interface_option(\n attr, valuestr, addrfam)\n if attrname == 'address' and 'address' in iface_dict:\n if 'addresses' not in iface_dict:\n iface_dict['addresses'] = []\n iface_dict['addresses'].append(value)\n else:\n iface_dict[attrname] = value\n\n elif attr in _REV_ETHTOOL_CONFIG_OPTS:\n if 'ethtool' not in iface_dict:\n iface_dict['ethtool'] = salt.utils.odict.OrderedDict()\n iface_dict['ethtool'][attr] = valuestr\n\n elif attr.startswith('bond'):\n opt = re.split(r'[_-]', attr, maxsplit=1)[1]\n if 'bonding' not in iface_dict:\n iface_dict['bonding'] = salt.utils.odict.OrderedDict()\n iface_dict['bonding'][opt] = valuestr\n\n elif attr.startswith('bridge'):\n opt = re.split(r'[_-]', attr, maxsplit=1)[1]\n if 'bridging' not in iface_dict:\n iface_dict['bridging'] = salt.utils.odict.OrderedDict()\n iface_dict['bridging'][opt] = valuestr\n\n elif attr in ['up', 'pre-up', 'post-up',\n 'down', 'pre-down', 'post-down']:\n cmd = valuestr\n cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr))\n if cmd_key not in iface_dict:\n iface_dict[cmd_key] = []\n iface_dict[cmd_key].append(cmd)\n\n elif line.startswith('auto'):\n for word in line.split()[1:]:\n if word not in adapters:\n adapters[word] = salt.utils.odict.OrderedDict()\n adapters[word]['enabled'] = True\n\n elif line.startswith('allow-hotplug'):\n for word in line.split()[1:]:\n if word not in adapters:\n adapters[word] = salt.utils.odict.OrderedDict()\n adapters[word]['hotplug'] = True\n\n elif line.startswith('source'):\n if 'source' not in adapters:\n adapters['source'] = salt.utils.odict.OrderedDict()\n\n # Create item in dict, if not already there\n if 'data' not in adapters['source']:\n adapters['source']['data'] = salt.utils.odict.OrderedDict()\n adapters['source']['data']['sources'] = []\n adapters['source']['data']['sources'].append(line.split()[1])\n\n # Return a sorted list of the keys for bond, bridge and ethtool options to\n # ensure a consistent order\n for iface_name in adapters:\n if iface_name == 'source':\n continue\n if 'data' not in adapters[iface_name]:\n msg = 'Interface file malformed for interface: {0}.'.format(iface_name)\n log.error(msg)\n adapters.pop(iface_name)\n continue\n for opt in ['ethtool', 'bonding', 'bridging']:\n for inet in ['inet', 'inet6']:\n if inet in adapters[iface_name]['data']:\n if opt in adapters[iface_name]['data'][inet]:\n opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys())\n adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys\n\n return adapters\n"
] |
# -*- coding: utf-8 -*-
'''
The networking module for Debian-based distros
References:
* http://www.debian.org/doc/manuals/debian-reference/ch05.en.html
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import functools
import logging
import os.path
import os
import re
import time
# Import third party libs
import jinja2
import jinja2.exceptions
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error,no-name-in-module
# Import salt libs
import salt.utils.dns
import salt.utils.files
import salt.utils.odict
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.validate.net
# Set up logging
log = logging.getLogger(__name__)
# Set up template environment
JINJA = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'debian_ip')
)
)
# Define the module's virtual name
__virtualname__ = 'ip'
def __virtual__():
'''
Confine this module to Debian-based distros
'''
if __grains__['os_family'] == 'Debian':
return __virtualname__
return (False, 'The debian_ip module could not be loaded: '
'unsupported OS family')
_ETHTOOL_CONFIG_OPTS = {
'speed': 'link-speed',
'duplex': 'link-duplex',
'autoneg': 'ethernet-autoneg',
'ethernet-port': 'ethernet-port',
'wol': 'ethernet-wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'rx': 'offload-rx',
'tx': 'offload-tx',
'sg': 'offload-sg',
'tso': 'offload-tso',
'ufo': 'offload-ufo',
'gso': 'offload-gso',
'gro': 'offload-gro',
'lro': 'offload-lro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_REV_ETHTOOL_CONFIG_OPTS = {
'link-speed': 'speed',
'link-duplex': 'duplex',
'ethernet-autoneg': 'autoneg',
'ethernet-port': 'ethernet-port',
'ethernet-wol': 'wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'offload-rx': 'rx',
'offload-tx': 'tx',
'offload-sg': 'sg',
'offload-tso': 'tso',
'offload-ufo': 'ufo',
'offload-gso': 'gso',
'offload-lro': 'lro',
'offload-gro': 'gro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_DEB_CONFIG_PPPOE_OPTS = {
'user': 'user',
'password': 'password',
'provider': 'provider',
'pppoe_iface': 'pppoe_iface',
'noipdefault': 'noipdefault',
'usepeerdns': 'usepeerdns',
'defaultroute': 'defaultroute',
'holdoff': 'holdoff',
'maxfail': 'maxfail',
'hide-password': 'hide-password',
'lcp-echo-interval': 'lcp-echo-interval',
'lcp-echo-failure': 'lcp-echo-failure',
'connect': 'connect',
'noauth': 'noauth',
'persist': 'persist',
'mtu': 'mtu',
'noaccomp': 'noaccomp',
'linkname': 'linkname',
}
_DEB_ROUTES_FILE = '/etc/network/routes'
_DEB_NETWORK_FILE = '/etc/network/interfaces'
_DEB_NETWORK_DIR = '/etc/network/interfaces.d/'
_DEB_NETWORK_UP_DIR = '/etc/network/if-up.d/'
_DEB_NETWORK_DOWN_DIR = '/etc/network/if-down.d/'
_DEB_NETWORK_CONF_FILES = '/etc/modprobe.d/'
_DEB_NETWORKING_FILE = '/etc/default/networking'
_DEB_HOSTNAME_FILE = '/etc/hostname'
_DEB_RESOLV_FILE = '/etc/resolv.conf'
_DEB_PPP_DIR = '/etc/ppp/peers/'
_CONFIG_TRUE = ['yes', 'on', 'true', '1', True]
_CONFIG_FALSE = ['no', 'off', 'false', '0', False]
_IFACE_TYPES = [
'eth', 'bond', 'alias', 'clone',
'ipsec', 'dialup', 'bridge', 'slave',
'vlan', 'pppoe', 'source',
]
def _error_msg_iface(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, '|'.join(str(e) for e in expected))
def _error_msg_routes(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, expected)
def _log_default_iface(iface, opt, value):
log.info(
'Using default option -- Interface: %s Option: %s Value: %s',
iface, opt, value
)
def _error_msg_network(option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]'
return msg.format(option, '|'.join(str(e) for e in expected))
def _log_default_network(opt, value):
log.info('Using existing setting -- Setting: %s Value: %s', opt, value)
def _raise_error_iface(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_iface(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_network(option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_network(option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_routes(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_routes(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _read_file(path):
'''
Reads and returns the contents of a text file
'''
try:
with salt.utils.files.flopen(path, 'rb') as contents:
return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]
except (OSError, IOError):
return ''
def _parse_resolve():
'''
Parse /etc/resolv.conf
'''
return salt.utils.dns.parse_resolv(_DEB_RESOLV_FILE)
def _parse_domainname():
'''
Parse /etc/resolv.conf and return domainname
'''
return _parse_resolve().get('domain', '')
def _parse_searchdomain():
'''
Parse /etc/resolv.conf and return searchdomain
'''
return _parse_resolve().get('search', '')
def _parse_hostname():
'''
Parse /etc/hostname and return hostname
'''
contents = _read_file(_DEB_HOSTNAME_FILE)
if contents:
return contents[0].split('\n')[0]
else:
return ''
def _parse_current_network_settings():
'''
Parse /etc/default/networking and return current configuration
'''
opts = salt.utils.odict.OrderedDict()
opts['networking'] = ''
if os.path.isfile(_DEB_NETWORKING_FILE):
with salt.utils.files.fopen(_DEB_NETWORKING_FILE) as contents:
for line in contents:
salt.utils.stringutils.to_unicode(line)
if line.startswith('#'):
continue
elif line.startswith('CONFIGURE_INTERFACES'):
opts['networking'] = line.split('=', 1)[1].strip()
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
opts['hostname'] = hostname
opts['domainname'] = domainname
opts['searchdomain'] = searchdomain
return opts
# def __validator_func(value):
# return (valid: True/False, (transformed) value, error message)
def __ipv4_quad(value):
'''validate an IPv4 address'''
return (salt.utils.validate.net.ipv4_addr(value), value,
'dotted IPv4 address')
def __ipv6(value):
'''validate an IPv6 address'''
return (salt.utils.validate.net.ipv6_addr(value), value,
'IPv6 address')
def __mac(value):
'''validate a mac address'''
return (salt.utils.validate.net.mac(value), value,
'MAC address')
def __anything(value):
return (True, value, None)
def __int(value):
'''validate an integer'''
valid, _value = False, value
try:
_value = int(value)
valid = True
except ValueError:
pass
return (valid, _value, 'integer')
def __float(value):
'''validate a float'''
valid, _value = False, value
try:
_value = float(value)
valid = True
except ValueError:
pass
return (valid, _value, 'float')
def __ipv4_netmask(value):
'''validate an IPv4 dotted quad or integer CIDR netmask'''
valid, errmsg = False, 'dotted quad or integer CIDR (0->32)'
valid, value, _ = __int(value)
if not (valid and 0 <= value <= 32):
valid = salt.utils.validate.net.netmask(value)
return (valid, value, errmsg)
def __ipv6_netmask(value):
'''validate an IPv6 integer netmask'''
valid, errmsg = False, 'IPv6 netmask (0->128)'
valid, value, _ = __int(value)
valid = (valid and 0 <= value <= 128)
return (valid, value, errmsg)
def __within2(value, within=None, errmsg=None, dtype=None):
'''validate that a value is in ``within`` and optionally a ``dtype``'''
valid, _value = False, value
if dtype:
try:
_value = dtype(value) # TODO: this is a bit loose when dtype is a class
valid = _value in within
except ValueError:
pass
else:
valid = _value in within
if errmsg is None:
if dtype:
typename = getattr(dtype, '__name__',
hasattr(dtype, '__class__')
and getattr(dtype.__class__, 'name', dtype))
errmsg = '{0} within \'{1}\''.format(typename, within)
else:
errmsg = 'within \'{0}\''.format(within)
return (valid, _value, errmsg)
def __within(within=None, errmsg=None, dtype=None):
return functools.partial(__within2, within=within,
errmsg=errmsg, dtype=dtype)
def __space_delimited_list(value):
'''validate that a value contains one or more space-delimited values'''
if isinstance(value, six.string_types):
value = value.strip().split()
if hasattr(value, '__iter__') and value != []:
return (True, value, 'space-delimited string')
else:
return (False, value, '{0} is not a valid space-delimited value.\n'.format(value))
SALT_ATTR_TO_DEBIAN_ATTR_MAP = {
'dns': 'dns-nameservers',
'search': 'dns-search',
'hwaddr': 'hwaddress', # TODO: this limits bootp functionality
'ipaddr': 'address',
'ipaddrs': 'addresses',
}
DEBIAN_ATTR_TO_SALT_ATTR_MAP = dict(
(v, k) for (k, v) in six.iteritems(SALT_ATTR_TO_DEBIAN_ATTR_MAP))
# TODO
DEBIAN_ATTR_TO_SALT_ATTR_MAP['address'] = 'address'
DEBIAN_ATTR_TO_SALT_ATTR_MAP['hwaddress'] = 'hwaddress'
IPV4_VALID_PROTO = ['bootp', 'dhcp', 'static', 'manual', 'loopback', 'ppp']
IPV4_ATTR_MAP = {
'proto': __within(IPV4_VALID_PROTO, dtype=six.text_type),
# ipv4 static & manual
'address': __ipv4_quad,
'addresses': __anything,
'netmask': __ipv4_netmask,
'broadcast': __ipv4_quad,
'metric': __int,
'gateway': __ipv4_quad, # supports a colon-delimited list
'pointopoint': __ipv4_quad,
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'link', 'host'], dtype=six.text_type),
# dhcp
'hostname': __anything,
'leasehours': __int,
'leasetime': __int,
'vendor': __anything,
'client': __anything,
# bootp
'bootfile': __anything,
'server': __ipv4_quad,
'hwaddr': __mac,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'dstaddr': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# bond
'slaves': __anything,
# ppp
'provider': __anything,
'unit': __int,
'options': __anything,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
#
'network': __anything, # i don't know what this is
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
IPV6_VALID_PROTO = ['auto', 'loopback', 'static', 'manual',
'dhcp', 'v4tunnel', '6to4']
IPV6_ATTR_MAP = {
'proto': __within(IPV6_VALID_PROTO),
# ipv6 static & manual
'address': __ipv6,
'addresses': __anything,
'netmask': __ipv6_netmask,
'broadcast': __ipv6,
'gateway': __ipv6, # supports a colon-delimited list
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'site', 'link', 'host'], dtype=six.text_type),
# inet6 auto
'privext': __within([0, 1, 2], dtype=int),
'dhcp': __within([0, 1], dtype=int),
# inet6 static & manual & dhcp
'media': __anything,
'accept_ra': __within([0, 1], dtype=int),
'autoconf': __within([0, 1], dtype=int),
'preferred-lifetime': __int,
'dad-attempts': __int, # 0 to disable
'dad-interval': __float,
# bond
'slaves': __anything,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
WIRELESS_ATTR_MAP = {
'wireless-essid': __anything,
'wireless-mode': __anything, # TODO
'wpa-ap-scan': __within([0, 1, 2], dtype=int), # TODO
'wpa-conf': __anything,
'wpa-driver': __anything,
'wpa-group': __anything,
'wpa-key-mgmt': __anything,
'wpa-pairwise': __anything,
'wpa-psk': __anything,
'wpa-proto': __anything, # partial(__within,
'wpa-roam': __anything,
'wpa-ssid': __anything, # TODO
}
ATTRMAPS = {
'inet': [IPV4_ATTR_MAP, WIRELESS_ATTR_MAP],
'inet6': [IPV6_ATTR_MAP, WIRELESS_ATTR_MAP]
}
def _validate_interface_option(attr, value, addrfam='inet'):
'''lookup the validation function for a [addrfam][attr] and
return the results
:param attr: attribute name
:param value: raw setting value
:param addrfam: address family (inet, inet6,
'''
valid, _value, errmsg = False, value, 'Unknown validator'
attrmaps = ATTRMAPS.get(addrfam, [])
for attrmap in attrmaps:
if attr in attrmap:
validate_func = attrmap[attr]
(valid, _value, errmsg) = validate_func(value)
break
return (valid, _value, errmsg)
def _attrmaps_contain_attr(attr):
return (
attr in WIRELESS_ATTR_MAP or
attr in IPV4_ATTR_MAP or
attr in IPV6_ATTR_MAP)
def _parse_interfaces(interface_files=None):
'''
Parse /etc/network/interfaces and return current configured interfaces
'''
if interface_files is None:
interface_files = []
# Add this later.
if os.path.exists(_DEB_NETWORK_DIR):
interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]
if os.path.isfile(_DEB_NETWORK_FILE):
interface_files.insert(0, _DEB_NETWORK_FILE)
adapters = salt.utils.odict.OrderedDict()
method = -1
for interface_file in interface_files:
with salt.utils.files.fopen(interface_file) as interfaces:
# This ensures iface_dict exists, but does not ensure we're not reading a new interface.
iface_dict = {}
for line in interfaces:
line = salt.utils.stringutils.to_unicode(line)
# Identify the clauses by the first word of each line.
# Go to the next line if the current line is a comment
# or all spaces.
if line.lstrip().startswith('#') or line.isspace():
continue
# Parse the iface clause
if line.startswith('iface'):
sline = line.split()
if len(sline) != 4:
msg = 'Interface file malformed: {0}.'
msg = msg.format(sline)
log.error(msg)
raise AttributeError(msg)
iface_name = sline[1]
addrfam = sline[2]
method = sline[3]
# Create item in dict, if not already there
if iface_name not in adapters:
adapters[iface_name] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters[iface_name]:
adapters[iface_name]['data'] = salt.utils.odict.OrderedDict()
if addrfam not in adapters[iface_name]['data']:
adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict()
iface_dict = adapters[iface_name]['data'][addrfam]
iface_dict['addrfam'] = addrfam
iface_dict['proto'] = method
iface_dict['filename'] = interface_file
# Parse the detail clauses.
elif line[0].isspace():
sline = line.split()
# conf file attr: dns-nameservers
# salt states.network attr: dns
attr, valuestr = line.rstrip().split(None, 1)
if _attrmaps_contain_attr(attr):
if '-' in attr:
attrname = attr.replace('-', '_')
else:
attrname = attr
(valid, value, errmsg) = _validate_interface_option(
attr, valuestr, addrfam)
if attrname == 'address' and 'address' in iface_dict:
if 'addresses' not in iface_dict:
iface_dict['addresses'] = []
iface_dict['addresses'].append(value)
else:
iface_dict[attrname] = value
elif attr in _REV_ETHTOOL_CONFIG_OPTS:
if 'ethtool' not in iface_dict:
iface_dict['ethtool'] = salt.utils.odict.OrderedDict()
iface_dict['ethtool'][attr] = valuestr
elif attr.startswith('bond'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bonding' not in iface_dict:
iface_dict['bonding'] = salt.utils.odict.OrderedDict()
iface_dict['bonding'][opt] = valuestr
elif attr.startswith('bridge'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bridging' not in iface_dict:
iface_dict['bridging'] = salt.utils.odict.OrderedDict()
iface_dict['bridging'][opt] = valuestr
elif attr in ['up', 'pre-up', 'post-up',
'down', 'pre-down', 'post-down']:
cmd = valuestr
cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr))
if cmd_key not in iface_dict:
iface_dict[cmd_key] = []
iface_dict[cmd_key].append(cmd)
elif line.startswith('auto'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['enabled'] = True
elif line.startswith('allow-hotplug'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['hotplug'] = True
elif line.startswith('source'):
if 'source' not in adapters:
adapters['source'] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters['source']:
adapters['source']['data'] = salt.utils.odict.OrderedDict()
adapters['source']['data']['sources'] = []
adapters['source']['data']['sources'].append(line.split()[1])
# Return a sorted list of the keys for bond, bridge and ethtool options to
# ensure a consistent order
for iface_name in adapters:
if iface_name == 'source':
continue
if 'data' not in adapters[iface_name]:
msg = 'Interface file malformed for interface: {0}.'.format(iface_name)
log.error(msg)
adapters.pop(iface_name)
continue
for opt in ['ethtool', 'bonding', 'bridging']:
for inet in ['inet', 'inet6']:
if inet in adapters[iface_name]['data']:
if opt in adapters[iface_name]['data'][inet]:
opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys())
adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys
return adapters
def _parse_ethtool_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
if 'autoneg' in opts:
if opts['autoneg'] in _CONFIG_TRUE:
config.update({'autoneg': 'on'})
elif opts['autoneg'] in _CONFIG_FALSE:
config.update({'autoneg': 'off'})
else:
_raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE)
if 'duplex' in opts:
valid = ['full', 'half']
if opts['duplex'] in valid:
config.update({'duplex': opts['duplex']})
else:
_raise_error_iface(iface, 'duplex', valid)
if 'speed' in opts:
valid = ['10', '100', '1000', '10000']
if six.text_type(opts['speed']) in valid:
config.update({'speed': opts['speed']})
else:
_raise_error_iface(iface, opts['speed'], valid)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'on'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'off'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_ethtool_pppoe_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
for opt in _DEB_CONFIG_PPPOE_OPTS:
if opt in opts:
config[opt] = opts[opt]
if 'provider' in opts and not opts['provider']:
_raise_error_iface(iface, 'provider', _CONFIG_TRUE + _CONFIG_FALSE)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('noipdefault', 'usepeerdns', 'defaultroute', 'hide-password', 'noauth', 'persist', 'noaccomp'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'True'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'False'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_settings_bond(opts, iface):
'''
Filters given options and outputs valid settings for requested
operation. If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond_def = {
# 803.ad aggregation selection logic
# 0 for stable (default)
# 1 for bandwidth
# 2 for count
'ad_select': '0',
# Max number of transmit queues (default = 16)
'tx_queues': '16',
# Link monitoring in milliseconds. Most NICs support this
'miimon': '100',
# ARP interval in milliseconds
'arp_interval': '250',
# Delay before considering link down in milliseconds (miimon * 2)
'downdelay': '200',
# lacp_rate 0: Slow - every 30 seconds
# lacp_rate 1: Fast - every 1 second
'lacp_rate': '0',
# Max bonds for this driver
'max_bonds': '1',
# Specifies the time, in milliseconds, to wait before
# enabling a slave after a link recovery has been
# detected. Only used with miimon.
'updelay': '0',
# Used with miimon.
# On: driver sends mii
# Off: ethtool sends mii
'use_carrier': 'on',
# Default. Don't change unless you know what you are doing.
'xmit_hash_policy': 'layer2',
}
if opts['mode'] in ['balance-rr', '0']:
log.info('Device: %s Bonding Mode: load balancing (round-robin)', iface)
return _parse_settings_bond_0(opts, iface, bond_def)
elif opts['mode'] in ['active-backup', '1']:
log.info('Device: %s Bonding Mode: fault-tolerance (active-backup)', iface)
return _parse_settings_bond_1(opts, iface, bond_def)
elif opts['mode'] in ['balance-xor', '2']:
log.info('Device: %s Bonding Mode: load balancing (xor)', iface)
return _parse_settings_bond_2(opts, iface, bond_def)
elif opts['mode'] in ['broadcast', '3']:
log.info('Device: %s Bonding Mode: fault-tolerance (broadcast)', iface)
return _parse_settings_bond_3(opts, iface, bond_def)
elif opts['mode'] in ['802.3ad', '4']:
log.info('Device: %s Bonding Mode: IEEE 802.3ad Dynamic link '
'aggregation', iface)
return _parse_settings_bond_4(opts, iface, bond_def)
elif opts['mode'] in ['balance-tlb', '5']:
log.info('Device: %s Bonding Mode: transmit load balancing', iface)
return _parse_settings_bond_5(opts, iface, bond_def)
elif opts['mode'] in ['balance-alb', '6']:
log.info('Device: %s Bonding Mode: adaptive load balancing', iface)
return _parse_settings_bond_6(opts, iface, bond_def)
else:
valid = [
'0', '1', '2', '3', '4', '5', '6',
'balance-rr', 'active-backup', 'balance-xor',
'broadcast', '802.3ad', 'balance-tlb', 'balance-alb'
]
_raise_error_iface(iface, 'mode', valid)
def _parse_settings_bond_0(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond0.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '0'}
# ARP targets in n.n.n.n form
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
return bond
def _parse_settings_bond_1(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '1'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
if not (__grains__['os'] == "Ubuntu" and __grains__['osrelease_info'][0] >= 16):
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_2(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond2.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '2'}
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_3(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond3.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '3'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_4(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond4.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '4'}
for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']:
if binding in opts:
if binding == 'lacp_rate':
if opts[binding] == 'fast':
opts.update({binding: '1'})
if opts[binding] == 'slow':
opts.update({binding: '0'})
valid = ['fast', '1', 'slow', '0']
else:
valid = ['integer']
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, valid)
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_5(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond5.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '5'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_settings_bond_6(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond6.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '6'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_bridge_opts(opts, iface):
'''
Filters given options and outputs valid settings for BRIDGING_OPTS
If an option has a value that is not expected, this
function will log the Interface, Setting and what was expected.
'''
config = {}
if 'ports' in opts:
if isinstance(opts['ports'], list):
opts['ports'] = ' '.join(opts['ports'])
config.update({'ports': opts['ports']})
for opt in ['ageing', 'fd', 'gcint', 'hello', 'maxage']:
if opt in opts:
try:
float(opts[opt])
config.update({opt: opts[opt]})
except ValueError:
_raise_error_iface(iface, opt, ['float'])
for opt in ['bridgeprio', 'maxwait']:
if opt in opts:
if isinstance(opts[opt], int):
config.update({opt: opts[opt]})
else:
_raise_error_iface(iface, opt, ['integer'])
if 'hw' in opts:
# match 12 hex digits with either : or - as separators between pairs
if re.match('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$',
opts['hw'].lower()):
config.update({'hw': opts['hw']})
else:
_raise_error_iface(iface, 'hw', ['valid MAC address'])
for opt in ['pathcost', 'portprio']:
if opt in opts:
try:
port, cost_or_prio = opts[opt].split()
int(cost_or_prio)
config.update({opt: '{0} {1}'.format(port, cost_or_prio)})
except ValueError:
_raise_error_iface(iface, opt, ['interface integer'])
if 'stp' in opts:
if opts['stp'] in _CONFIG_TRUE:
config.update({'stp': 'on'})
elif opts['stp'] in _CONFIG_FALSE:
config.update({'stp': 'off'})
else:
_raise_error_iface(iface, 'stp', _CONFIG_TRUE + _CONFIG_FALSE)
if 'waitport' in opts:
if isinstance(opts['waitport'], int):
config.update({'waitport': opts['waitport']})
else:
values = opts['waitport'].split()
waitport_time = values.pop(0)
if waitport_time.isdigit() and values:
config.update({
'waitport': '{0} {1}'.format(
waitport_time, ' '.join(values)
)
})
else:
_raise_error_iface(iface, opt, ['integer [interfaces]'])
return config
def _parse_settings_eth(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['inet'] = salt.utils.odict.OrderedDict()
iface_data['inet6'] = salt.utils.odict.OrderedDict()
if enabled:
adapters[iface]['enabled'] = True
if opts.get('hotplug', False):
adapters[iface]['hotplug'] = True
if opts.get('enable_ipv6', None) and opts.get('iface_type', '') == 'vlan':
iface_data['inet6']['vlan_raw_device'] = (
re.sub(r'\.\d*', '', iface))
for addrfam in ['inet', 'inet6']:
if iface_type not in ['bridge']:
tmp_ethtool = _parse_ethtool_opts(opts, iface)
if tmp_ethtool:
ethtool = {}
for item in tmp_ethtool:
ethtool[_ETHTOOL_CONFIG_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['ethtool'] = ethtool
# return a list of sorted keys to ensure consistent order
iface_data[addrfam]['ethtool_keys'] = sorted(ethtool)
if iface_type == 'bridge':
bridging = _parse_bridge_opts(opts, iface)
if bridging:
iface_data[addrfam]['bridging'] = bridging
iface_data[addrfam]['bridging_keys'] = sorted(bridging)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'bond':
bonding = _parse_settings_bond(opts, iface)
if bonding:
iface_data[addrfam]['bonding'] = bonding
iface_data[addrfam]['bonding']['slaves'] = opts['slaves']
iface_data[addrfam]['bonding_keys'] = sorted(bonding)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'slave':
adapters[iface]['master'] = opts['master']
opts['proto'] = 'manual'
iface_data[addrfam]['master'] = adapters[iface]['master']
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'vlan':
iface_data[addrfam]['vlan_raw_device'] = re.sub(r'\.\d*', '', iface)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'pppoe':
tmp_ethtool = _parse_ethtool_pppoe_opts(opts, iface)
if tmp_ethtool:
for item in tmp_ethtool:
adapters[iface]['data'][addrfam][_DEB_CONFIG_PPPOE_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['addrfam'] = addrfam
opts.pop('mode', None)
for opt, val in opts.items():
inet = None
if opt.startswith('ipv4'):
opt = opt[4:]
inet = 'inet'
iface_data['inet']['addrfam'] = 'inet'
elif opt.startswith('ipv6'):
iface_data['inet6']['addrfam'] = 'inet6'
opt = opt[4:]
inet = 'inet6'
elif opt in ['ipaddr', 'address', 'ipaddresses', 'addresses', 'gateway', 'proto']:
iface_data['inet']['addrfam'] = 'inet'
inet = 'inet'
_opt = SALT_ATTR_TO_DEBIAN_ATTR_MAP.get(opt, opt)
_debopt = _opt.replace('-', '_')
for addrfam in ['inet', 'inet6']:
(valid, value, errmsg) = _validate_interface_option(_opt, val, addrfam=addrfam)
if not valid:
continue
if inet is None and _debopt not in iface_data[addrfam]:
iface_data[addrfam][_debopt] = value
elif inet == addrfam:
iface_data[addrfam][_debopt] = value
for opt in ['up_cmds', 'pre_up_cmds', 'post_up_cmds',
'down_cmds', 'pre_down_cmds', 'post_down_cmds']:
if opt in opts:
iface_data['inet'][opt] = opts[opt]
iface_data['inet6'][opt] = opts[opt]
# Remove incomplete/disabled inet blocks
for (addrfam, opt) in [('inet', 'enable_ipv4'), ('inet6', 'enable_ipv6')]:
if opts.get(opt, None) is False:
iface_data.pop(addrfam)
elif iface_data[addrfam].get('addrfam', '') != addrfam:
iface_data.pop(addrfam)
return adapters
def _parse_settings_source(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['sources'] = [opts['source']]
return adapters
def _parse_network_settings(opts, current):
'''
Filters given options and outputs valid settings for
the global network settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
current = dict((k.lower(), v) for (k, v) in six.iteritems(current))
result = {}
valid = _CONFIG_TRUE + _CONFIG_FALSE
if 'enabled' not in opts:
try:
opts['networking'] = current['networking']
_log_default_network('networking', current['networking'])
except ValueError:
_raise_error_network('networking', valid)
else:
opts['networking'] = opts['enabled']
if opts['networking'] in valid:
if opts['networking'] in _CONFIG_TRUE:
result['networking'] = 'yes'
elif opts['networking'] in _CONFIG_FALSE:
result['networking'] = 'no'
else:
_raise_error_network('networking', valid)
if 'hostname' not in opts:
try:
opts['hostname'] = current['hostname']
_log_default_network('hostname', current['hostname'])
except ValueError:
_raise_error_network('hostname', ['server1.example.com'])
if opts['hostname']:
result['hostname'] = opts['hostname']
else:
_raise_error_network('hostname', ['server1.example.com'])
if 'search' in opts:
result['search'] = opts['search']
return result
def _parse_routes(iface, opts):
'''
Filters given options and outputs valid settings for
the route settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
result = {}
if 'routes' not in opts:
_raise_error_routes(iface, 'routes', 'List of routes')
for opt in opts:
result[opt] = opts[opt]
return result
def _write_file(iface, data, folder, pattern):
'''
Writes a file to disk
'''
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
return filename
def _write_file_routes(iface, data, folder, pattern):
'''
Writes a file to disk
'''
# ifup / ifdown is executing given folder via run-parts.
# according to run-parts man-page, only filenames with this pattern are
# executed: (^[a-zA-Z0-9_-]+$)
# In order to make the routes file work for vlan interfaces
# (default would have been in example /etc/network/if-up.d/route-bond0.12)
# these dots in the iface name need to be replaced by underscores, so it
# can be executed by run-parts
iface = iface.replace('.', '_')
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
__salt__['file.set_mode'](filename, '0755')
return filename
def _write_file_network(data, filename, create=False):
'''
Writes a file to disk
If file does not exist, only create if create
argument is True
'''
if not os.path.exists(filename) and not create:
msg = '{0} cannot be written. {0} does not exist\
and create is set to False'
msg = msg.format(filename)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
def _read_temp(data):
'''
Return what would be written to disk
'''
tout = StringIO()
tout.write(data)
tout.seek(0)
output = tout.readlines()
tout.close()
return output
def _read_temp_ifaces(iface, data):
'''
Return what would be written to disk for interfaces
'''
try:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': data})
# Return as an array so the difflib works
return [item + '\n' for item in ifcfg.split('\n')]
def _write_file_ppp_ifaces(iface, data):
'''
Writes a file to disk
'''
try:
template = JINJA.get_template('debian_ppp_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_ppp_eth.jinja')
return ''
adapters = _parse_interfaces()
adapters[iface] = data
ifcfg = ''
tmp = template.render({'data': adapters[iface]})
ifcfg = tmp + ifcfg
filename = _DEB_PPP_DIR + '/' + adapters[iface]['data']['inet']['provider']
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.fopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return filename
def build_bond(iface, **settings):
'''
Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb
'''
deb_major = __grains__['osrelease'][:1]
opts = _parse_settings_bond(settings, iface)
try:
template = JINJA.get_template('conf.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template conf.jinja')
return ''
data = template.render({'name': iface, 'bonding': opts})
if 'test' in settings and settings['test']:
return _read_temp(data)
_write_file(iface, data, _DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
if deb_major == '5':
for line_type in ('alias', 'options'):
cmd = ['sed', '-i', '-e', r'/^{0}\s{1}.*/d'.format(line_type, iface),
'/etc/modprobe.conf']
__salt__['cmd.run'](cmd, python_shell=False)
__salt__['file.append']('/etc/modprobe.conf', path)
# Load kernel module
__salt__['kmod.load']('bonding')
# install ifenslave-2.6
__salt__['pkg.install']('ifenslave-2.6')
return _read_file(path)
def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'vlan':
settings['vlan'] = 'yes'
__salt__['pkg.install']('vlan')
elif iface_type == 'pppoe':
settings['pppoe'] = 'yes'
if not __salt__['pkg.version']('ppp'):
inst = __salt__['pkg.install']('ppp')
elif iface_type == 'bond':
if 'slaves' not in settings:
msg = 'slaves is a required setting for bond interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'bridge':
if 'ports' not in settings:
msg = (
'ports is a required setting for bridge interfaces on Debian '
'or Ubuntu based systems'
)
log.error(msg)
raise AttributeError(msg)
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'pppoe']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
if iface_type in ['source']:
opts = _parse_settings_source(settings, iface_type, enabled, iface)
if 'test' in settings and settings['test']:
return _read_temp_ifaces(iface, opts[iface])
ifcfg = _write_file_ifaces(iface, opts[iface], **settings)
if iface_type == 'pppoe':
_write_file_ppp_ifaces(iface, opts[iface])
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg]
def build_routes(iface, **settings):
'''
Add route scripts for a network interface using up commands.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
'''
opts = _parse_routes(iface, settings)
try:
template = JINJA.get_template('route_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template route_eth.jinja')
return ''
add_routecfg = template.render(route_type='add',
routes=opts['routes'],
iface=iface)
del_routecfg = template.render(route_type='del',
routes=opts['routes'],
iface=iface)
if 'test' in settings and settings['test']:
return _read_temp(add_routecfg + del_routecfg)
filename = _write_file_routes(iface,
add_routecfg,
_DEB_NETWORK_UP_DIR,
'route-{0}')
results = _read_file(filename)
filename = _write_file_routes(iface,
del_routecfg,
_DEB_NETWORK_DOWN_DIR,
'route-{0}')
results += _read_file(filename)
return results
def down(iface, iface_type):
'''
Shutdown a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.down eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought down.
if iface_type not in ['slave', 'source']:
return __salt__['cmd.run'](['ifdown', iface])
return None
def get_bond(iface):
'''
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
'''
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
return _read_file(path)
def get_interface(iface):
'''
Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
adapters = _parse_interfaces()
if iface in adapters:
try:
if iface == 'source':
template = JINJA.get_template('debian_source.jinja')
else:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': adapters[iface]})
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg.split('\n')]
else:
return []
def up(iface, iface_type): # pylint: disable=C0103
'''
Start up a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.up eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought up.
if iface_type not in ('slave', 'source'):
return __salt__['cmd.run'](['ifup', iface])
return None
def get_network_settings():
'''
Return the contents of the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_network_settings
'''
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
settings = {}
if __salt__['service.available']('networking'):
if __salt__['service.status']('networking'):
settings['networking'] = "yes"
else:
settings['networking'] = "no"
else:
settings['networking'] = "no"
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
settings['hostname'] = hostname
settings['domainname'] = domainname
settings['searchdomain'] = searchdomain
else:
settings = _parse_current_network_settings()
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(settings)
return _read_temp(network)
def get_routes(iface):
'''
Return the routes for the interface
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0
'''
filename = os.path.join(_DEB_NETWORK_UP_DIR, 'route-{0}'.format(iface))
results = _read_file(filename)
filename = os.path.join(_DEB_NETWORK_DOWN_DIR, 'route-{0}'.format(iface))
results += _read_file(filename)
return results
def apply_network_settings(**settings):
'''
Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings
'''
if 'require_reboot' not in settings:
settings['require_reboot'] = False
if 'apply_hostname' not in settings:
settings['apply_hostname'] = False
hostname_res = True
if settings['apply_hostname'] in _CONFIG_TRUE:
if 'hostname' in settings:
hostname_res = __salt__['network.mod_hostname'](settings['hostname'])
else:
log.warning(
'The network state sls is trying to apply hostname '
'changes but no hostname is defined.'
)
hostname_res = False
res = True
if settings['require_reboot'] in _CONFIG_TRUE:
log.warning(
'The network state sls is requiring a reboot of the system to '
'properly apply network configuration.'
)
res = True
else:
stop = __salt__['service.stop']('networking')
time.sleep(2)
res = stop and __salt__['service.start']('networking')
return hostname_res and res
def build_network_settings(**settings):
'''
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
'''
changes = []
# Read current configuration and store default values
current_network_settings = _parse_current_network_settings()
# Build settings
opts = _parse_network_settings(settings, current_network_settings)
# Ubuntu has moved away from /etc/default/networking
# beginning with the 12.04 release so we disable or enable
# the networking related services on boot
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
if opts['networking'] == 'yes':
service_cmd = 'service.enable'
else:
service_cmd = 'service.disable'
if __salt__['service.available']('NetworkManager'):
__salt__[service_cmd]('NetworkManager')
if __salt__['service.available']('networking'):
__salt__[service_cmd]('networking')
else:
try:
template = JINJA.get_template('network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template network.jinja')
return ''
network = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(network)
# Write settings
_write_file_network(network, _DEB_NETWORKING_FILE, True)
# Get hostname and domain from opts
sline = opts['hostname'].split('.', 1)
opts['hostname'] = sline[0]
current_domainname = current_network_settings['domainname']
current_searchdomain = current_network_settings['searchdomain']
new_domain = False
if len(sline) > 1:
new_domainname = sline[1]
if new_domainname != current_domainname:
domainname = new_domainname
opts['domainname'] = new_domainname
new_domain = True
else:
domainname = current_domainname
opts['domainname'] = domainname
else:
domainname = current_domainname
opts['domainname'] = domainname
new_search = False
if 'search' in opts:
new_searchdomain = opts['search']
if new_searchdomain != current_searchdomain:
searchdomain = new_searchdomain
opts['searchdomain'] = new_searchdomain
new_search = True
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
# If the domain changes, then we should write the resolv.conf file.
if new_domain or new_search:
# Look for existing domain line and update if necessary
resolve = _parse_resolve()
domain_prog = re.compile(r'domain\s+')
search_prog = re.compile(r'search\s+')
new_contents = []
for item in _read_file(_DEB_RESOLV_FILE):
if domain_prog.match(item):
item = 'domain {0}'.format(domainname)
elif search_prog.match(item):
item = 'search {0}'.format(searchdomain)
new_contents.append(item)
# A domain line didn't exist so we'll add one in
# with the new domainname
if 'domain' not in resolve:
new_contents.insert(0, 'domain {0}' . format(domainname))
# A search line didn't exist so we'll add one in
# with the new search domain
if 'search' not in resolve:
new_contents.insert('domain' in resolve, 'search {0}'.format(searchdomain))
new_resolv = '\n'.join(new_contents)
# Write /etc/resolv.conf
if not ('test' in settings and settings['test']):
_write_file_network(new_resolv, _DEB_RESOLV_FILE)
# used for returning the results back
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(opts)
changes.extend(_read_temp(network))
return changes
|
saltstack/salt
|
salt/modules/debian_ip.py
|
_write_file_ppp_ifaces
|
python
|
def _write_file_ppp_ifaces(iface, data):
'''
Writes a file to disk
'''
try:
template = JINJA.get_template('debian_ppp_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_ppp_eth.jinja')
return ''
adapters = _parse_interfaces()
adapters[iface] = data
ifcfg = ''
tmp = template.render({'data': adapters[iface]})
ifcfg = tmp + ifcfg
filename = _DEB_PPP_DIR + '/' + adapters[iface]['data']['inet']['provider']
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.fopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return filename
|
Writes a file to disk
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_ip.py#L1535-L1562
|
[
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n",
"def to_str(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str, bytes, bytearray, or unicode (py2), return str\n '''\n def _normalize(s):\n try:\n return unicodedata.normalize('NFC', s) if normalize else s\n except TypeError:\n return s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n # This shouldn't be six.string_types because if we're on PY2 and we already\n # have a string, we should just return it.\n if isinstance(s, str):\n return _normalize(s)\n\n exc = None\n if six.PY3:\n if isinstance(s, (bytes, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytes, or bytearray not {}'.format(type(s)))\n else:\n if isinstance(s, bytearray):\n return str(s) # future lint: disable=blacklisted-function\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n for enc in encoding:\n try:\n return _normalize(s).encode(enc, errors)\n except UnicodeEncodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytearray, or unicode')\n",
"def _parse_interfaces(interface_files=None):\n '''\n Parse /etc/network/interfaces and return current configured interfaces\n '''\n if interface_files is None:\n interface_files = []\n # Add this later.\n if os.path.exists(_DEB_NETWORK_DIR):\n interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]\n\n if os.path.isfile(_DEB_NETWORK_FILE):\n interface_files.insert(0, _DEB_NETWORK_FILE)\n\n adapters = salt.utils.odict.OrderedDict()\n method = -1\n\n for interface_file in interface_files:\n with salt.utils.files.fopen(interface_file) as interfaces:\n # This ensures iface_dict exists, but does not ensure we're not reading a new interface.\n iface_dict = {}\n for line in interfaces:\n line = salt.utils.stringutils.to_unicode(line)\n # Identify the clauses by the first word of each line.\n # Go to the next line if the current line is a comment\n # or all spaces.\n if line.lstrip().startswith('#') or line.isspace():\n continue\n # Parse the iface clause\n if line.startswith('iface'):\n sline = line.split()\n\n if len(sline) != 4:\n msg = 'Interface file malformed: {0}.'\n msg = msg.format(sline)\n log.error(msg)\n raise AttributeError(msg)\n\n iface_name = sline[1]\n addrfam = sline[2]\n method = sline[3]\n\n # Create item in dict, if not already there\n if iface_name not in adapters:\n adapters[iface_name] = salt.utils.odict.OrderedDict()\n\n # Create item in dict, if not already there\n if 'data' not in adapters[iface_name]:\n adapters[iface_name]['data'] = salt.utils.odict.OrderedDict()\n\n if addrfam not in adapters[iface_name]['data']:\n adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict()\n\n iface_dict = adapters[iface_name]['data'][addrfam]\n\n iface_dict['addrfam'] = addrfam\n iface_dict['proto'] = method\n iface_dict['filename'] = interface_file\n\n # Parse the detail clauses.\n elif line[0].isspace():\n sline = line.split()\n\n # conf file attr: dns-nameservers\n # salt states.network attr: dns\n\n attr, valuestr = line.rstrip().split(None, 1)\n if _attrmaps_contain_attr(attr):\n if '-' in attr:\n attrname = attr.replace('-', '_')\n else:\n attrname = attr\n (valid, value, errmsg) = _validate_interface_option(\n attr, valuestr, addrfam)\n if attrname == 'address' and 'address' in iface_dict:\n if 'addresses' not in iface_dict:\n iface_dict['addresses'] = []\n iface_dict['addresses'].append(value)\n else:\n iface_dict[attrname] = value\n\n elif attr in _REV_ETHTOOL_CONFIG_OPTS:\n if 'ethtool' not in iface_dict:\n iface_dict['ethtool'] = salt.utils.odict.OrderedDict()\n iface_dict['ethtool'][attr] = valuestr\n\n elif attr.startswith('bond'):\n opt = re.split(r'[_-]', attr, maxsplit=1)[1]\n if 'bonding' not in iface_dict:\n iface_dict['bonding'] = salt.utils.odict.OrderedDict()\n iface_dict['bonding'][opt] = valuestr\n\n elif attr.startswith('bridge'):\n opt = re.split(r'[_-]', attr, maxsplit=1)[1]\n if 'bridging' not in iface_dict:\n iface_dict['bridging'] = salt.utils.odict.OrderedDict()\n iface_dict['bridging'][opt] = valuestr\n\n elif attr in ['up', 'pre-up', 'post-up',\n 'down', 'pre-down', 'post-down']:\n cmd = valuestr\n cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr))\n if cmd_key not in iface_dict:\n iface_dict[cmd_key] = []\n iface_dict[cmd_key].append(cmd)\n\n elif line.startswith('auto'):\n for word in line.split()[1:]:\n if word not in adapters:\n adapters[word] = salt.utils.odict.OrderedDict()\n adapters[word]['enabled'] = True\n\n elif line.startswith('allow-hotplug'):\n for word in line.split()[1:]:\n if word not in adapters:\n adapters[word] = salt.utils.odict.OrderedDict()\n adapters[word]['hotplug'] = True\n\n elif line.startswith('source'):\n if 'source' not in adapters:\n adapters['source'] = salt.utils.odict.OrderedDict()\n\n # Create item in dict, if not already there\n if 'data' not in adapters['source']:\n adapters['source']['data'] = salt.utils.odict.OrderedDict()\n adapters['source']['data']['sources'] = []\n adapters['source']['data']['sources'].append(line.split()[1])\n\n # Return a sorted list of the keys for bond, bridge and ethtool options to\n # ensure a consistent order\n for iface_name in adapters:\n if iface_name == 'source':\n continue\n if 'data' not in adapters[iface_name]:\n msg = 'Interface file malformed for interface: {0}.'.format(iface_name)\n log.error(msg)\n adapters.pop(iface_name)\n continue\n for opt in ['ethtool', 'bonding', 'bridging']:\n for inet in ['inet', 'inet6']:\n if inet in adapters[iface_name]['data']:\n if opt in adapters[iface_name]['data'][inet]:\n opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys())\n adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys\n\n return adapters\n"
] |
# -*- coding: utf-8 -*-
'''
The networking module for Debian-based distros
References:
* http://www.debian.org/doc/manuals/debian-reference/ch05.en.html
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import functools
import logging
import os.path
import os
import re
import time
# Import third party libs
import jinja2
import jinja2.exceptions
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error,no-name-in-module
# Import salt libs
import salt.utils.dns
import salt.utils.files
import salt.utils.odict
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.validate.net
# Set up logging
log = logging.getLogger(__name__)
# Set up template environment
JINJA = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'debian_ip')
)
)
# Define the module's virtual name
__virtualname__ = 'ip'
def __virtual__():
'''
Confine this module to Debian-based distros
'''
if __grains__['os_family'] == 'Debian':
return __virtualname__
return (False, 'The debian_ip module could not be loaded: '
'unsupported OS family')
_ETHTOOL_CONFIG_OPTS = {
'speed': 'link-speed',
'duplex': 'link-duplex',
'autoneg': 'ethernet-autoneg',
'ethernet-port': 'ethernet-port',
'wol': 'ethernet-wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'rx': 'offload-rx',
'tx': 'offload-tx',
'sg': 'offload-sg',
'tso': 'offload-tso',
'ufo': 'offload-ufo',
'gso': 'offload-gso',
'gro': 'offload-gro',
'lro': 'offload-lro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_REV_ETHTOOL_CONFIG_OPTS = {
'link-speed': 'speed',
'link-duplex': 'duplex',
'ethernet-autoneg': 'autoneg',
'ethernet-port': 'ethernet-port',
'ethernet-wol': 'wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'offload-rx': 'rx',
'offload-tx': 'tx',
'offload-sg': 'sg',
'offload-tso': 'tso',
'offload-ufo': 'ufo',
'offload-gso': 'gso',
'offload-lro': 'lro',
'offload-gro': 'gro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_DEB_CONFIG_PPPOE_OPTS = {
'user': 'user',
'password': 'password',
'provider': 'provider',
'pppoe_iface': 'pppoe_iface',
'noipdefault': 'noipdefault',
'usepeerdns': 'usepeerdns',
'defaultroute': 'defaultroute',
'holdoff': 'holdoff',
'maxfail': 'maxfail',
'hide-password': 'hide-password',
'lcp-echo-interval': 'lcp-echo-interval',
'lcp-echo-failure': 'lcp-echo-failure',
'connect': 'connect',
'noauth': 'noauth',
'persist': 'persist',
'mtu': 'mtu',
'noaccomp': 'noaccomp',
'linkname': 'linkname',
}
_DEB_ROUTES_FILE = '/etc/network/routes'
_DEB_NETWORK_FILE = '/etc/network/interfaces'
_DEB_NETWORK_DIR = '/etc/network/interfaces.d/'
_DEB_NETWORK_UP_DIR = '/etc/network/if-up.d/'
_DEB_NETWORK_DOWN_DIR = '/etc/network/if-down.d/'
_DEB_NETWORK_CONF_FILES = '/etc/modprobe.d/'
_DEB_NETWORKING_FILE = '/etc/default/networking'
_DEB_HOSTNAME_FILE = '/etc/hostname'
_DEB_RESOLV_FILE = '/etc/resolv.conf'
_DEB_PPP_DIR = '/etc/ppp/peers/'
_CONFIG_TRUE = ['yes', 'on', 'true', '1', True]
_CONFIG_FALSE = ['no', 'off', 'false', '0', False]
_IFACE_TYPES = [
'eth', 'bond', 'alias', 'clone',
'ipsec', 'dialup', 'bridge', 'slave',
'vlan', 'pppoe', 'source',
]
def _error_msg_iface(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, '|'.join(str(e) for e in expected))
def _error_msg_routes(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, expected)
def _log_default_iface(iface, opt, value):
log.info(
'Using default option -- Interface: %s Option: %s Value: %s',
iface, opt, value
)
def _error_msg_network(option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]'
return msg.format(option, '|'.join(str(e) for e in expected))
def _log_default_network(opt, value):
log.info('Using existing setting -- Setting: %s Value: %s', opt, value)
def _raise_error_iface(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_iface(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_network(option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_network(option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_routes(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_routes(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _read_file(path):
'''
Reads and returns the contents of a text file
'''
try:
with salt.utils.files.flopen(path, 'rb') as contents:
return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]
except (OSError, IOError):
return ''
def _parse_resolve():
'''
Parse /etc/resolv.conf
'''
return salt.utils.dns.parse_resolv(_DEB_RESOLV_FILE)
def _parse_domainname():
'''
Parse /etc/resolv.conf and return domainname
'''
return _parse_resolve().get('domain', '')
def _parse_searchdomain():
'''
Parse /etc/resolv.conf and return searchdomain
'''
return _parse_resolve().get('search', '')
def _parse_hostname():
'''
Parse /etc/hostname and return hostname
'''
contents = _read_file(_DEB_HOSTNAME_FILE)
if contents:
return contents[0].split('\n')[0]
else:
return ''
def _parse_current_network_settings():
'''
Parse /etc/default/networking and return current configuration
'''
opts = salt.utils.odict.OrderedDict()
opts['networking'] = ''
if os.path.isfile(_DEB_NETWORKING_FILE):
with salt.utils.files.fopen(_DEB_NETWORKING_FILE) as contents:
for line in contents:
salt.utils.stringutils.to_unicode(line)
if line.startswith('#'):
continue
elif line.startswith('CONFIGURE_INTERFACES'):
opts['networking'] = line.split('=', 1)[1].strip()
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
opts['hostname'] = hostname
opts['domainname'] = domainname
opts['searchdomain'] = searchdomain
return opts
# def __validator_func(value):
# return (valid: True/False, (transformed) value, error message)
def __ipv4_quad(value):
'''validate an IPv4 address'''
return (salt.utils.validate.net.ipv4_addr(value), value,
'dotted IPv4 address')
def __ipv6(value):
'''validate an IPv6 address'''
return (salt.utils.validate.net.ipv6_addr(value), value,
'IPv6 address')
def __mac(value):
'''validate a mac address'''
return (salt.utils.validate.net.mac(value), value,
'MAC address')
def __anything(value):
return (True, value, None)
def __int(value):
'''validate an integer'''
valid, _value = False, value
try:
_value = int(value)
valid = True
except ValueError:
pass
return (valid, _value, 'integer')
def __float(value):
'''validate a float'''
valid, _value = False, value
try:
_value = float(value)
valid = True
except ValueError:
pass
return (valid, _value, 'float')
def __ipv4_netmask(value):
'''validate an IPv4 dotted quad or integer CIDR netmask'''
valid, errmsg = False, 'dotted quad or integer CIDR (0->32)'
valid, value, _ = __int(value)
if not (valid and 0 <= value <= 32):
valid = salt.utils.validate.net.netmask(value)
return (valid, value, errmsg)
def __ipv6_netmask(value):
'''validate an IPv6 integer netmask'''
valid, errmsg = False, 'IPv6 netmask (0->128)'
valid, value, _ = __int(value)
valid = (valid and 0 <= value <= 128)
return (valid, value, errmsg)
def __within2(value, within=None, errmsg=None, dtype=None):
'''validate that a value is in ``within`` and optionally a ``dtype``'''
valid, _value = False, value
if dtype:
try:
_value = dtype(value) # TODO: this is a bit loose when dtype is a class
valid = _value in within
except ValueError:
pass
else:
valid = _value in within
if errmsg is None:
if dtype:
typename = getattr(dtype, '__name__',
hasattr(dtype, '__class__')
and getattr(dtype.__class__, 'name', dtype))
errmsg = '{0} within \'{1}\''.format(typename, within)
else:
errmsg = 'within \'{0}\''.format(within)
return (valid, _value, errmsg)
def __within(within=None, errmsg=None, dtype=None):
return functools.partial(__within2, within=within,
errmsg=errmsg, dtype=dtype)
def __space_delimited_list(value):
'''validate that a value contains one or more space-delimited values'''
if isinstance(value, six.string_types):
value = value.strip().split()
if hasattr(value, '__iter__') and value != []:
return (True, value, 'space-delimited string')
else:
return (False, value, '{0} is not a valid space-delimited value.\n'.format(value))
SALT_ATTR_TO_DEBIAN_ATTR_MAP = {
'dns': 'dns-nameservers',
'search': 'dns-search',
'hwaddr': 'hwaddress', # TODO: this limits bootp functionality
'ipaddr': 'address',
'ipaddrs': 'addresses',
}
DEBIAN_ATTR_TO_SALT_ATTR_MAP = dict(
(v, k) for (k, v) in six.iteritems(SALT_ATTR_TO_DEBIAN_ATTR_MAP))
# TODO
DEBIAN_ATTR_TO_SALT_ATTR_MAP['address'] = 'address'
DEBIAN_ATTR_TO_SALT_ATTR_MAP['hwaddress'] = 'hwaddress'
IPV4_VALID_PROTO = ['bootp', 'dhcp', 'static', 'manual', 'loopback', 'ppp']
IPV4_ATTR_MAP = {
'proto': __within(IPV4_VALID_PROTO, dtype=six.text_type),
# ipv4 static & manual
'address': __ipv4_quad,
'addresses': __anything,
'netmask': __ipv4_netmask,
'broadcast': __ipv4_quad,
'metric': __int,
'gateway': __ipv4_quad, # supports a colon-delimited list
'pointopoint': __ipv4_quad,
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'link', 'host'], dtype=six.text_type),
# dhcp
'hostname': __anything,
'leasehours': __int,
'leasetime': __int,
'vendor': __anything,
'client': __anything,
# bootp
'bootfile': __anything,
'server': __ipv4_quad,
'hwaddr': __mac,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'dstaddr': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# bond
'slaves': __anything,
# ppp
'provider': __anything,
'unit': __int,
'options': __anything,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
#
'network': __anything, # i don't know what this is
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
IPV6_VALID_PROTO = ['auto', 'loopback', 'static', 'manual',
'dhcp', 'v4tunnel', '6to4']
IPV6_ATTR_MAP = {
'proto': __within(IPV6_VALID_PROTO),
# ipv6 static & manual
'address': __ipv6,
'addresses': __anything,
'netmask': __ipv6_netmask,
'broadcast': __ipv6,
'gateway': __ipv6, # supports a colon-delimited list
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'site', 'link', 'host'], dtype=six.text_type),
# inet6 auto
'privext': __within([0, 1, 2], dtype=int),
'dhcp': __within([0, 1], dtype=int),
# inet6 static & manual & dhcp
'media': __anything,
'accept_ra': __within([0, 1], dtype=int),
'autoconf': __within([0, 1], dtype=int),
'preferred-lifetime': __int,
'dad-attempts': __int, # 0 to disable
'dad-interval': __float,
# bond
'slaves': __anything,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
WIRELESS_ATTR_MAP = {
'wireless-essid': __anything,
'wireless-mode': __anything, # TODO
'wpa-ap-scan': __within([0, 1, 2], dtype=int), # TODO
'wpa-conf': __anything,
'wpa-driver': __anything,
'wpa-group': __anything,
'wpa-key-mgmt': __anything,
'wpa-pairwise': __anything,
'wpa-psk': __anything,
'wpa-proto': __anything, # partial(__within,
'wpa-roam': __anything,
'wpa-ssid': __anything, # TODO
}
ATTRMAPS = {
'inet': [IPV4_ATTR_MAP, WIRELESS_ATTR_MAP],
'inet6': [IPV6_ATTR_MAP, WIRELESS_ATTR_MAP]
}
def _validate_interface_option(attr, value, addrfam='inet'):
'''lookup the validation function for a [addrfam][attr] and
return the results
:param attr: attribute name
:param value: raw setting value
:param addrfam: address family (inet, inet6,
'''
valid, _value, errmsg = False, value, 'Unknown validator'
attrmaps = ATTRMAPS.get(addrfam, [])
for attrmap in attrmaps:
if attr in attrmap:
validate_func = attrmap[attr]
(valid, _value, errmsg) = validate_func(value)
break
return (valid, _value, errmsg)
def _attrmaps_contain_attr(attr):
return (
attr in WIRELESS_ATTR_MAP or
attr in IPV4_ATTR_MAP or
attr in IPV6_ATTR_MAP)
def _parse_interfaces(interface_files=None):
'''
Parse /etc/network/interfaces and return current configured interfaces
'''
if interface_files is None:
interface_files = []
# Add this later.
if os.path.exists(_DEB_NETWORK_DIR):
interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]
if os.path.isfile(_DEB_NETWORK_FILE):
interface_files.insert(0, _DEB_NETWORK_FILE)
adapters = salt.utils.odict.OrderedDict()
method = -1
for interface_file in interface_files:
with salt.utils.files.fopen(interface_file) as interfaces:
# This ensures iface_dict exists, but does not ensure we're not reading a new interface.
iface_dict = {}
for line in interfaces:
line = salt.utils.stringutils.to_unicode(line)
# Identify the clauses by the first word of each line.
# Go to the next line if the current line is a comment
# or all spaces.
if line.lstrip().startswith('#') or line.isspace():
continue
# Parse the iface clause
if line.startswith('iface'):
sline = line.split()
if len(sline) != 4:
msg = 'Interface file malformed: {0}.'
msg = msg.format(sline)
log.error(msg)
raise AttributeError(msg)
iface_name = sline[1]
addrfam = sline[2]
method = sline[3]
# Create item in dict, if not already there
if iface_name not in adapters:
adapters[iface_name] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters[iface_name]:
adapters[iface_name]['data'] = salt.utils.odict.OrderedDict()
if addrfam not in adapters[iface_name]['data']:
adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict()
iface_dict = adapters[iface_name]['data'][addrfam]
iface_dict['addrfam'] = addrfam
iface_dict['proto'] = method
iface_dict['filename'] = interface_file
# Parse the detail clauses.
elif line[0].isspace():
sline = line.split()
# conf file attr: dns-nameservers
# salt states.network attr: dns
attr, valuestr = line.rstrip().split(None, 1)
if _attrmaps_contain_attr(attr):
if '-' in attr:
attrname = attr.replace('-', '_')
else:
attrname = attr
(valid, value, errmsg) = _validate_interface_option(
attr, valuestr, addrfam)
if attrname == 'address' and 'address' in iface_dict:
if 'addresses' not in iface_dict:
iface_dict['addresses'] = []
iface_dict['addresses'].append(value)
else:
iface_dict[attrname] = value
elif attr in _REV_ETHTOOL_CONFIG_OPTS:
if 'ethtool' not in iface_dict:
iface_dict['ethtool'] = salt.utils.odict.OrderedDict()
iface_dict['ethtool'][attr] = valuestr
elif attr.startswith('bond'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bonding' not in iface_dict:
iface_dict['bonding'] = salt.utils.odict.OrderedDict()
iface_dict['bonding'][opt] = valuestr
elif attr.startswith('bridge'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bridging' not in iface_dict:
iface_dict['bridging'] = salt.utils.odict.OrderedDict()
iface_dict['bridging'][opt] = valuestr
elif attr in ['up', 'pre-up', 'post-up',
'down', 'pre-down', 'post-down']:
cmd = valuestr
cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr))
if cmd_key not in iface_dict:
iface_dict[cmd_key] = []
iface_dict[cmd_key].append(cmd)
elif line.startswith('auto'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['enabled'] = True
elif line.startswith('allow-hotplug'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['hotplug'] = True
elif line.startswith('source'):
if 'source' not in adapters:
adapters['source'] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters['source']:
adapters['source']['data'] = salt.utils.odict.OrderedDict()
adapters['source']['data']['sources'] = []
adapters['source']['data']['sources'].append(line.split()[1])
# Return a sorted list of the keys for bond, bridge and ethtool options to
# ensure a consistent order
for iface_name in adapters:
if iface_name == 'source':
continue
if 'data' not in adapters[iface_name]:
msg = 'Interface file malformed for interface: {0}.'.format(iface_name)
log.error(msg)
adapters.pop(iface_name)
continue
for opt in ['ethtool', 'bonding', 'bridging']:
for inet in ['inet', 'inet6']:
if inet in adapters[iface_name]['data']:
if opt in adapters[iface_name]['data'][inet]:
opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys())
adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys
return adapters
def _parse_ethtool_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
if 'autoneg' in opts:
if opts['autoneg'] in _CONFIG_TRUE:
config.update({'autoneg': 'on'})
elif opts['autoneg'] in _CONFIG_FALSE:
config.update({'autoneg': 'off'})
else:
_raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE)
if 'duplex' in opts:
valid = ['full', 'half']
if opts['duplex'] in valid:
config.update({'duplex': opts['duplex']})
else:
_raise_error_iface(iface, 'duplex', valid)
if 'speed' in opts:
valid = ['10', '100', '1000', '10000']
if six.text_type(opts['speed']) in valid:
config.update({'speed': opts['speed']})
else:
_raise_error_iface(iface, opts['speed'], valid)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'on'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'off'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_ethtool_pppoe_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
for opt in _DEB_CONFIG_PPPOE_OPTS:
if opt in opts:
config[opt] = opts[opt]
if 'provider' in opts and not opts['provider']:
_raise_error_iface(iface, 'provider', _CONFIG_TRUE + _CONFIG_FALSE)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('noipdefault', 'usepeerdns', 'defaultroute', 'hide-password', 'noauth', 'persist', 'noaccomp'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'True'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'False'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_settings_bond(opts, iface):
'''
Filters given options and outputs valid settings for requested
operation. If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond_def = {
# 803.ad aggregation selection logic
# 0 for stable (default)
# 1 for bandwidth
# 2 for count
'ad_select': '0',
# Max number of transmit queues (default = 16)
'tx_queues': '16',
# Link monitoring in milliseconds. Most NICs support this
'miimon': '100',
# ARP interval in milliseconds
'arp_interval': '250',
# Delay before considering link down in milliseconds (miimon * 2)
'downdelay': '200',
# lacp_rate 0: Slow - every 30 seconds
# lacp_rate 1: Fast - every 1 second
'lacp_rate': '0',
# Max bonds for this driver
'max_bonds': '1',
# Specifies the time, in milliseconds, to wait before
# enabling a slave after a link recovery has been
# detected. Only used with miimon.
'updelay': '0',
# Used with miimon.
# On: driver sends mii
# Off: ethtool sends mii
'use_carrier': 'on',
# Default. Don't change unless you know what you are doing.
'xmit_hash_policy': 'layer2',
}
if opts['mode'] in ['balance-rr', '0']:
log.info('Device: %s Bonding Mode: load balancing (round-robin)', iface)
return _parse_settings_bond_0(opts, iface, bond_def)
elif opts['mode'] in ['active-backup', '1']:
log.info('Device: %s Bonding Mode: fault-tolerance (active-backup)', iface)
return _parse_settings_bond_1(opts, iface, bond_def)
elif opts['mode'] in ['balance-xor', '2']:
log.info('Device: %s Bonding Mode: load balancing (xor)', iface)
return _parse_settings_bond_2(opts, iface, bond_def)
elif opts['mode'] in ['broadcast', '3']:
log.info('Device: %s Bonding Mode: fault-tolerance (broadcast)', iface)
return _parse_settings_bond_3(opts, iface, bond_def)
elif opts['mode'] in ['802.3ad', '4']:
log.info('Device: %s Bonding Mode: IEEE 802.3ad Dynamic link '
'aggregation', iface)
return _parse_settings_bond_4(opts, iface, bond_def)
elif opts['mode'] in ['balance-tlb', '5']:
log.info('Device: %s Bonding Mode: transmit load balancing', iface)
return _parse_settings_bond_5(opts, iface, bond_def)
elif opts['mode'] in ['balance-alb', '6']:
log.info('Device: %s Bonding Mode: adaptive load balancing', iface)
return _parse_settings_bond_6(opts, iface, bond_def)
else:
valid = [
'0', '1', '2', '3', '4', '5', '6',
'balance-rr', 'active-backup', 'balance-xor',
'broadcast', '802.3ad', 'balance-tlb', 'balance-alb'
]
_raise_error_iface(iface, 'mode', valid)
def _parse_settings_bond_0(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond0.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '0'}
# ARP targets in n.n.n.n form
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
return bond
def _parse_settings_bond_1(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '1'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
if not (__grains__['os'] == "Ubuntu" and __grains__['osrelease_info'][0] >= 16):
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_2(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond2.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '2'}
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_3(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond3.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '3'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_4(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond4.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '4'}
for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']:
if binding in opts:
if binding == 'lacp_rate':
if opts[binding] == 'fast':
opts.update({binding: '1'})
if opts[binding] == 'slow':
opts.update({binding: '0'})
valid = ['fast', '1', 'slow', '0']
else:
valid = ['integer']
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, valid)
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_5(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond5.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '5'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_settings_bond_6(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond6.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '6'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_bridge_opts(opts, iface):
'''
Filters given options and outputs valid settings for BRIDGING_OPTS
If an option has a value that is not expected, this
function will log the Interface, Setting and what was expected.
'''
config = {}
if 'ports' in opts:
if isinstance(opts['ports'], list):
opts['ports'] = ' '.join(opts['ports'])
config.update({'ports': opts['ports']})
for opt in ['ageing', 'fd', 'gcint', 'hello', 'maxage']:
if opt in opts:
try:
float(opts[opt])
config.update({opt: opts[opt]})
except ValueError:
_raise_error_iface(iface, opt, ['float'])
for opt in ['bridgeprio', 'maxwait']:
if opt in opts:
if isinstance(opts[opt], int):
config.update({opt: opts[opt]})
else:
_raise_error_iface(iface, opt, ['integer'])
if 'hw' in opts:
# match 12 hex digits with either : or - as separators between pairs
if re.match('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$',
opts['hw'].lower()):
config.update({'hw': opts['hw']})
else:
_raise_error_iface(iface, 'hw', ['valid MAC address'])
for opt in ['pathcost', 'portprio']:
if opt in opts:
try:
port, cost_or_prio = opts[opt].split()
int(cost_or_prio)
config.update({opt: '{0} {1}'.format(port, cost_or_prio)})
except ValueError:
_raise_error_iface(iface, opt, ['interface integer'])
if 'stp' in opts:
if opts['stp'] in _CONFIG_TRUE:
config.update({'stp': 'on'})
elif opts['stp'] in _CONFIG_FALSE:
config.update({'stp': 'off'})
else:
_raise_error_iface(iface, 'stp', _CONFIG_TRUE + _CONFIG_FALSE)
if 'waitport' in opts:
if isinstance(opts['waitport'], int):
config.update({'waitport': opts['waitport']})
else:
values = opts['waitport'].split()
waitport_time = values.pop(0)
if waitport_time.isdigit() and values:
config.update({
'waitport': '{0} {1}'.format(
waitport_time, ' '.join(values)
)
})
else:
_raise_error_iface(iface, opt, ['integer [interfaces]'])
return config
def _parse_settings_eth(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['inet'] = salt.utils.odict.OrderedDict()
iface_data['inet6'] = salt.utils.odict.OrderedDict()
if enabled:
adapters[iface]['enabled'] = True
if opts.get('hotplug', False):
adapters[iface]['hotplug'] = True
if opts.get('enable_ipv6', None) and opts.get('iface_type', '') == 'vlan':
iface_data['inet6']['vlan_raw_device'] = (
re.sub(r'\.\d*', '', iface))
for addrfam in ['inet', 'inet6']:
if iface_type not in ['bridge']:
tmp_ethtool = _parse_ethtool_opts(opts, iface)
if tmp_ethtool:
ethtool = {}
for item in tmp_ethtool:
ethtool[_ETHTOOL_CONFIG_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['ethtool'] = ethtool
# return a list of sorted keys to ensure consistent order
iface_data[addrfam]['ethtool_keys'] = sorted(ethtool)
if iface_type == 'bridge':
bridging = _parse_bridge_opts(opts, iface)
if bridging:
iface_data[addrfam]['bridging'] = bridging
iface_data[addrfam]['bridging_keys'] = sorted(bridging)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'bond':
bonding = _parse_settings_bond(opts, iface)
if bonding:
iface_data[addrfam]['bonding'] = bonding
iface_data[addrfam]['bonding']['slaves'] = opts['slaves']
iface_data[addrfam]['bonding_keys'] = sorted(bonding)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'slave':
adapters[iface]['master'] = opts['master']
opts['proto'] = 'manual'
iface_data[addrfam]['master'] = adapters[iface]['master']
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'vlan':
iface_data[addrfam]['vlan_raw_device'] = re.sub(r'\.\d*', '', iface)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'pppoe':
tmp_ethtool = _parse_ethtool_pppoe_opts(opts, iface)
if tmp_ethtool:
for item in tmp_ethtool:
adapters[iface]['data'][addrfam][_DEB_CONFIG_PPPOE_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['addrfam'] = addrfam
opts.pop('mode', None)
for opt, val in opts.items():
inet = None
if opt.startswith('ipv4'):
opt = opt[4:]
inet = 'inet'
iface_data['inet']['addrfam'] = 'inet'
elif opt.startswith('ipv6'):
iface_data['inet6']['addrfam'] = 'inet6'
opt = opt[4:]
inet = 'inet6'
elif opt in ['ipaddr', 'address', 'ipaddresses', 'addresses', 'gateway', 'proto']:
iface_data['inet']['addrfam'] = 'inet'
inet = 'inet'
_opt = SALT_ATTR_TO_DEBIAN_ATTR_MAP.get(opt, opt)
_debopt = _opt.replace('-', '_')
for addrfam in ['inet', 'inet6']:
(valid, value, errmsg) = _validate_interface_option(_opt, val, addrfam=addrfam)
if not valid:
continue
if inet is None and _debopt not in iface_data[addrfam]:
iface_data[addrfam][_debopt] = value
elif inet == addrfam:
iface_data[addrfam][_debopt] = value
for opt in ['up_cmds', 'pre_up_cmds', 'post_up_cmds',
'down_cmds', 'pre_down_cmds', 'post_down_cmds']:
if opt in opts:
iface_data['inet'][opt] = opts[opt]
iface_data['inet6'][opt] = opts[opt]
# Remove incomplete/disabled inet blocks
for (addrfam, opt) in [('inet', 'enable_ipv4'), ('inet6', 'enable_ipv6')]:
if opts.get(opt, None) is False:
iface_data.pop(addrfam)
elif iface_data[addrfam].get('addrfam', '') != addrfam:
iface_data.pop(addrfam)
return adapters
def _parse_settings_source(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['sources'] = [opts['source']]
return adapters
def _parse_network_settings(opts, current):
'''
Filters given options and outputs valid settings for
the global network settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
current = dict((k.lower(), v) for (k, v) in six.iteritems(current))
result = {}
valid = _CONFIG_TRUE + _CONFIG_FALSE
if 'enabled' not in opts:
try:
opts['networking'] = current['networking']
_log_default_network('networking', current['networking'])
except ValueError:
_raise_error_network('networking', valid)
else:
opts['networking'] = opts['enabled']
if opts['networking'] in valid:
if opts['networking'] in _CONFIG_TRUE:
result['networking'] = 'yes'
elif opts['networking'] in _CONFIG_FALSE:
result['networking'] = 'no'
else:
_raise_error_network('networking', valid)
if 'hostname' not in opts:
try:
opts['hostname'] = current['hostname']
_log_default_network('hostname', current['hostname'])
except ValueError:
_raise_error_network('hostname', ['server1.example.com'])
if opts['hostname']:
result['hostname'] = opts['hostname']
else:
_raise_error_network('hostname', ['server1.example.com'])
if 'search' in opts:
result['search'] = opts['search']
return result
def _parse_routes(iface, opts):
'''
Filters given options and outputs valid settings for
the route settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
result = {}
if 'routes' not in opts:
_raise_error_routes(iface, 'routes', 'List of routes')
for opt in opts:
result[opt] = opts[opt]
return result
def _write_file(iface, data, folder, pattern):
'''
Writes a file to disk
'''
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
return filename
def _write_file_routes(iface, data, folder, pattern):
'''
Writes a file to disk
'''
# ifup / ifdown is executing given folder via run-parts.
# according to run-parts man-page, only filenames with this pattern are
# executed: (^[a-zA-Z0-9_-]+$)
# In order to make the routes file work for vlan interfaces
# (default would have been in example /etc/network/if-up.d/route-bond0.12)
# these dots in the iface name need to be replaced by underscores, so it
# can be executed by run-parts
iface = iface.replace('.', '_')
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
__salt__['file.set_mode'](filename, '0755')
return filename
def _write_file_network(data, filename, create=False):
'''
Writes a file to disk
If file does not exist, only create if create
argument is True
'''
if not os.path.exists(filename) and not create:
msg = '{0} cannot be written. {0} does not exist\
and create is set to False'
msg = msg.format(filename)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
def _read_temp(data):
'''
Return what would be written to disk
'''
tout = StringIO()
tout.write(data)
tout.seek(0)
output = tout.readlines()
tout.close()
return output
def _read_temp_ifaces(iface, data):
'''
Return what would be written to disk for interfaces
'''
try:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': data})
# Return as an array so the difflib works
return [item + '\n' for item in ifcfg.split('\n')]
def _write_file_ifaces(iface, data, **settings):
'''
Writes a file to disk
'''
try:
eth_template = JINJA.get_template('debian_eth.jinja')
source_template = JINJA.get_template('debian_source.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
# Read /etc/network/interfaces into a dict
adapters = _parse_interfaces()
# Apply supplied settings over on-disk settings
adapters[iface] = data
ifcfg = ''
for adapter in adapters:
if 'type' in adapters[adapter] and adapters[adapter]['type'] == 'source':
tmp = source_template.render({'name': adapter, 'data': adapters[adapter]})
else:
tmp = eth_template.render({'name': adapter, 'data': adapters[adapter]})
ifcfg = ifcfg + tmp
if adapter == iface:
saved_ifcfg = tmp
_SEPARATE_FILE = False
if 'filename' in settings:
if not settings['filename'].startswith('/'):
filename = '{0}/{1}'.format(_DEB_NETWORK_DIR, settings['filename'])
else:
filename = settings['filename']
_SEPARATE_FILE = True
else:
if 'filename' in adapters[adapter]['data']:
filename = adapters[adapter]['data']
else:
filename = _DEB_NETWORK_FILE
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
if _SEPARATE_FILE:
fout.write(salt.utils.stringutils.to_str(saved_ifcfg))
else:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return saved_ifcfg.split('\n')
def build_bond(iface, **settings):
'''
Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb
'''
deb_major = __grains__['osrelease'][:1]
opts = _parse_settings_bond(settings, iface)
try:
template = JINJA.get_template('conf.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template conf.jinja')
return ''
data = template.render({'name': iface, 'bonding': opts})
if 'test' in settings and settings['test']:
return _read_temp(data)
_write_file(iface, data, _DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
if deb_major == '5':
for line_type in ('alias', 'options'):
cmd = ['sed', '-i', '-e', r'/^{0}\s{1}.*/d'.format(line_type, iface),
'/etc/modprobe.conf']
__salt__['cmd.run'](cmd, python_shell=False)
__salt__['file.append']('/etc/modprobe.conf', path)
# Load kernel module
__salt__['kmod.load']('bonding')
# install ifenslave-2.6
__salt__['pkg.install']('ifenslave-2.6')
return _read_file(path)
def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'vlan':
settings['vlan'] = 'yes'
__salt__['pkg.install']('vlan')
elif iface_type == 'pppoe':
settings['pppoe'] = 'yes'
if not __salt__['pkg.version']('ppp'):
inst = __salt__['pkg.install']('ppp')
elif iface_type == 'bond':
if 'slaves' not in settings:
msg = 'slaves is a required setting for bond interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'bridge':
if 'ports' not in settings:
msg = (
'ports is a required setting for bridge interfaces on Debian '
'or Ubuntu based systems'
)
log.error(msg)
raise AttributeError(msg)
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'pppoe']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
if iface_type in ['source']:
opts = _parse_settings_source(settings, iface_type, enabled, iface)
if 'test' in settings and settings['test']:
return _read_temp_ifaces(iface, opts[iface])
ifcfg = _write_file_ifaces(iface, opts[iface], **settings)
if iface_type == 'pppoe':
_write_file_ppp_ifaces(iface, opts[iface])
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg]
def build_routes(iface, **settings):
'''
Add route scripts for a network interface using up commands.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
'''
opts = _parse_routes(iface, settings)
try:
template = JINJA.get_template('route_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template route_eth.jinja')
return ''
add_routecfg = template.render(route_type='add',
routes=opts['routes'],
iface=iface)
del_routecfg = template.render(route_type='del',
routes=opts['routes'],
iface=iface)
if 'test' in settings and settings['test']:
return _read_temp(add_routecfg + del_routecfg)
filename = _write_file_routes(iface,
add_routecfg,
_DEB_NETWORK_UP_DIR,
'route-{0}')
results = _read_file(filename)
filename = _write_file_routes(iface,
del_routecfg,
_DEB_NETWORK_DOWN_DIR,
'route-{0}')
results += _read_file(filename)
return results
def down(iface, iface_type):
'''
Shutdown a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.down eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought down.
if iface_type not in ['slave', 'source']:
return __salt__['cmd.run'](['ifdown', iface])
return None
def get_bond(iface):
'''
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
'''
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
return _read_file(path)
def get_interface(iface):
'''
Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
adapters = _parse_interfaces()
if iface in adapters:
try:
if iface == 'source':
template = JINJA.get_template('debian_source.jinja')
else:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': adapters[iface]})
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg.split('\n')]
else:
return []
def up(iface, iface_type): # pylint: disable=C0103
'''
Start up a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.up eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought up.
if iface_type not in ('slave', 'source'):
return __salt__['cmd.run'](['ifup', iface])
return None
def get_network_settings():
'''
Return the contents of the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_network_settings
'''
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
settings = {}
if __salt__['service.available']('networking'):
if __salt__['service.status']('networking'):
settings['networking'] = "yes"
else:
settings['networking'] = "no"
else:
settings['networking'] = "no"
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
settings['hostname'] = hostname
settings['domainname'] = domainname
settings['searchdomain'] = searchdomain
else:
settings = _parse_current_network_settings()
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(settings)
return _read_temp(network)
def get_routes(iface):
'''
Return the routes for the interface
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0
'''
filename = os.path.join(_DEB_NETWORK_UP_DIR, 'route-{0}'.format(iface))
results = _read_file(filename)
filename = os.path.join(_DEB_NETWORK_DOWN_DIR, 'route-{0}'.format(iface))
results += _read_file(filename)
return results
def apply_network_settings(**settings):
'''
Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings
'''
if 'require_reboot' not in settings:
settings['require_reboot'] = False
if 'apply_hostname' not in settings:
settings['apply_hostname'] = False
hostname_res = True
if settings['apply_hostname'] in _CONFIG_TRUE:
if 'hostname' in settings:
hostname_res = __salt__['network.mod_hostname'](settings['hostname'])
else:
log.warning(
'The network state sls is trying to apply hostname '
'changes but no hostname is defined.'
)
hostname_res = False
res = True
if settings['require_reboot'] in _CONFIG_TRUE:
log.warning(
'The network state sls is requiring a reboot of the system to '
'properly apply network configuration.'
)
res = True
else:
stop = __salt__['service.stop']('networking')
time.sleep(2)
res = stop and __salt__['service.start']('networking')
return hostname_res and res
def build_network_settings(**settings):
'''
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
'''
changes = []
# Read current configuration and store default values
current_network_settings = _parse_current_network_settings()
# Build settings
opts = _parse_network_settings(settings, current_network_settings)
# Ubuntu has moved away from /etc/default/networking
# beginning with the 12.04 release so we disable or enable
# the networking related services on boot
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
if opts['networking'] == 'yes':
service_cmd = 'service.enable'
else:
service_cmd = 'service.disable'
if __salt__['service.available']('NetworkManager'):
__salt__[service_cmd]('NetworkManager')
if __salt__['service.available']('networking'):
__salt__[service_cmd]('networking')
else:
try:
template = JINJA.get_template('network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template network.jinja')
return ''
network = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(network)
# Write settings
_write_file_network(network, _DEB_NETWORKING_FILE, True)
# Get hostname and domain from opts
sline = opts['hostname'].split('.', 1)
opts['hostname'] = sline[0]
current_domainname = current_network_settings['domainname']
current_searchdomain = current_network_settings['searchdomain']
new_domain = False
if len(sline) > 1:
new_domainname = sline[1]
if new_domainname != current_domainname:
domainname = new_domainname
opts['domainname'] = new_domainname
new_domain = True
else:
domainname = current_domainname
opts['domainname'] = domainname
else:
domainname = current_domainname
opts['domainname'] = domainname
new_search = False
if 'search' in opts:
new_searchdomain = opts['search']
if new_searchdomain != current_searchdomain:
searchdomain = new_searchdomain
opts['searchdomain'] = new_searchdomain
new_search = True
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
# If the domain changes, then we should write the resolv.conf file.
if new_domain or new_search:
# Look for existing domain line and update if necessary
resolve = _parse_resolve()
domain_prog = re.compile(r'domain\s+')
search_prog = re.compile(r'search\s+')
new_contents = []
for item in _read_file(_DEB_RESOLV_FILE):
if domain_prog.match(item):
item = 'domain {0}'.format(domainname)
elif search_prog.match(item):
item = 'search {0}'.format(searchdomain)
new_contents.append(item)
# A domain line didn't exist so we'll add one in
# with the new domainname
if 'domain' not in resolve:
new_contents.insert(0, 'domain {0}' . format(domainname))
# A search line didn't exist so we'll add one in
# with the new search domain
if 'search' not in resolve:
new_contents.insert('domain' in resolve, 'search {0}'.format(searchdomain))
new_resolv = '\n'.join(new_contents)
# Write /etc/resolv.conf
if not ('test' in settings and settings['test']):
_write_file_network(new_resolv, _DEB_RESOLV_FILE)
# used for returning the results back
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(opts)
changes.extend(_read_temp(network))
return changes
|
saltstack/salt
|
salt/modules/debian_ip.py
|
build_bond
|
python
|
def build_bond(iface, **settings):
'''
Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb
'''
deb_major = __grains__['osrelease'][:1]
opts = _parse_settings_bond(settings, iface)
try:
template = JINJA.get_template('conf.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template conf.jinja')
return ''
data = template.render({'name': iface, 'bonding': opts})
if 'test' in settings and settings['test']:
return _read_temp(data)
_write_file(iface, data, _DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
if deb_major == '5':
for line_type in ('alias', 'options'):
cmd = ['sed', '-i', '-e', r'/^{0}\s{1}.*/d'.format(line_type, iface),
'/etc/modprobe.conf']
__salt__['cmd.run'](cmd, python_shell=False)
__salt__['file.append']('/etc/modprobe.conf', path)
# Load kernel module
__salt__['kmod.load']('bonding')
# install ifenslave-2.6
__salt__['pkg.install']('ifenslave-2.6')
return _read_file(path)
|
Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_ip.py#L1565-L1604
|
[
"def _read_file(path):\n '''\n Reads and returns the contents of a text file\n '''\n try:\n with salt.utils.files.flopen(path, 'rb') as contents:\n return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]\n except (OSError, IOError):\n return ''\n",
"def _parse_settings_bond(opts, iface):\n '''\n Filters given options and outputs valid settings for requested\n operation. If an option has a value that is not expected, this\n function will log what the Interface, Setting and what it was\n expecting.\n '''\n\n bond_def = {\n # 803.ad aggregation selection logic\n # 0 for stable (default)\n # 1 for bandwidth\n # 2 for count\n 'ad_select': '0',\n # Max number of transmit queues (default = 16)\n 'tx_queues': '16',\n # Link monitoring in milliseconds. Most NICs support this\n 'miimon': '100',\n # ARP interval in milliseconds\n 'arp_interval': '250',\n # Delay before considering link down in milliseconds (miimon * 2)\n 'downdelay': '200',\n # lacp_rate 0: Slow - every 30 seconds\n # lacp_rate 1: Fast - every 1 second\n 'lacp_rate': '0',\n # Max bonds for this driver\n 'max_bonds': '1',\n # Specifies the time, in milliseconds, to wait before\n # enabling a slave after a link recovery has been\n # detected. Only used with miimon.\n 'updelay': '0',\n # Used with miimon.\n # On: driver sends mii\n # Off: ethtool sends mii\n 'use_carrier': 'on',\n # Default. Don't change unless you know what you are doing.\n 'xmit_hash_policy': 'layer2',\n }\n\n if opts['mode'] in ['balance-rr', '0']:\n log.info('Device: %s Bonding Mode: load balancing (round-robin)', iface)\n return _parse_settings_bond_0(opts, iface, bond_def)\n elif opts['mode'] in ['active-backup', '1']:\n log.info('Device: %s Bonding Mode: fault-tolerance (active-backup)', iface)\n return _parse_settings_bond_1(opts, iface, bond_def)\n elif opts['mode'] in ['balance-xor', '2']:\n log.info('Device: %s Bonding Mode: load balancing (xor)', iface)\n return _parse_settings_bond_2(opts, iface, bond_def)\n elif opts['mode'] in ['broadcast', '3']:\n log.info('Device: %s Bonding Mode: fault-tolerance (broadcast)', iface)\n return _parse_settings_bond_3(opts, iface, bond_def)\n elif opts['mode'] in ['802.3ad', '4']:\n log.info('Device: %s Bonding Mode: IEEE 802.3ad Dynamic link '\n 'aggregation', iface)\n return _parse_settings_bond_4(opts, iface, bond_def)\n elif opts['mode'] in ['balance-tlb', '5']:\n log.info('Device: %s Bonding Mode: transmit load balancing', iface)\n return _parse_settings_bond_5(opts, iface, bond_def)\n elif opts['mode'] in ['balance-alb', '6']:\n log.info('Device: %s Bonding Mode: adaptive load balancing', iface)\n return _parse_settings_bond_6(opts, iface, bond_def)\n else:\n valid = [\n '0', '1', '2', '3', '4', '5', '6',\n 'balance-rr', 'active-backup', 'balance-xor',\n 'broadcast', '802.3ad', 'balance-tlb', 'balance-alb'\n ]\n _raise_error_iface(iface, 'mode', valid)\n",
"def _write_file(iface, data, folder, pattern):\n '''\n Writes a file to disk\n '''\n filename = os.path.join(folder, pattern.format(iface))\n if not os.path.exists(folder):\n msg = '{0} cannot be written. {1} does not exist'\n msg = msg.format(filename, folder)\n log.error(msg)\n raise AttributeError(msg)\n with salt.utils.files.flopen(filename, 'w') as fout:\n fout.write(salt.utils.stringutils.to_str(data))\n return filename\n",
"def _read_temp(data):\n '''\n Return what would be written to disk\n '''\n tout = StringIO()\n tout.write(data)\n tout.seek(0)\n output = tout.readlines()\n tout.close()\n\n return output\n"
] |
# -*- coding: utf-8 -*-
'''
The networking module for Debian-based distros
References:
* http://www.debian.org/doc/manuals/debian-reference/ch05.en.html
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import functools
import logging
import os.path
import os
import re
import time
# Import third party libs
import jinja2
import jinja2.exceptions
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error,no-name-in-module
# Import salt libs
import salt.utils.dns
import salt.utils.files
import salt.utils.odict
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.validate.net
# Set up logging
log = logging.getLogger(__name__)
# Set up template environment
JINJA = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'debian_ip')
)
)
# Define the module's virtual name
__virtualname__ = 'ip'
def __virtual__():
'''
Confine this module to Debian-based distros
'''
if __grains__['os_family'] == 'Debian':
return __virtualname__
return (False, 'The debian_ip module could not be loaded: '
'unsupported OS family')
_ETHTOOL_CONFIG_OPTS = {
'speed': 'link-speed',
'duplex': 'link-duplex',
'autoneg': 'ethernet-autoneg',
'ethernet-port': 'ethernet-port',
'wol': 'ethernet-wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'rx': 'offload-rx',
'tx': 'offload-tx',
'sg': 'offload-sg',
'tso': 'offload-tso',
'ufo': 'offload-ufo',
'gso': 'offload-gso',
'gro': 'offload-gro',
'lro': 'offload-lro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_REV_ETHTOOL_CONFIG_OPTS = {
'link-speed': 'speed',
'link-duplex': 'duplex',
'ethernet-autoneg': 'autoneg',
'ethernet-port': 'ethernet-port',
'ethernet-wol': 'wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'offload-rx': 'rx',
'offload-tx': 'tx',
'offload-sg': 'sg',
'offload-tso': 'tso',
'offload-ufo': 'ufo',
'offload-gso': 'gso',
'offload-lro': 'lro',
'offload-gro': 'gro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_DEB_CONFIG_PPPOE_OPTS = {
'user': 'user',
'password': 'password',
'provider': 'provider',
'pppoe_iface': 'pppoe_iface',
'noipdefault': 'noipdefault',
'usepeerdns': 'usepeerdns',
'defaultroute': 'defaultroute',
'holdoff': 'holdoff',
'maxfail': 'maxfail',
'hide-password': 'hide-password',
'lcp-echo-interval': 'lcp-echo-interval',
'lcp-echo-failure': 'lcp-echo-failure',
'connect': 'connect',
'noauth': 'noauth',
'persist': 'persist',
'mtu': 'mtu',
'noaccomp': 'noaccomp',
'linkname': 'linkname',
}
_DEB_ROUTES_FILE = '/etc/network/routes'
_DEB_NETWORK_FILE = '/etc/network/interfaces'
_DEB_NETWORK_DIR = '/etc/network/interfaces.d/'
_DEB_NETWORK_UP_DIR = '/etc/network/if-up.d/'
_DEB_NETWORK_DOWN_DIR = '/etc/network/if-down.d/'
_DEB_NETWORK_CONF_FILES = '/etc/modprobe.d/'
_DEB_NETWORKING_FILE = '/etc/default/networking'
_DEB_HOSTNAME_FILE = '/etc/hostname'
_DEB_RESOLV_FILE = '/etc/resolv.conf'
_DEB_PPP_DIR = '/etc/ppp/peers/'
_CONFIG_TRUE = ['yes', 'on', 'true', '1', True]
_CONFIG_FALSE = ['no', 'off', 'false', '0', False]
_IFACE_TYPES = [
'eth', 'bond', 'alias', 'clone',
'ipsec', 'dialup', 'bridge', 'slave',
'vlan', 'pppoe', 'source',
]
def _error_msg_iface(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, '|'.join(str(e) for e in expected))
def _error_msg_routes(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, expected)
def _log_default_iface(iface, opt, value):
log.info(
'Using default option -- Interface: %s Option: %s Value: %s',
iface, opt, value
)
def _error_msg_network(option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]'
return msg.format(option, '|'.join(str(e) for e in expected))
def _log_default_network(opt, value):
log.info('Using existing setting -- Setting: %s Value: %s', opt, value)
def _raise_error_iface(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_iface(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_network(option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_network(option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_routes(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_routes(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _read_file(path):
'''
Reads and returns the contents of a text file
'''
try:
with salt.utils.files.flopen(path, 'rb') as contents:
return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]
except (OSError, IOError):
return ''
def _parse_resolve():
'''
Parse /etc/resolv.conf
'''
return salt.utils.dns.parse_resolv(_DEB_RESOLV_FILE)
def _parse_domainname():
'''
Parse /etc/resolv.conf and return domainname
'''
return _parse_resolve().get('domain', '')
def _parse_searchdomain():
'''
Parse /etc/resolv.conf and return searchdomain
'''
return _parse_resolve().get('search', '')
def _parse_hostname():
'''
Parse /etc/hostname and return hostname
'''
contents = _read_file(_DEB_HOSTNAME_FILE)
if contents:
return contents[0].split('\n')[0]
else:
return ''
def _parse_current_network_settings():
'''
Parse /etc/default/networking and return current configuration
'''
opts = salt.utils.odict.OrderedDict()
opts['networking'] = ''
if os.path.isfile(_DEB_NETWORKING_FILE):
with salt.utils.files.fopen(_DEB_NETWORKING_FILE) as contents:
for line in contents:
salt.utils.stringutils.to_unicode(line)
if line.startswith('#'):
continue
elif line.startswith('CONFIGURE_INTERFACES'):
opts['networking'] = line.split('=', 1)[1].strip()
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
opts['hostname'] = hostname
opts['domainname'] = domainname
opts['searchdomain'] = searchdomain
return opts
# def __validator_func(value):
# return (valid: True/False, (transformed) value, error message)
def __ipv4_quad(value):
'''validate an IPv4 address'''
return (salt.utils.validate.net.ipv4_addr(value), value,
'dotted IPv4 address')
def __ipv6(value):
'''validate an IPv6 address'''
return (salt.utils.validate.net.ipv6_addr(value), value,
'IPv6 address')
def __mac(value):
'''validate a mac address'''
return (salt.utils.validate.net.mac(value), value,
'MAC address')
def __anything(value):
return (True, value, None)
def __int(value):
'''validate an integer'''
valid, _value = False, value
try:
_value = int(value)
valid = True
except ValueError:
pass
return (valid, _value, 'integer')
def __float(value):
'''validate a float'''
valid, _value = False, value
try:
_value = float(value)
valid = True
except ValueError:
pass
return (valid, _value, 'float')
def __ipv4_netmask(value):
'''validate an IPv4 dotted quad or integer CIDR netmask'''
valid, errmsg = False, 'dotted quad or integer CIDR (0->32)'
valid, value, _ = __int(value)
if not (valid and 0 <= value <= 32):
valid = salt.utils.validate.net.netmask(value)
return (valid, value, errmsg)
def __ipv6_netmask(value):
'''validate an IPv6 integer netmask'''
valid, errmsg = False, 'IPv6 netmask (0->128)'
valid, value, _ = __int(value)
valid = (valid and 0 <= value <= 128)
return (valid, value, errmsg)
def __within2(value, within=None, errmsg=None, dtype=None):
'''validate that a value is in ``within`` and optionally a ``dtype``'''
valid, _value = False, value
if dtype:
try:
_value = dtype(value) # TODO: this is a bit loose when dtype is a class
valid = _value in within
except ValueError:
pass
else:
valid = _value in within
if errmsg is None:
if dtype:
typename = getattr(dtype, '__name__',
hasattr(dtype, '__class__')
and getattr(dtype.__class__, 'name', dtype))
errmsg = '{0} within \'{1}\''.format(typename, within)
else:
errmsg = 'within \'{0}\''.format(within)
return (valid, _value, errmsg)
def __within(within=None, errmsg=None, dtype=None):
return functools.partial(__within2, within=within,
errmsg=errmsg, dtype=dtype)
def __space_delimited_list(value):
'''validate that a value contains one or more space-delimited values'''
if isinstance(value, six.string_types):
value = value.strip().split()
if hasattr(value, '__iter__') and value != []:
return (True, value, 'space-delimited string')
else:
return (False, value, '{0} is not a valid space-delimited value.\n'.format(value))
SALT_ATTR_TO_DEBIAN_ATTR_MAP = {
'dns': 'dns-nameservers',
'search': 'dns-search',
'hwaddr': 'hwaddress', # TODO: this limits bootp functionality
'ipaddr': 'address',
'ipaddrs': 'addresses',
}
DEBIAN_ATTR_TO_SALT_ATTR_MAP = dict(
(v, k) for (k, v) in six.iteritems(SALT_ATTR_TO_DEBIAN_ATTR_MAP))
# TODO
DEBIAN_ATTR_TO_SALT_ATTR_MAP['address'] = 'address'
DEBIAN_ATTR_TO_SALT_ATTR_MAP['hwaddress'] = 'hwaddress'
IPV4_VALID_PROTO = ['bootp', 'dhcp', 'static', 'manual', 'loopback', 'ppp']
IPV4_ATTR_MAP = {
'proto': __within(IPV4_VALID_PROTO, dtype=six.text_type),
# ipv4 static & manual
'address': __ipv4_quad,
'addresses': __anything,
'netmask': __ipv4_netmask,
'broadcast': __ipv4_quad,
'metric': __int,
'gateway': __ipv4_quad, # supports a colon-delimited list
'pointopoint': __ipv4_quad,
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'link', 'host'], dtype=six.text_type),
# dhcp
'hostname': __anything,
'leasehours': __int,
'leasetime': __int,
'vendor': __anything,
'client': __anything,
# bootp
'bootfile': __anything,
'server': __ipv4_quad,
'hwaddr': __mac,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'dstaddr': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# bond
'slaves': __anything,
# ppp
'provider': __anything,
'unit': __int,
'options': __anything,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
#
'network': __anything, # i don't know what this is
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
IPV6_VALID_PROTO = ['auto', 'loopback', 'static', 'manual',
'dhcp', 'v4tunnel', '6to4']
IPV6_ATTR_MAP = {
'proto': __within(IPV6_VALID_PROTO),
# ipv6 static & manual
'address': __ipv6,
'addresses': __anything,
'netmask': __ipv6_netmask,
'broadcast': __ipv6,
'gateway': __ipv6, # supports a colon-delimited list
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'site', 'link', 'host'], dtype=six.text_type),
# inet6 auto
'privext': __within([0, 1, 2], dtype=int),
'dhcp': __within([0, 1], dtype=int),
# inet6 static & manual & dhcp
'media': __anything,
'accept_ra': __within([0, 1], dtype=int),
'autoconf': __within([0, 1], dtype=int),
'preferred-lifetime': __int,
'dad-attempts': __int, # 0 to disable
'dad-interval': __float,
# bond
'slaves': __anything,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
WIRELESS_ATTR_MAP = {
'wireless-essid': __anything,
'wireless-mode': __anything, # TODO
'wpa-ap-scan': __within([0, 1, 2], dtype=int), # TODO
'wpa-conf': __anything,
'wpa-driver': __anything,
'wpa-group': __anything,
'wpa-key-mgmt': __anything,
'wpa-pairwise': __anything,
'wpa-psk': __anything,
'wpa-proto': __anything, # partial(__within,
'wpa-roam': __anything,
'wpa-ssid': __anything, # TODO
}
ATTRMAPS = {
'inet': [IPV4_ATTR_MAP, WIRELESS_ATTR_MAP],
'inet6': [IPV6_ATTR_MAP, WIRELESS_ATTR_MAP]
}
def _validate_interface_option(attr, value, addrfam='inet'):
'''lookup the validation function for a [addrfam][attr] and
return the results
:param attr: attribute name
:param value: raw setting value
:param addrfam: address family (inet, inet6,
'''
valid, _value, errmsg = False, value, 'Unknown validator'
attrmaps = ATTRMAPS.get(addrfam, [])
for attrmap in attrmaps:
if attr in attrmap:
validate_func = attrmap[attr]
(valid, _value, errmsg) = validate_func(value)
break
return (valid, _value, errmsg)
def _attrmaps_contain_attr(attr):
return (
attr in WIRELESS_ATTR_MAP or
attr in IPV4_ATTR_MAP or
attr in IPV6_ATTR_MAP)
def _parse_interfaces(interface_files=None):
'''
Parse /etc/network/interfaces and return current configured interfaces
'''
if interface_files is None:
interface_files = []
# Add this later.
if os.path.exists(_DEB_NETWORK_DIR):
interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]
if os.path.isfile(_DEB_NETWORK_FILE):
interface_files.insert(0, _DEB_NETWORK_FILE)
adapters = salt.utils.odict.OrderedDict()
method = -1
for interface_file in interface_files:
with salt.utils.files.fopen(interface_file) as interfaces:
# This ensures iface_dict exists, but does not ensure we're not reading a new interface.
iface_dict = {}
for line in interfaces:
line = salt.utils.stringutils.to_unicode(line)
# Identify the clauses by the first word of each line.
# Go to the next line if the current line is a comment
# or all spaces.
if line.lstrip().startswith('#') or line.isspace():
continue
# Parse the iface clause
if line.startswith('iface'):
sline = line.split()
if len(sline) != 4:
msg = 'Interface file malformed: {0}.'
msg = msg.format(sline)
log.error(msg)
raise AttributeError(msg)
iface_name = sline[1]
addrfam = sline[2]
method = sline[3]
# Create item in dict, if not already there
if iface_name not in adapters:
adapters[iface_name] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters[iface_name]:
adapters[iface_name]['data'] = salt.utils.odict.OrderedDict()
if addrfam not in adapters[iface_name]['data']:
adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict()
iface_dict = adapters[iface_name]['data'][addrfam]
iface_dict['addrfam'] = addrfam
iface_dict['proto'] = method
iface_dict['filename'] = interface_file
# Parse the detail clauses.
elif line[0].isspace():
sline = line.split()
# conf file attr: dns-nameservers
# salt states.network attr: dns
attr, valuestr = line.rstrip().split(None, 1)
if _attrmaps_contain_attr(attr):
if '-' in attr:
attrname = attr.replace('-', '_')
else:
attrname = attr
(valid, value, errmsg) = _validate_interface_option(
attr, valuestr, addrfam)
if attrname == 'address' and 'address' in iface_dict:
if 'addresses' not in iface_dict:
iface_dict['addresses'] = []
iface_dict['addresses'].append(value)
else:
iface_dict[attrname] = value
elif attr in _REV_ETHTOOL_CONFIG_OPTS:
if 'ethtool' not in iface_dict:
iface_dict['ethtool'] = salt.utils.odict.OrderedDict()
iface_dict['ethtool'][attr] = valuestr
elif attr.startswith('bond'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bonding' not in iface_dict:
iface_dict['bonding'] = salt.utils.odict.OrderedDict()
iface_dict['bonding'][opt] = valuestr
elif attr.startswith('bridge'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bridging' not in iface_dict:
iface_dict['bridging'] = salt.utils.odict.OrderedDict()
iface_dict['bridging'][opt] = valuestr
elif attr in ['up', 'pre-up', 'post-up',
'down', 'pre-down', 'post-down']:
cmd = valuestr
cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr))
if cmd_key not in iface_dict:
iface_dict[cmd_key] = []
iface_dict[cmd_key].append(cmd)
elif line.startswith('auto'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['enabled'] = True
elif line.startswith('allow-hotplug'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['hotplug'] = True
elif line.startswith('source'):
if 'source' not in adapters:
adapters['source'] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters['source']:
adapters['source']['data'] = salt.utils.odict.OrderedDict()
adapters['source']['data']['sources'] = []
adapters['source']['data']['sources'].append(line.split()[1])
# Return a sorted list of the keys for bond, bridge and ethtool options to
# ensure a consistent order
for iface_name in adapters:
if iface_name == 'source':
continue
if 'data' not in adapters[iface_name]:
msg = 'Interface file malformed for interface: {0}.'.format(iface_name)
log.error(msg)
adapters.pop(iface_name)
continue
for opt in ['ethtool', 'bonding', 'bridging']:
for inet in ['inet', 'inet6']:
if inet in adapters[iface_name]['data']:
if opt in adapters[iface_name]['data'][inet]:
opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys())
adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys
return adapters
def _parse_ethtool_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
if 'autoneg' in opts:
if opts['autoneg'] in _CONFIG_TRUE:
config.update({'autoneg': 'on'})
elif opts['autoneg'] in _CONFIG_FALSE:
config.update({'autoneg': 'off'})
else:
_raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE)
if 'duplex' in opts:
valid = ['full', 'half']
if opts['duplex'] in valid:
config.update({'duplex': opts['duplex']})
else:
_raise_error_iface(iface, 'duplex', valid)
if 'speed' in opts:
valid = ['10', '100', '1000', '10000']
if six.text_type(opts['speed']) in valid:
config.update({'speed': opts['speed']})
else:
_raise_error_iface(iface, opts['speed'], valid)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'on'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'off'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_ethtool_pppoe_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
for opt in _DEB_CONFIG_PPPOE_OPTS:
if opt in opts:
config[opt] = opts[opt]
if 'provider' in opts and not opts['provider']:
_raise_error_iface(iface, 'provider', _CONFIG_TRUE + _CONFIG_FALSE)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('noipdefault', 'usepeerdns', 'defaultroute', 'hide-password', 'noauth', 'persist', 'noaccomp'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'True'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'False'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_settings_bond(opts, iface):
'''
Filters given options and outputs valid settings for requested
operation. If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond_def = {
# 803.ad aggregation selection logic
# 0 for stable (default)
# 1 for bandwidth
# 2 for count
'ad_select': '0',
# Max number of transmit queues (default = 16)
'tx_queues': '16',
# Link monitoring in milliseconds. Most NICs support this
'miimon': '100',
# ARP interval in milliseconds
'arp_interval': '250',
# Delay before considering link down in milliseconds (miimon * 2)
'downdelay': '200',
# lacp_rate 0: Slow - every 30 seconds
# lacp_rate 1: Fast - every 1 second
'lacp_rate': '0',
# Max bonds for this driver
'max_bonds': '1',
# Specifies the time, in milliseconds, to wait before
# enabling a slave after a link recovery has been
# detected. Only used with miimon.
'updelay': '0',
# Used with miimon.
# On: driver sends mii
# Off: ethtool sends mii
'use_carrier': 'on',
# Default. Don't change unless you know what you are doing.
'xmit_hash_policy': 'layer2',
}
if opts['mode'] in ['balance-rr', '0']:
log.info('Device: %s Bonding Mode: load balancing (round-robin)', iface)
return _parse_settings_bond_0(opts, iface, bond_def)
elif opts['mode'] in ['active-backup', '1']:
log.info('Device: %s Bonding Mode: fault-tolerance (active-backup)', iface)
return _parse_settings_bond_1(opts, iface, bond_def)
elif opts['mode'] in ['balance-xor', '2']:
log.info('Device: %s Bonding Mode: load balancing (xor)', iface)
return _parse_settings_bond_2(opts, iface, bond_def)
elif opts['mode'] in ['broadcast', '3']:
log.info('Device: %s Bonding Mode: fault-tolerance (broadcast)', iface)
return _parse_settings_bond_3(opts, iface, bond_def)
elif opts['mode'] in ['802.3ad', '4']:
log.info('Device: %s Bonding Mode: IEEE 802.3ad Dynamic link '
'aggregation', iface)
return _parse_settings_bond_4(opts, iface, bond_def)
elif opts['mode'] in ['balance-tlb', '5']:
log.info('Device: %s Bonding Mode: transmit load balancing', iface)
return _parse_settings_bond_5(opts, iface, bond_def)
elif opts['mode'] in ['balance-alb', '6']:
log.info('Device: %s Bonding Mode: adaptive load balancing', iface)
return _parse_settings_bond_6(opts, iface, bond_def)
else:
valid = [
'0', '1', '2', '3', '4', '5', '6',
'balance-rr', 'active-backup', 'balance-xor',
'broadcast', '802.3ad', 'balance-tlb', 'balance-alb'
]
_raise_error_iface(iface, 'mode', valid)
def _parse_settings_bond_0(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond0.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '0'}
# ARP targets in n.n.n.n form
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
return bond
def _parse_settings_bond_1(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '1'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
if not (__grains__['os'] == "Ubuntu" and __grains__['osrelease_info'][0] >= 16):
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_2(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond2.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '2'}
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_3(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond3.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '3'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_4(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond4.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '4'}
for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']:
if binding in opts:
if binding == 'lacp_rate':
if opts[binding] == 'fast':
opts.update({binding: '1'})
if opts[binding] == 'slow':
opts.update({binding: '0'})
valid = ['fast', '1', 'slow', '0']
else:
valid = ['integer']
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, valid)
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_5(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond5.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '5'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_settings_bond_6(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond6.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '6'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_bridge_opts(opts, iface):
'''
Filters given options and outputs valid settings for BRIDGING_OPTS
If an option has a value that is not expected, this
function will log the Interface, Setting and what was expected.
'''
config = {}
if 'ports' in opts:
if isinstance(opts['ports'], list):
opts['ports'] = ' '.join(opts['ports'])
config.update({'ports': opts['ports']})
for opt in ['ageing', 'fd', 'gcint', 'hello', 'maxage']:
if opt in opts:
try:
float(opts[opt])
config.update({opt: opts[opt]})
except ValueError:
_raise_error_iface(iface, opt, ['float'])
for opt in ['bridgeprio', 'maxwait']:
if opt in opts:
if isinstance(opts[opt], int):
config.update({opt: opts[opt]})
else:
_raise_error_iface(iface, opt, ['integer'])
if 'hw' in opts:
# match 12 hex digits with either : or - as separators between pairs
if re.match('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$',
opts['hw'].lower()):
config.update({'hw': opts['hw']})
else:
_raise_error_iface(iface, 'hw', ['valid MAC address'])
for opt in ['pathcost', 'portprio']:
if opt in opts:
try:
port, cost_or_prio = opts[opt].split()
int(cost_or_prio)
config.update({opt: '{0} {1}'.format(port, cost_or_prio)})
except ValueError:
_raise_error_iface(iface, opt, ['interface integer'])
if 'stp' in opts:
if opts['stp'] in _CONFIG_TRUE:
config.update({'stp': 'on'})
elif opts['stp'] in _CONFIG_FALSE:
config.update({'stp': 'off'})
else:
_raise_error_iface(iface, 'stp', _CONFIG_TRUE + _CONFIG_FALSE)
if 'waitport' in opts:
if isinstance(opts['waitport'], int):
config.update({'waitport': opts['waitport']})
else:
values = opts['waitport'].split()
waitport_time = values.pop(0)
if waitport_time.isdigit() and values:
config.update({
'waitport': '{0} {1}'.format(
waitport_time, ' '.join(values)
)
})
else:
_raise_error_iface(iface, opt, ['integer [interfaces]'])
return config
def _parse_settings_eth(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['inet'] = salt.utils.odict.OrderedDict()
iface_data['inet6'] = salt.utils.odict.OrderedDict()
if enabled:
adapters[iface]['enabled'] = True
if opts.get('hotplug', False):
adapters[iface]['hotplug'] = True
if opts.get('enable_ipv6', None) and opts.get('iface_type', '') == 'vlan':
iface_data['inet6']['vlan_raw_device'] = (
re.sub(r'\.\d*', '', iface))
for addrfam in ['inet', 'inet6']:
if iface_type not in ['bridge']:
tmp_ethtool = _parse_ethtool_opts(opts, iface)
if tmp_ethtool:
ethtool = {}
for item in tmp_ethtool:
ethtool[_ETHTOOL_CONFIG_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['ethtool'] = ethtool
# return a list of sorted keys to ensure consistent order
iface_data[addrfam]['ethtool_keys'] = sorted(ethtool)
if iface_type == 'bridge':
bridging = _parse_bridge_opts(opts, iface)
if bridging:
iface_data[addrfam]['bridging'] = bridging
iface_data[addrfam]['bridging_keys'] = sorted(bridging)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'bond':
bonding = _parse_settings_bond(opts, iface)
if bonding:
iface_data[addrfam]['bonding'] = bonding
iface_data[addrfam]['bonding']['slaves'] = opts['slaves']
iface_data[addrfam]['bonding_keys'] = sorted(bonding)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'slave':
adapters[iface]['master'] = opts['master']
opts['proto'] = 'manual'
iface_data[addrfam]['master'] = adapters[iface]['master']
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'vlan':
iface_data[addrfam]['vlan_raw_device'] = re.sub(r'\.\d*', '', iface)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'pppoe':
tmp_ethtool = _parse_ethtool_pppoe_opts(opts, iface)
if tmp_ethtool:
for item in tmp_ethtool:
adapters[iface]['data'][addrfam][_DEB_CONFIG_PPPOE_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['addrfam'] = addrfam
opts.pop('mode', None)
for opt, val in opts.items():
inet = None
if opt.startswith('ipv4'):
opt = opt[4:]
inet = 'inet'
iface_data['inet']['addrfam'] = 'inet'
elif opt.startswith('ipv6'):
iface_data['inet6']['addrfam'] = 'inet6'
opt = opt[4:]
inet = 'inet6'
elif opt in ['ipaddr', 'address', 'ipaddresses', 'addresses', 'gateway', 'proto']:
iface_data['inet']['addrfam'] = 'inet'
inet = 'inet'
_opt = SALT_ATTR_TO_DEBIAN_ATTR_MAP.get(opt, opt)
_debopt = _opt.replace('-', '_')
for addrfam in ['inet', 'inet6']:
(valid, value, errmsg) = _validate_interface_option(_opt, val, addrfam=addrfam)
if not valid:
continue
if inet is None and _debopt not in iface_data[addrfam]:
iface_data[addrfam][_debopt] = value
elif inet == addrfam:
iface_data[addrfam][_debopt] = value
for opt in ['up_cmds', 'pre_up_cmds', 'post_up_cmds',
'down_cmds', 'pre_down_cmds', 'post_down_cmds']:
if opt in opts:
iface_data['inet'][opt] = opts[opt]
iface_data['inet6'][opt] = opts[opt]
# Remove incomplete/disabled inet blocks
for (addrfam, opt) in [('inet', 'enable_ipv4'), ('inet6', 'enable_ipv6')]:
if opts.get(opt, None) is False:
iface_data.pop(addrfam)
elif iface_data[addrfam].get('addrfam', '') != addrfam:
iface_data.pop(addrfam)
return adapters
def _parse_settings_source(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['sources'] = [opts['source']]
return adapters
def _parse_network_settings(opts, current):
'''
Filters given options and outputs valid settings for
the global network settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
current = dict((k.lower(), v) for (k, v) in six.iteritems(current))
result = {}
valid = _CONFIG_TRUE + _CONFIG_FALSE
if 'enabled' not in opts:
try:
opts['networking'] = current['networking']
_log_default_network('networking', current['networking'])
except ValueError:
_raise_error_network('networking', valid)
else:
opts['networking'] = opts['enabled']
if opts['networking'] in valid:
if opts['networking'] in _CONFIG_TRUE:
result['networking'] = 'yes'
elif opts['networking'] in _CONFIG_FALSE:
result['networking'] = 'no'
else:
_raise_error_network('networking', valid)
if 'hostname' not in opts:
try:
opts['hostname'] = current['hostname']
_log_default_network('hostname', current['hostname'])
except ValueError:
_raise_error_network('hostname', ['server1.example.com'])
if opts['hostname']:
result['hostname'] = opts['hostname']
else:
_raise_error_network('hostname', ['server1.example.com'])
if 'search' in opts:
result['search'] = opts['search']
return result
def _parse_routes(iface, opts):
'''
Filters given options and outputs valid settings for
the route settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
result = {}
if 'routes' not in opts:
_raise_error_routes(iface, 'routes', 'List of routes')
for opt in opts:
result[opt] = opts[opt]
return result
def _write_file(iface, data, folder, pattern):
'''
Writes a file to disk
'''
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
return filename
def _write_file_routes(iface, data, folder, pattern):
'''
Writes a file to disk
'''
# ifup / ifdown is executing given folder via run-parts.
# according to run-parts man-page, only filenames with this pattern are
# executed: (^[a-zA-Z0-9_-]+$)
# In order to make the routes file work for vlan interfaces
# (default would have been in example /etc/network/if-up.d/route-bond0.12)
# these dots in the iface name need to be replaced by underscores, so it
# can be executed by run-parts
iface = iface.replace('.', '_')
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
__salt__['file.set_mode'](filename, '0755')
return filename
def _write_file_network(data, filename, create=False):
'''
Writes a file to disk
If file does not exist, only create if create
argument is True
'''
if not os.path.exists(filename) and not create:
msg = '{0} cannot be written. {0} does not exist\
and create is set to False'
msg = msg.format(filename)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
def _read_temp(data):
'''
Return what would be written to disk
'''
tout = StringIO()
tout.write(data)
tout.seek(0)
output = tout.readlines()
tout.close()
return output
def _read_temp_ifaces(iface, data):
'''
Return what would be written to disk for interfaces
'''
try:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': data})
# Return as an array so the difflib works
return [item + '\n' for item in ifcfg.split('\n')]
def _write_file_ifaces(iface, data, **settings):
'''
Writes a file to disk
'''
try:
eth_template = JINJA.get_template('debian_eth.jinja')
source_template = JINJA.get_template('debian_source.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
# Read /etc/network/interfaces into a dict
adapters = _parse_interfaces()
# Apply supplied settings over on-disk settings
adapters[iface] = data
ifcfg = ''
for adapter in adapters:
if 'type' in adapters[adapter] and adapters[adapter]['type'] == 'source':
tmp = source_template.render({'name': adapter, 'data': adapters[adapter]})
else:
tmp = eth_template.render({'name': adapter, 'data': adapters[adapter]})
ifcfg = ifcfg + tmp
if adapter == iface:
saved_ifcfg = tmp
_SEPARATE_FILE = False
if 'filename' in settings:
if not settings['filename'].startswith('/'):
filename = '{0}/{1}'.format(_DEB_NETWORK_DIR, settings['filename'])
else:
filename = settings['filename']
_SEPARATE_FILE = True
else:
if 'filename' in adapters[adapter]['data']:
filename = adapters[adapter]['data']
else:
filename = _DEB_NETWORK_FILE
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
if _SEPARATE_FILE:
fout.write(salt.utils.stringutils.to_str(saved_ifcfg))
else:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return saved_ifcfg.split('\n')
def _write_file_ppp_ifaces(iface, data):
'''
Writes a file to disk
'''
try:
template = JINJA.get_template('debian_ppp_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_ppp_eth.jinja')
return ''
adapters = _parse_interfaces()
adapters[iface] = data
ifcfg = ''
tmp = template.render({'data': adapters[iface]})
ifcfg = tmp + ifcfg
filename = _DEB_PPP_DIR + '/' + adapters[iface]['data']['inet']['provider']
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.fopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return filename
def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'vlan':
settings['vlan'] = 'yes'
__salt__['pkg.install']('vlan')
elif iface_type == 'pppoe':
settings['pppoe'] = 'yes'
if not __salt__['pkg.version']('ppp'):
inst = __salt__['pkg.install']('ppp')
elif iface_type == 'bond':
if 'slaves' not in settings:
msg = 'slaves is a required setting for bond interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'bridge':
if 'ports' not in settings:
msg = (
'ports is a required setting for bridge interfaces on Debian '
'or Ubuntu based systems'
)
log.error(msg)
raise AttributeError(msg)
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'pppoe']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
if iface_type in ['source']:
opts = _parse_settings_source(settings, iface_type, enabled, iface)
if 'test' in settings and settings['test']:
return _read_temp_ifaces(iface, opts[iface])
ifcfg = _write_file_ifaces(iface, opts[iface], **settings)
if iface_type == 'pppoe':
_write_file_ppp_ifaces(iface, opts[iface])
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg]
def build_routes(iface, **settings):
'''
Add route scripts for a network interface using up commands.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
'''
opts = _parse_routes(iface, settings)
try:
template = JINJA.get_template('route_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template route_eth.jinja')
return ''
add_routecfg = template.render(route_type='add',
routes=opts['routes'],
iface=iface)
del_routecfg = template.render(route_type='del',
routes=opts['routes'],
iface=iface)
if 'test' in settings and settings['test']:
return _read_temp(add_routecfg + del_routecfg)
filename = _write_file_routes(iface,
add_routecfg,
_DEB_NETWORK_UP_DIR,
'route-{0}')
results = _read_file(filename)
filename = _write_file_routes(iface,
del_routecfg,
_DEB_NETWORK_DOWN_DIR,
'route-{0}')
results += _read_file(filename)
return results
def down(iface, iface_type):
'''
Shutdown a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.down eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought down.
if iface_type not in ['slave', 'source']:
return __salt__['cmd.run'](['ifdown', iface])
return None
def get_bond(iface):
'''
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
'''
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
return _read_file(path)
def get_interface(iface):
'''
Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
adapters = _parse_interfaces()
if iface in adapters:
try:
if iface == 'source':
template = JINJA.get_template('debian_source.jinja')
else:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': adapters[iface]})
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg.split('\n')]
else:
return []
def up(iface, iface_type): # pylint: disable=C0103
'''
Start up a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.up eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought up.
if iface_type not in ('slave', 'source'):
return __salt__['cmd.run'](['ifup', iface])
return None
def get_network_settings():
'''
Return the contents of the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_network_settings
'''
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
settings = {}
if __salt__['service.available']('networking'):
if __salt__['service.status']('networking'):
settings['networking'] = "yes"
else:
settings['networking'] = "no"
else:
settings['networking'] = "no"
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
settings['hostname'] = hostname
settings['domainname'] = domainname
settings['searchdomain'] = searchdomain
else:
settings = _parse_current_network_settings()
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(settings)
return _read_temp(network)
def get_routes(iface):
'''
Return the routes for the interface
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0
'''
filename = os.path.join(_DEB_NETWORK_UP_DIR, 'route-{0}'.format(iface))
results = _read_file(filename)
filename = os.path.join(_DEB_NETWORK_DOWN_DIR, 'route-{0}'.format(iface))
results += _read_file(filename)
return results
def apply_network_settings(**settings):
'''
Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings
'''
if 'require_reboot' not in settings:
settings['require_reboot'] = False
if 'apply_hostname' not in settings:
settings['apply_hostname'] = False
hostname_res = True
if settings['apply_hostname'] in _CONFIG_TRUE:
if 'hostname' in settings:
hostname_res = __salt__['network.mod_hostname'](settings['hostname'])
else:
log.warning(
'The network state sls is trying to apply hostname '
'changes but no hostname is defined.'
)
hostname_res = False
res = True
if settings['require_reboot'] in _CONFIG_TRUE:
log.warning(
'The network state sls is requiring a reboot of the system to '
'properly apply network configuration.'
)
res = True
else:
stop = __salt__['service.stop']('networking')
time.sleep(2)
res = stop and __salt__['service.start']('networking')
return hostname_res and res
def build_network_settings(**settings):
'''
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
'''
changes = []
# Read current configuration and store default values
current_network_settings = _parse_current_network_settings()
# Build settings
opts = _parse_network_settings(settings, current_network_settings)
# Ubuntu has moved away from /etc/default/networking
# beginning with the 12.04 release so we disable or enable
# the networking related services on boot
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
if opts['networking'] == 'yes':
service_cmd = 'service.enable'
else:
service_cmd = 'service.disable'
if __salt__['service.available']('NetworkManager'):
__salt__[service_cmd]('NetworkManager')
if __salt__['service.available']('networking'):
__salt__[service_cmd]('networking')
else:
try:
template = JINJA.get_template('network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template network.jinja')
return ''
network = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(network)
# Write settings
_write_file_network(network, _DEB_NETWORKING_FILE, True)
# Get hostname and domain from opts
sline = opts['hostname'].split('.', 1)
opts['hostname'] = sline[0]
current_domainname = current_network_settings['domainname']
current_searchdomain = current_network_settings['searchdomain']
new_domain = False
if len(sline) > 1:
new_domainname = sline[1]
if new_domainname != current_domainname:
domainname = new_domainname
opts['domainname'] = new_domainname
new_domain = True
else:
domainname = current_domainname
opts['domainname'] = domainname
else:
domainname = current_domainname
opts['domainname'] = domainname
new_search = False
if 'search' in opts:
new_searchdomain = opts['search']
if new_searchdomain != current_searchdomain:
searchdomain = new_searchdomain
opts['searchdomain'] = new_searchdomain
new_search = True
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
# If the domain changes, then we should write the resolv.conf file.
if new_domain or new_search:
# Look for existing domain line and update if necessary
resolve = _parse_resolve()
domain_prog = re.compile(r'domain\s+')
search_prog = re.compile(r'search\s+')
new_contents = []
for item in _read_file(_DEB_RESOLV_FILE):
if domain_prog.match(item):
item = 'domain {0}'.format(domainname)
elif search_prog.match(item):
item = 'search {0}'.format(searchdomain)
new_contents.append(item)
# A domain line didn't exist so we'll add one in
# with the new domainname
if 'domain' not in resolve:
new_contents.insert(0, 'domain {0}' . format(domainname))
# A search line didn't exist so we'll add one in
# with the new search domain
if 'search' not in resolve:
new_contents.insert('domain' in resolve, 'search {0}'.format(searchdomain))
new_resolv = '\n'.join(new_contents)
# Write /etc/resolv.conf
if not ('test' in settings and settings['test']):
_write_file_network(new_resolv, _DEB_RESOLV_FILE)
# used for returning the results back
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(opts)
changes.extend(_read_temp(network))
return changes
|
saltstack/salt
|
salt/modules/debian_ip.py
|
build_interface
|
python
|
def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'vlan':
settings['vlan'] = 'yes'
__salt__['pkg.install']('vlan')
elif iface_type == 'pppoe':
settings['pppoe'] = 'yes'
if not __salt__['pkg.version']('ppp'):
inst = __salt__['pkg.install']('ppp')
elif iface_type == 'bond':
if 'slaves' not in settings:
msg = 'slaves is a required setting for bond interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'bridge':
if 'ports' not in settings:
msg = (
'ports is a required setting for bridge interfaces on Debian '
'or Ubuntu based systems'
)
log.error(msg)
raise AttributeError(msg)
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'pppoe']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
if iface_type in ['source']:
opts = _parse_settings_source(settings, iface_type, enabled, iface)
if 'test' in settings and settings['test']:
return _read_temp_ifaces(iface, opts[iface])
ifcfg = _write_file_ifaces(iface, opts[iface], **settings)
if iface_type == 'pppoe':
_write_file_ppp_ifaces(iface, opts[iface])
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg]
|
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_ip.py#L1607-L1670
|
[
"def _raise_error_iface(iface, option, expected):\n '''\n Log and raise an error with a logical formatted message.\n '''\n msg = _error_msg_iface(iface, option, expected)\n log.error(msg)\n raise AttributeError(msg)\n",
"def _parse_settings_eth(opts, iface_type, enabled, iface):\n '''\n Filters given options and outputs valid settings for a\n network interface.\n '''\n adapters = salt.utils.odict.OrderedDict()\n adapters[iface] = salt.utils.odict.OrderedDict()\n\n adapters[iface]['type'] = iface_type\n\n adapters[iface]['data'] = salt.utils.odict.OrderedDict()\n iface_data = adapters[iface]['data']\n iface_data['inet'] = salt.utils.odict.OrderedDict()\n iface_data['inet6'] = salt.utils.odict.OrderedDict()\n\n if enabled:\n adapters[iface]['enabled'] = True\n\n if opts.get('hotplug', False):\n adapters[iface]['hotplug'] = True\n\n if opts.get('enable_ipv6', None) and opts.get('iface_type', '') == 'vlan':\n iface_data['inet6']['vlan_raw_device'] = (\n re.sub(r'\\.\\d*', '', iface))\n\n for addrfam in ['inet', 'inet6']:\n if iface_type not in ['bridge']:\n tmp_ethtool = _parse_ethtool_opts(opts, iface)\n if tmp_ethtool:\n ethtool = {}\n for item in tmp_ethtool:\n ethtool[_ETHTOOL_CONFIG_OPTS[item]] = tmp_ethtool[item]\n\n iface_data[addrfam]['ethtool'] = ethtool\n # return a list of sorted keys to ensure consistent order\n iface_data[addrfam]['ethtool_keys'] = sorted(ethtool)\n\n if iface_type == 'bridge':\n bridging = _parse_bridge_opts(opts, iface)\n if bridging:\n iface_data[addrfam]['bridging'] = bridging\n iface_data[addrfam]['bridging_keys'] = sorted(bridging)\n iface_data[addrfam]['addrfam'] = addrfam\n\n elif iface_type == 'bond':\n bonding = _parse_settings_bond(opts, iface)\n if bonding:\n iface_data[addrfam]['bonding'] = bonding\n iface_data[addrfam]['bonding']['slaves'] = opts['slaves']\n iface_data[addrfam]['bonding_keys'] = sorted(bonding)\n iface_data[addrfam]['addrfam'] = addrfam\n\n elif iface_type == 'slave':\n adapters[iface]['master'] = opts['master']\n\n opts['proto'] = 'manual'\n iface_data[addrfam]['master'] = adapters[iface]['master']\n iface_data[addrfam]['addrfam'] = addrfam\n\n elif iface_type == 'vlan':\n iface_data[addrfam]['vlan_raw_device'] = re.sub(r'\\.\\d*', '', iface)\n iface_data[addrfam]['addrfam'] = addrfam\n\n elif iface_type == 'pppoe':\n tmp_ethtool = _parse_ethtool_pppoe_opts(opts, iface)\n if tmp_ethtool:\n for item in tmp_ethtool:\n adapters[iface]['data'][addrfam][_DEB_CONFIG_PPPOE_OPTS[item]] = tmp_ethtool[item]\n iface_data[addrfam]['addrfam'] = addrfam\n\n opts.pop('mode', None)\n\n for opt, val in opts.items():\n inet = None\n if opt.startswith('ipv4'):\n opt = opt[4:]\n inet = 'inet'\n iface_data['inet']['addrfam'] = 'inet'\n elif opt.startswith('ipv6'):\n iface_data['inet6']['addrfam'] = 'inet6'\n opt = opt[4:]\n inet = 'inet6'\n elif opt in ['ipaddr', 'address', 'ipaddresses', 'addresses', 'gateway', 'proto']:\n iface_data['inet']['addrfam'] = 'inet'\n inet = 'inet'\n\n _opt = SALT_ATTR_TO_DEBIAN_ATTR_MAP.get(opt, opt)\n _debopt = _opt.replace('-', '_')\n\n for addrfam in ['inet', 'inet6']:\n (valid, value, errmsg) = _validate_interface_option(_opt, val, addrfam=addrfam)\n if not valid:\n continue\n if inet is None and _debopt not in iface_data[addrfam]:\n iface_data[addrfam][_debopt] = value\n elif inet == addrfam:\n iface_data[addrfam][_debopt] = value\n\n for opt in ['up_cmds', 'pre_up_cmds', 'post_up_cmds',\n 'down_cmds', 'pre_down_cmds', 'post_down_cmds']:\n if opt in opts:\n iface_data['inet'][opt] = opts[opt]\n iface_data['inet6'][opt] = opts[opt]\n\n # Remove incomplete/disabled inet blocks\n for (addrfam, opt) in [('inet', 'enable_ipv4'), ('inet6', 'enable_ipv6')]:\n if opts.get(opt, None) is False:\n iface_data.pop(addrfam)\n elif iface_data[addrfam].get('addrfam', '') != addrfam:\n iface_data.pop(addrfam)\n\n return adapters\n",
"def _parse_settings_source(opts, iface_type, enabled, iface):\n '''\n Filters given options and outputs valid settings for a\n network interface.\n '''\n adapters = salt.utils.odict.OrderedDict()\n adapters[iface] = salt.utils.odict.OrderedDict()\n\n adapters[iface]['type'] = iface_type\n\n adapters[iface]['data'] = salt.utils.odict.OrderedDict()\n iface_data = adapters[iface]['data']\n iface_data['sources'] = [opts['source']]\n\n return adapters\n",
"def _read_temp_ifaces(iface, data):\n '''\n Return what would be written to disk for interfaces\n '''\n try:\n template = JINJA.get_template('debian_eth.jinja')\n except jinja2.exceptions.TemplateNotFound:\n log.error('Could not load template debian_eth.jinja')\n return ''\n\n ifcfg = template.render({'name': iface, 'data': data})\n # Return as an array so the difflib works\n return [item + '\\n' for item in ifcfg.split('\\n')]\n",
"def _write_file_ifaces(iface, data, **settings):\n '''\n Writes a file to disk\n '''\n try:\n eth_template = JINJA.get_template('debian_eth.jinja')\n source_template = JINJA.get_template('debian_source.jinja')\n except jinja2.exceptions.TemplateNotFound:\n log.error('Could not load template debian_eth.jinja')\n return ''\n\n # Read /etc/network/interfaces into a dict\n adapters = _parse_interfaces()\n # Apply supplied settings over on-disk settings\n adapters[iface] = data\n\n ifcfg = ''\n for adapter in adapters:\n if 'type' in adapters[adapter] and adapters[adapter]['type'] == 'source':\n tmp = source_template.render({'name': adapter, 'data': adapters[adapter]})\n else:\n tmp = eth_template.render({'name': adapter, 'data': adapters[adapter]})\n ifcfg = ifcfg + tmp\n if adapter == iface:\n saved_ifcfg = tmp\n\n _SEPARATE_FILE = False\n if 'filename' in settings:\n if not settings['filename'].startswith('/'):\n filename = '{0}/{1}'.format(_DEB_NETWORK_DIR, settings['filename'])\n else:\n filename = settings['filename']\n _SEPARATE_FILE = True\n else:\n if 'filename' in adapters[adapter]['data']:\n filename = adapters[adapter]['data']\n else:\n filename = _DEB_NETWORK_FILE\n\n if not os.path.exists(os.path.dirname(filename)):\n msg = '{0} cannot be written.'\n msg = msg.format(os.path.dirname(filename))\n log.error(msg)\n raise AttributeError(msg)\n with salt.utils.files.flopen(filename, 'w') as fout:\n if _SEPARATE_FILE:\n fout.write(salt.utils.stringutils.to_str(saved_ifcfg))\n else:\n fout.write(salt.utils.stringutils.to_str(ifcfg))\n\n # Return as an array so the difflib works\n return saved_ifcfg.split('\\n')\n",
"def _write_file_ppp_ifaces(iface, data):\n '''\n Writes a file to disk\n '''\n try:\n template = JINJA.get_template('debian_ppp_eth.jinja')\n except jinja2.exceptions.TemplateNotFound:\n log.error('Could not load template debian_ppp_eth.jinja')\n return ''\n\n adapters = _parse_interfaces()\n adapters[iface] = data\n\n ifcfg = ''\n tmp = template.render({'data': adapters[iface]})\n ifcfg = tmp + ifcfg\n\n filename = _DEB_PPP_DIR + '/' + adapters[iface]['data']['inet']['provider']\n if not os.path.exists(os.path.dirname(filename)):\n msg = '{0} cannot be written.'\n msg = msg.format(os.path.dirname(filename))\n log.error(msg)\n raise AttributeError(msg)\n with salt.utils.files.fopen(filename, 'w') as fout:\n fout.write(salt.utils.stringutils.to_str(ifcfg))\n\n # Return as an array so the difflib works\n return filename\n"
] |
# -*- coding: utf-8 -*-
'''
The networking module for Debian-based distros
References:
* http://www.debian.org/doc/manuals/debian-reference/ch05.en.html
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import functools
import logging
import os.path
import os
import re
import time
# Import third party libs
import jinja2
import jinja2.exceptions
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error,no-name-in-module
# Import salt libs
import salt.utils.dns
import salt.utils.files
import salt.utils.odict
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.validate.net
# Set up logging
log = logging.getLogger(__name__)
# Set up template environment
JINJA = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'debian_ip')
)
)
# Define the module's virtual name
__virtualname__ = 'ip'
def __virtual__():
'''
Confine this module to Debian-based distros
'''
if __grains__['os_family'] == 'Debian':
return __virtualname__
return (False, 'The debian_ip module could not be loaded: '
'unsupported OS family')
_ETHTOOL_CONFIG_OPTS = {
'speed': 'link-speed',
'duplex': 'link-duplex',
'autoneg': 'ethernet-autoneg',
'ethernet-port': 'ethernet-port',
'wol': 'ethernet-wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'rx': 'offload-rx',
'tx': 'offload-tx',
'sg': 'offload-sg',
'tso': 'offload-tso',
'ufo': 'offload-ufo',
'gso': 'offload-gso',
'gro': 'offload-gro',
'lro': 'offload-lro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_REV_ETHTOOL_CONFIG_OPTS = {
'link-speed': 'speed',
'link-duplex': 'duplex',
'ethernet-autoneg': 'autoneg',
'ethernet-port': 'ethernet-port',
'ethernet-wol': 'wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'offload-rx': 'rx',
'offload-tx': 'tx',
'offload-sg': 'sg',
'offload-tso': 'tso',
'offload-ufo': 'ufo',
'offload-gso': 'gso',
'offload-lro': 'lro',
'offload-gro': 'gro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_DEB_CONFIG_PPPOE_OPTS = {
'user': 'user',
'password': 'password',
'provider': 'provider',
'pppoe_iface': 'pppoe_iface',
'noipdefault': 'noipdefault',
'usepeerdns': 'usepeerdns',
'defaultroute': 'defaultroute',
'holdoff': 'holdoff',
'maxfail': 'maxfail',
'hide-password': 'hide-password',
'lcp-echo-interval': 'lcp-echo-interval',
'lcp-echo-failure': 'lcp-echo-failure',
'connect': 'connect',
'noauth': 'noauth',
'persist': 'persist',
'mtu': 'mtu',
'noaccomp': 'noaccomp',
'linkname': 'linkname',
}
_DEB_ROUTES_FILE = '/etc/network/routes'
_DEB_NETWORK_FILE = '/etc/network/interfaces'
_DEB_NETWORK_DIR = '/etc/network/interfaces.d/'
_DEB_NETWORK_UP_DIR = '/etc/network/if-up.d/'
_DEB_NETWORK_DOWN_DIR = '/etc/network/if-down.d/'
_DEB_NETWORK_CONF_FILES = '/etc/modprobe.d/'
_DEB_NETWORKING_FILE = '/etc/default/networking'
_DEB_HOSTNAME_FILE = '/etc/hostname'
_DEB_RESOLV_FILE = '/etc/resolv.conf'
_DEB_PPP_DIR = '/etc/ppp/peers/'
_CONFIG_TRUE = ['yes', 'on', 'true', '1', True]
_CONFIG_FALSE = ['no', 'off', 'false', '0', False]
_IFACE_TYPES = [
'eth', 'bond', 'alias', 'clone',
'ipsec', 'dialup', 'bridge', 'slave',
'vlan', 'pppoe', 'source',
]
def _error_msg_iface(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, '|'.join(str(e) for e in expected))
def _error_msg_routes(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, expected)
def _log_default_iface(iface, opt, value):
log.info(
'Using default option -- Interface: %s Option: %s Value: %s',
iface, opt, value
)
def _error_msg_network(option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]'
return msg.format(option, '|'.join(str(e) for e in expected))
def _log_default_network(opt, value):
log.info('Using existing setting -- Setting: %s Value: %s', opt, value)
def _raise_error_iface(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_iface(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_network(option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_network(option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_routes(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_routes(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _read_file(path):
'''
Reads and returns the contents of a text file
'''
try:
with salt.utils.files.flopen(path, 'rb') as contents:
return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]
except (OSError, IOError):
return ''
def _parse_resolve():
'''
Parse /etc/resolv.conf
'''
return salt.utils.dns.parse_resolv(_DEB_RESOLV_FILE)
def _parse_domainname():
'''
Parse /etc/resolv.conf and return domainname
'''
return _parse_resolve().get('domain', '')
def _parse_searchdomain():
'''
Parse /etc/resolv.conf and return searchdomain
'''
return _parse_resolve().get('search', '')
def _parse_hostname():
'''
Parse /etc/hostname and return hostname
'''
contents = _read_file(_DEB_HOSTNAME_FILE)
if contents:
return contents[0].split('\n')[0]
else:
return ''
def _parse_current_network_settings():
'''
Parse /etc/default/networking and return current configuration
'''
opts = salt.utils.odict.OrderedDict()
opts['networking'] = ''
if os.path.isfile(_DEB_NETWORKING_FILE):
with salt.utils.files.fopen(_DEB_NETWORKING_FILE) as contents:
for line in contents:
salt.utils.stringutils.to_unicode(line)
if line.startswith('#'):
continue
elif line.startswith('CONFIGURE_INTERFACES'):
opts['networking'] = line.split('=', 1)[1].strip()
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
opts['hostname'] = hostname
opts['domainname'] = domainname
opts['searchdomain'] = searchdomain
return opts
# def __validator_func(value):
# return (valid: True/False, (transformed) value, error message)
def __ipv4_quad(value):
'''validate an IPv4 address'''
return (salt.utils.validate.net.ipv4_addr(value), value,
'dotted IPv4 address')
def __ipv6(value):
'''validate an IPv6 address'''
return (salt.utils.validate.net.ipv6_addr(value), value,
'IPv6 address')
def __mac(value):
'''validate a mac address'''
return (salt.utils.validate.net.mac(value), value,
'MAC address')
def __anything(value):
return (True, value, None)
def __int(value):
'''validate an integer'''
valid, _value = False, value
try:
_value = int(value)
valid = True
except ValueError:
pass
return (valid, _value, 'integer')
def __float(value):
'''validate a float'''
valid, _value = False, value
try:
_value = float(value)
valid = True
except ValueError:
pass
return (valid, _value, 'float')
def __ipv4_netmask(value):
'''validate an IPv4 dotted quad or integer CIDR netmask'''
valid, errmsg = False, 'dotted quad or integer CIDR (0->32)'
valid, value, _ = __int(value)
if not (valid and 0 <= value <= 32):
valid = salt.utils.validate.net.netmask(value)
return (valid, value, errmsg)
def __ipv6_netmask(value):
'''validate an IPv6 integer netmask'''
valid, errmsg = False, 'IPv6 netmask (0->128)'
valid, value, _ = __int(value)
valid = (valid and 0 <= value <= 128)
return (valid, value, errmsg)
def __within2(value, within=None, errmsg=None, dtype=None):
'''validate that a value is in ``within`` and optionally a ``dtype``'''
valid, _value = False, value
if dtype:
try:
_value = dtype(value) # TODO: this is a bit loose when dtype is a class
valid = _value in within
except ValueError:
pass
else:
valid = _value in within
if errmsg is None:
if dtype:
typename = getattr(dtype, '__name__',
hasattr(dtype, '__class__')
and getattr(dtype.__class__, 'name', dtype))
errmsg = '{0} within \'{1}\''.format(typename, within)
else:
errmsg = 'within \'{0}\''.format(within)
return (valid, _value, errmsg)
def __within(within=None, errmsg=None, dtype=None):
return functools.partial(__within2, within=within,
errmsg=errmsg, dtype=dtype)
def __space_delimited_list(value):
'''validate that a value contains one or more space-delimited values'''
if isinstance(value, six.string_types):
value = value.strip().split()
if hasattr(value, '__iter__') and value != []:
return (True, value, 'space-delimited string')
else:
return (False, value, '{0} is not a valid space-delimited value.\n'.format(value))
SALT_ATTR_TO_DEBIAN_ATTR_MAP = {
'dns': 'dns-nameservers',
'search': 'dns-search',
'hwaddr': 'hwaddress', # TODO: this limits bootp functionality
'ipaddr': 'address',
'ipaddrs': 'addresses',
}
DEBIAN_ATTR_TO_SALT_ATTR_MAP = dict(
(v, k) for (k, v) in six.iteritems(SALT_ATTR_TO_DEBIAN_ATTR_MAP))
# TODO
DEBIAN_ATTR_TO_SALT_ATTR_MAP['address'] = 'address'
DEBIAN_ATTR_TO_SALT_ATTR_MAP['hwaddress'] = 'hwaddress'
IPV4_VALID_PROTO = ['bootp', 'dhcp', 'static', 'manual', 'loopback', 'ppp']
IPV4_ATTR_MAP = {
'proto': __within(IPV4_VALID_PROTO, dtype=six.text_type),
# ipv4 static & manual
'address': __ipv4_quad,
'addresses': __anything,
'netmask': __ipv4_netmask,
'broadcast': __ipv4_quad,
'metric': __int,
'gateway': __ipv4_quad, # supports a colon-delimited list
'pointopoint': __ipv4_quad,
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'link', 'host'], dtype=six.text_type),
# dhcp
'hostname': __anything,
'leasehours': __int,
'leasetime': __int,
'vendor': __anything,
'client': __anything,
# bootp
'bootfile': __anything,
'server': __ipv4_quad,
'hwaddr': __mac,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'dstaddr': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# bond
'slaves': __anything,
# ppp
'provider': __anything,
'unit': __int,
'options': __anything,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
#
'network': __anything, # i don't know what this is
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
IPV6_VALID_PROTO = ['auto', 'loopback', 'static', 'manual',
'dhcp', 'v4tunnel', '6to4']
IPV6_ATTR_MAP = {
'proto': __within(IPV6_VALID_PROTO),
# ipv6 static & manual
'address': __ipv6,
'addresses': __anything,
'netmask': __ipv6_netmask,
'broadcast': __ipv6,
'gateway': __ipv6, # supports a colon-delimited list
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'site', 'link', 'host'], dtype=six.text_type),
# inet6 auto
'privext': __within([0, 1, 2], dtype=int),
'dhcp': __within([0, 1], dtype=int),
# inet6 static & manual & dhcp
'media': __anything,
'accept_ra': __within([0, 1], dtype=int),
'autoconf': __within([0, 1], dtype=int),
'preferred-lifetime': __int,
'dad-attempts': __int, # 0 to disable
'dad-interval': __float,
# bond
'slaves': __anything,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
WIRELESS_ATTR_MAP = {
'wireless-essid': __anything,
'wireless-mode': __anything, # TODO
'wpa-ap-scan': __within([0, 1, 2], dtype=int), # TODO
'wpa-conf': __anything,
'wpa-driver': __anything,
'wpa-group': __anything,
'wpa-key-mgmt': __anything,
'wpa-pairwise': __anything,
'wpa-psk': __anything,
'wpa-proto': __anything, # partial(__within,
'wpa-roam': __anything,
'wpa-ssid': __anything, # TODO
}
ATTRMAPS = {
'inet': [IPV4_ATTR_MAP, WIRELESS_ATTR_MAP],
'inet6': [IPV6_ATTR_MAP, WIRELESS_ATTR_MAP]
}
def _validate_interface_option(attr, value, addrfam='inet'):
'''lookup the validation function for a [addrfam][attr] and
return the results
:param attr: attribute name
:param value: raw setting value
:param addrfam: address family (inet, inet6,
'''
valid, _value, errmsg = False, value, 'Unknown validator'
attrmaps = ATTRMAPS.get(addrfam, [])
for attrmap in attrmaps:
if attr in attrmap:
validate_func = attrmap[attr]
(valid, _value, errmsg) = validate_func(value)
break
return (valid, _value, errmsg)
def _attrmaps_contain_attr(attr):
return (
attr in WIRELESS_ATTR_MAP or
attr in IPV4_ATTR_MAP or
attr in IPV6_ATTR_MAP)
def _parse_interfaces(interface_files=None):
'''
Parse /etc/network/interfaces and return current configured interfaces
'''
if interface_files is None:
interface_files = []
# Add this later.
if os.path.exists(_DEB_NETWORK_DIR):
interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]
if os.path.isfile(_DEB_NETWORK_FILE):
interface_files.insert(0, _DEB_NETWORK_FILE)
adapters = salt.utils.odict.OrderedDict()
method = -1
for interface_file in interface_files:
with salt.utils.files.fopen(interface_file) as interfaces:
# This ensures iface_dict exists, but does not ensure we're not reading a new interface.
iface_dict = {}
for line in interfaces:
line = salt.utils.stringutils.to_unicode(line)
# Identify the clauses by the first word of each line.
# Go to the next line if the current line is a comment
# or all spaces.
if line.lstrip().startswith('#') or line.isspace():
continue
# Parse the iface clause
if line.startswith('iface'):
sline = line.split()
if len(sline) != 4:
msg = 'Interface file malformed: {0}.'
msg = msg.format(sline)
log.error(msg)
raise AttributeError(msg)
iface_name = sline[1]
addrfam = sline[2]
method = sline[3]
# Create item in dict, if not already there
if iface_name not in adapters:
adapters[iface_name] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters[iface_name]:
adapters[iface_name]['data'] = salt.utils.odict.OrderedDict()
if addrfam not in adapters[iface_name]['data']:
adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict()
iface_dict = adapters[iface_name]['data'][addrfam]
iface_dict['addrfam'] = addrfam
iface_dict['proto'] = method
iface_dict['filename'] = interface_file
# Parse the detail clauses.
elif line[0].isspace():
sline = line.split()
# conf file attr: dns-nameservers
# salt states.network attr: dns
attr, valuestr = line.rstrip().split(None, 1)
if _attrmaps_contain_attr(attr):
if '-' in attr:
attrname = attr.replace('-', '_')
else:
attrname = attr
(valid, value, errmsg) = _validate_interface_option(
attr, valuestr, addrfam)
if attrname == 'address' and 'address' in iface_dict:
if 'addresses' not in iface_dict:
iface_dict['addresses'] = []
iface_dict['addresses'].append(value)
else:
iface_dict[attrname] = value
elif attr in _REV_ETHTOOL_CONFIG_OPTS:
if 'ethtool' not in iface_dict:
iface_dict['ethtool'] = salt.utils.odict.OrderedDict()
iface_dict['ethtool'][attr] = valuestr
elif attr.startswith('bond'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bonding' not in iface_dict:
iface_dict['bonding'] = salt.utils.odict.OrderedDict()
iface_dict['bonding'][opt] = valuestr
elif attr.startswith('bridge'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bridging' not in iface_dict:
iface_dict['bridging'] = salt.utils.odict.OrderedDict()
iface_dict['bridging'][opt] = valuestr
elif attr in ['up', 'pre-up', 'post-up',
'down', 'pre-down', 'post-down']:
cmd = valuestr
cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr))
if cmd_key not in iface_dict:
iface_dict[cmd_key] = []
iface_dict[cmd_key].append(cmd)
elif line.startswith('auto'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['enabled'] = True
elif line.startswith('allow-hotplug'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['hotplug'] = True
elif line.startswith('source'):
if 'source' not in adapters:
adapters['source'] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters['source']:
adapters['source']['data'] = salt.utils.odict.OrderedDict()
adapters['source']['data']['sources'] = []
adapters['source']['data']['sources'].append(line.split()[1])
# Return a sorted list of the keys for bond, bridge and ethtool options to
# ensure a consistent order
for iface_name in adapters:
if iface_name == 'source':
continue
if 'data' not in adapters[iface_name]:
msg = 'Interface file malformed for interface: {0}.'.format(iface_name)
log.error(msg)
adapters.pop(iface_name)
continue
for opt in ['ethtool', 'bonding', 'bridging']:
for inet in ['inet', 'inet6']:
if inet in adapters[iface_name]['data']:
if opt in adapters[iface_name]['data'][inet]:
opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys())
adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys
return adapters
def _parse_ethtool_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
if 'autoneg' in opts:
if opts['autoneg'] in _CONFIG_TRUE:
config.update({'autoneg': 'on'})
elif opts['autoneg'] in _CONFIG_FALSE:
config.update({'autoneg': 'off'})
else:
_raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE)
if 'duplex' in opts:
valid = ['full', 'half']
if opts['duplex'] in valid:
config.update({'duplex': opts['duplex']})
else:
_raise_error_iface(iface, 'duplex', valid)
if 'speed' in opts:
valid = ['10', '100', '1000', '10000']
if six.text_type(opts['speed']) in valid:
config.update({'speed': opts['speed']})
else:
_raise_error_iface(iface, opts['speed'], valid)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'on'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'off'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_ethtool_pppoe_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
for opt in _DEB_CONFIG_PPPOE_OPTS:
if opt in opts:
config[opt] = opts[opt]
if 'provider' in opts and not opts['provider']:
_raise_error_iface(iface, 'provider', _CONFIG_TRUE + _CONFIG_FALSE)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('noipdefault', 'usepeerdns', 'defaultroute', 'hide-password', 'noauth', 'persist', 'noaccomp'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'True'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'False'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_settings_bond(opts, iface):
'''
Filters given options and outputs valid settings for requested
operation. If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond_def = {
# 803.ad aggregation selection logic
# 0 for stable (default)
# 1 for bandwidth
# 2 for count
'ad_select': '0',
# Max number of transmit queues (default = 16)
'tx_queues': '16',
# Link monitoring in milliseconds. Most NICs support this
'miimon': '100',
# ARP interval in milliseconds
'arp_interval': '250',
# Delay before considering link down in milliseconds (miimon * 2)
'downdelay': '200',
# lacp_rate 0: Slow - every 30 seconds
# lacp_rate 1: Fast - every 1 second
'lacp_rate': '0',
# Max bonds for this driver
'max_bonds': '1',
# Specifies the time, in milliseconds, to wait before
# enabling a slave after a link recovery has been
# detected. Only used with miimon.
'updelay': '0',
# Used with miimon.
# On: driver sends mii
# Off: ethtool sends mii
'use_carrier': 'on',
# Default. Don't change unless you know what you are doing.
'xmit_hash_policy': 'layer2',
}
if opts['mode'] in ['balance-rr', '0']:
log.info('Device: %s Bonding Mode: load balancing (round-robin)', iface)
return _parse_settings_bond_0(opts, iface, bond_def)
elif opts['mode'] in ['active-backup', '1']:
log.info('Device: %s Bonding Mode: fault-tolerance (active-backup)', iface)
return _parse_settings_bond_1(opts, iface, bond_def)
elif opts['mode'] in ['balance-xor', '2']:
log.info('Device: %s Bonding Mode: load balancing (xor)', iface)
return _parse_settings_bond_2(opts, iface, bond_def)
elif opts['mode'] in ['broadcast', '3']:
log.info('Device: %s Bonding Mode: fault-tolerance (broadcast)', iface)
return _parse_settings_bond_3(opts, iface, bond_def)
elif opts['mode'] in ['802.3ad', '4']:
log.info('Device: %s Bonding Mode: IEEE 802.3ad Dynamic link '
'aggregation', iface)
return _parse_settings_bond_4(opts, iface, bond_def)
elif opts['mode'] in ['balance-tlb', '5']:
log.info('Device: %s Bonding Mode: transmit load balancing', iface)
return _parse_settings_bond_5(opts, iface, bond_def)
elif opts['mode'] in ['balance-alb', '6']:
log.info('Device: %s Bonding Mode: adaptive load balancing', iface)
return _parse_settings_bond_6(opts, iface, bond_def)
else:
valid = [
'0', '1', '2', '3', '4', '5', '6',
'balance-rr', 'active-backup', 'balance-xor',
'broadcast', '802.3ad', 'balance-tlb', 'balance-alb'
]
_raise_error_iface(iface, 'mode', valid)
def _parse_settings_bond_0(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond0.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '0'}
# ARP targets in n.n.n.n form
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
return bond
def _parse_settings_bond_1(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '1'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
if not (__grains__['os'] == "Ubuntu" and __grains__['osrelease_info'][0] >= 16):
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_2(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond2.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '2'}
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_3(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond3.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '3'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_4(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond4.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '4'}
for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']:
if binding in opts:
if binding == 'lacp_rate':
if opts[binding] == 'fast':
opts.update({binding: '1'})
if opts[binding] == 'slow':
opts.update({binding: '0'})
valid = ['fast', '1', 'slow', '0']
else:
valid = ['integer']
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, valid)
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_5(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond5.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '5'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_settings_bond_6(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond6.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '6'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_bridge_opts(opts, iface):
'''
Filters given options and outputs valid settings for BRIDGING_OPTS
If an option has a value that is not expected, this
function will log the Interface, Setting and what was expected.
'''
config = {}
if 'ports' in opts:
if isinstance(opts['ports'], list):
opts['ports'] = ' '.join(opts['ports'])
config.update({'ports': opts['ports']})
for opt in ['ageing', 'fd', 'gcint', 'hello', 'maxage']:
if opt in opts:
try:
float(opts[opt])
config.update({opt: opts[opt]})
except ValueError:
_raise_error_iface(iface, opt, ['float'])
for opt in ['bridgeprio', 'maxwait']:
if opt in opts:
if isinstance(opts[opt], int):
config.update({opt: opts[opt]})
else:
_raise_error_iface(iface, opt, ['integer'])
if 'hw' in opts:
# match 12 hex digits with either : or - as separators between pairs
if re.match('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$',
opts['hw'].lower()):
config.update({'hw': opts['hw']})
else:
_raise_error_iface(iface, 'hw', ['valid MAC address'])
for opt in ['pathcost', 'portprio']:
if opt in opts:
try:
port, cost_or_prio = opts[opt].split()
int(cost_or_prio)
config.update({opt: '{0} {1}'.format(port, cost_or_prio)})
except ValueError:
_raise_error_iface(iface, opt, ['interface integer'])
if 'stp' in opts:
if opts['stp'] in _CONFIG_TRUE:
config.update({'stp': 'on'})
elif opts['stp'] in _CONFIG_FALSE:
config.update({'stp': 'off'})
else:
_raise_error_iface(iface, 'stp', _CONFIG_TRUE + _CONFIG_FALSE)
if 'waitport' in opts:
if isinstance(opts['waitport'], int):
config.update({'waitport': opts['waitport']})
else:
values = opts['waitport'].split()
waitport_time = values.pop(0)
if waitport_time.isdigit() and values:
config.update({
'waitport': '{0} {1}'.format(
waitport_time, ' '.join(values)
)
})
else:
_raise_error_iface(iface, opt, ['integer [interfaces]'])
return config
def _parse_settings_eth(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['inet'] = salt.utils.odict.OrderedDict()
iface_data['inet6'] = salt.utils.odict.OrderedDict()
if enabled:
adapters[iface]['enabled'] = True
if opts.get('hotplug', False):
adapters[iface]['hotplug'] = True
if opts.get('enable_ipv6', None) and opts.get('iface_type', '') == 'vlan':
iface_data['inet6']['vlan_raw_device'] = (
re.sub(r'\.\d*', '', iface))
for addrfam in ['inet', 'inet6']:
if iface_type not in ['bridge']:
tmp_ethtool = _parse_ethtool_opts(opts, iface)
if tmp_ethtool:
ethtool = {}
for item in tmp_ethtool:
ethtool[_ETHTOOL_CONFIG_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['ethtool'] = ethtool
# return a list of sorted keys to ensure consistent order
iface_data[addrfam]['ethtool_keys'] = sorted(ethtool)
if iface_type == 'bridge':
bridging = _parse_bridge_opts(opts, iface)
if bridging:
iface_data[addrfam]['bridging'] = bridging
iface_data[addrfam]['bridging_keys'] = sorted(bridging)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'bond':
bonding = _parse_settings_bond(opts, iface)
if bonding:
iface_data[addrfam]['bonding'] = bonding
iface_data[addrfam]['bonding']['slaves'] = opts['slaves']
iface_data[addrfam]['bonding_keys'] = sorted(bonding)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'slave':
adapters[iface]['master'] = opts['master']
opts['proto'] = 'manual'
iface_data[addrfam]['master'] = adapters[iface]['master']
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'vlan':
iface_data[addrfam]['vlan_raw_device'] = re.sub(r'\.\d*', '', iface)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'pppoe':
tmp_ethtool = _parse_ethtool_pppoe_opts(opts, iface)
if tmp_ethtool:
for item in tmp_ethtool:
adapters[iface]['data'][addrfam][_DEB_CONFIG_PPPOE_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['addrfam'] = addrfam
opts.pop('mode', None)
for opt, val in opts.items():
inet = None
if opt.startswith('ipv4'):
opt = opt[4:]
inet = 'inet'
iface_data['inet']['addrfam'] = 'inet'
elif opt.startswith('ipv6'):
iface_data['inet6']['addrfam'] = 'inet6'
opt = opt[4:]
inet = 'inet6'
elif opt in ['ipaddr', 'address', 'ipaddresses', 'addresses', 'gateway', 'proto']:
iface_data['inet']['addrfam'] = 'inet'
inet = 'inet'
_opt = SALT_ATTR_TO_DEBIAN_ATTR_MAP.get(opt, opt)
_debopt = _opt.replace('-', '_')
for addrfam in ['inet', 'inet6']:
(valid, value, errmsg) = _validate_interface_option(_opt, val, addrfam=addrfam)
if not valid:
continue
if inet is None and _debopt not in iface_data[addrfam]:
iface_data[addrfam][_debopt] = value
elif inet == addrfam:
iface_data[addrfam][_debopt] = value
for opt in ['up_cmds', 'pre_up_cmds', 'post_up_cmds',
'down_cmds', 'pre_down_cmds', 'post_down_cmds']:
if opt in opts:
iface_data['inet'][opt] = opts[opt]
iface_data['inet6'][opt] = opts[opt]
# Remove incomplete/disabled inet blocks
for (addrfam, opt) in [('inet', 'enable_ipv4'), ('inet6', 'enable_ipv6')]:
if opts.get(opt, None) is False:
iface_data.pop(addrfam)
elif iface_data[addrfam].get('addrfam', '') != addrfam:
iface_data.pop(addrfam)
return adapters
def _parse_settings_source(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['sources'] = [opts['source']]
return adapters
def _parse_network_settings(opts, current):
'''
Filters given options and outputs valid settings for
the global network settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
current = dict((k.lower(), v) for (k, v) in six.iteritems(current))
result = {}
valid = _CONFIG_TRUE + _CONFIG_FALSE
if 'enabled' not in opts:
try:
opts['networking'] = current['networking']
_log_default_network('networking', current['networking'])
except ValueError:
_raise_error_network('networking', valid)
else:
opts['networking'] = opts['enabled']
if opts['networking'] in valid:
if opts['networking'] in _CONFIG_TRUE:
result['networking'] = 'yes'
elif opts['networking'] in _CONFIG_FALSE:
result['networking'] = 'no'
else:
_raise_error_network('networking', valid)
if 'hostname' not in opts:
try:
opts['hostname'] = current['hostname']
_log_default_network('hostname', current['hostname'])
except ValueError:
_raise_error_network('hostname', ['server1.example.com'])
if opts['hostname']:
result['hostname'] = opts['hostname']
else:
_raise_error_network('hostname', ['server1.example.com'])
if 'search' in opts:
result['search'] = opts['search']
return result
def _parse_routes(iface, opts):
'''
Filters given options and outputs valid settings for
the route settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
result = {}
if 'routes' not in opts:
_raise_error_routes(iface, 'routes', 'List of routes')
for opt in opts:
result[opt] = opts[opt]
return result
def _write_file(iface, data, folder, pattern):
'''
Writes a file to disk
'''
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
return filename
def _write_file_routes(iface, data, folder, pattern):
'''
Writes a file to disk
'''
# ifup / ifdown is executing given folder via run-parts.
# according to run-parts man-page, only filenames with this pattern are
# executed: (^[a-zA-Z0-9_-]+$)
# In order to make the routes file work for vlan interfaces
# (default would have been in example /etc/network/if-up.d/route-bond0.12)
# these dots in the iface name need to be replaced by underscores, so it
# can be executed by run-parts
iface = iface.replace('.', '_')
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
__salt__['file.set_mode'](filename, '0755')
return filename
def _write_file_network(data, filename, create=False):
'''
Writes a file to disk
If file does not exist, only create if create
argument is True
'''
if not os.path.exists(filename) and not create:
msg = '{0} cannot be written. {0} does not exist\
and create is set to False'
msg = msg.format(filename)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
def _read_temp(data):
'''
Return what would be written to disk
'''
tout = StringIO()
tout.write(data)
tout.seek(0)
output = tout.readlines()
tout.close()
return output
def _read_temp_ifaces(iface, data):
'''
Return what would be written to disk for interfaces
'''
try:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': data})
# Return as an array so the difflib works
return [item + '\n' for item in ifcfg.split('\n')]
def _write_file_ifaces(iface, data, **settings):
'''
Writes a file to disk
'''
try:
eth_template = JINJA.get_template('debian_eth.jinja')
source_template = JINJA.get_template('debian_source.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
# Read /etc/network/interfaces into a dict
adapters = _parse_interfaces()
# Apply supplied settings over on-disk settings
adapters[iface] = data
ifcfg = ''
for adapter in adapters:
if 'type' in adapters[adapter] and adapters[adapter]['type'] == 'source':
tmp = source_template.render({'name': adapter, 'data': adapters[adapter]})
else:
tmp = eth_template.render({'name': adapter, 'data': adapters[adapter]})
ifcfg = ifcfg + tmp
if adapter == iface:
saved_ifcfg = tmp
_SEPARATE_FILE = False
if 'filename' in settings:
if not settings['filename'].startswith('/'):
filename = '{0}/{1}'.format(_DEB_NETWORK_DIR, settings['filename'])
else:
filename = settings['filename']
_SEPARATE_FILE = True
else:
if 'filename' in adapters[adapter]['data']:
filename = adapters[adapter]['data']
else:
filename = _DEB_NETWORK_FILE
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
if _SEPARATE_FILE:
fout.write(salt.utils.stringutils.to_str(saved_ifcfg))
else:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return saved_ifcfg.split('\n')
def _write_file_ppp_ifaces(iface, data):
'''
Writes a file to disk
'''
try:
template = JINJA.get_template('debian_ppp_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_ppp_eth.jinja')
return ''
adapters = _parse_interfaces()
adapters[iface] = data
ifcfg = ''
tmp = template.render({'data': adapters[iface]})
ifcfg = tmp + ifcfg
filename = _DEB_PPP_DIR + '/' + adapters[iface]['data']['inet']['provider']
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.fopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return filename
def build_bond(iface, **settings):
'''
Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb
'''
deb_major = __grains__['osrelease'][:1]
opts = _parse_settings_bond(settings, iface)
try:
template = JINJA.get_template('conf.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template conf.jinja')
return ''
data = template.render({'name': iface, 'bonding': opts})
if 'test' in settings and settings['test']:
return _read_temp(data)
_write_file(iface, data, _DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
if deb_major == '5':
for line_type in ('alias', 'options'):
cmd = ['sed', '-i', '-e', r'/^{0}\s{1}.*/d'.format(line_type, iface),
'/etc/modprobe.conf']
__salt__['cmd.run'](cmd, python_shell=False)
__salt__['file.append']('/etc/modprobe.conf', path)
# Load kernel module
__salt__['kmod.load']('bonding')
# install ifenslave-2.6
__salt__['pkg.install']('ifenslave-2.6')
return _read_file(path)
def build_routes(iface, **settings):
'''
Add route scripts for a network interface using up commands.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
'''
opts = _parse_routes(iface, settings)
try:
template = JINJA.get_template('route_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template route_eth.jinja')
return ''
add_routecfg = template.render(route_type='add',
routes=opts['routes'],
iface=iface)
del_routecfg = template.render(route_type='del',
routes=opts['routes'],
iface=iface)
if 'test' in settings and settings['test']:
return _read_temp(add_routecfg + del_routecfg)
filename = _write_file_routes(iface,
add_routecfg,
_DEB_NETWORK_UP_DIR,
'route-{0}')
results = _read_file(filename)
filename = _write_file_routes(iface,
del_routecfg,
_DEB_NETWORK_DOWN_DIR,
'route-{0}')
results += _read_file(filename)
return results
def down(iface, iface_type):
'''
Shutdown a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.down eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought down.
if iface_type not in ['slave', 'source']:
return __salt__['cmd.run'](['ifdown', iface])
return None
def get_bond(iface):
'''
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
'''
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
return _read_file(path)
def get_interface(iface):
'''
Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
adapters = _parse_interfaces()
if iface in adapters:
try:
if iface == 'source':
template = JINJA.get_template('debian_source.jinja')
else:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': adapters[iface]})
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg.split('\n')]
else:
return []
def up(iface, iface_type): # pylint: disable=C0103
'''
Start up a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.up eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought up.
if iface_type not in ('slave', 'source'):
return __salt__['cmd.run'](['ifup', iface])
return None
def get_network_settings():
'''
Return the contents of the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_network_settings
'''
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
settings = {}
if __salt__['service.available']('networking'):
if __salt__['service.status']('networking'):
settings['networking'] = "yes"
else:
settings['networking'] = "no"
else:
settings['networking'] = "no"
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
settings['hostname'] = hostname
settings['domainname'] = domainname
settings['searchdomain'] = searchdomain
else:
settings = _parse_current_network_settings()
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(settings)
return _read_temp(network)
def get_routes(iface):
'''
Return the routes for the interface
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0
'''
filename = os.path.join(_DEB_NETWORK_UP_DIR, 'route-{0}'.format(iface))
results = _read_file(filename)
filename = os.path.join(_DEB_NETWORK_DOWN_DIR, 'route-{0}'.format(iface))
results += _read_file(filename)
return results
def apply_network_settings(**settings):
'''
Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings
'''
if 'require_reboot' not in settings:
settings['require_reboot'] = False
if 'apply_hostname' not in settings:
settings['apply_hostname'] = False
hostname_res = True
if settings['apply_hostname'] in _CONFIG_TRUE:
if 'hostname' in settings:
hostname_res = __salt__['network.mod_hostname'](settings['hostname'])
else:
log.warning(
'The network state sls is trying to apply hostname '
'changes but no hostname is defined.'
)
hostname_res = False
res = True
if settings['require_reboot'] in _CONFIG_TRUE:
log.warning(
'The network state sls is requiring a reboot of the system to '
'properly apply network configuration.'
)
res = True
else:
stop = __salt__['service.stop']('networking')
time.sleep(2)
res = stop and __salt__['service.start']('networking')
return hostname_res and res
def build_network_settings(**settings):
'''
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
'''
changes = []
# Read current configuration and store default values
current_network_settings = _parse_current_network_settings()
# Build settings
opts = _parse_network_settings(settings, current_network_settings)
# Ubuntu has moved away from /etc/default/networking
# beginning with the 12.04 release so we disable or enable
# the networking related services on boot
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
if opts['networking'] == 'yes':
service_cmd = 'service.enable'
else:
service_cmd = 'service.disable'
if __salt__['service.available']('NetworkManager'):
__salt__[service_cmd]('NetworkManager')
if __salt__['service.available']('networking'):
__salt__[service_cmd]('networking')
else:
try:
template = JINJA.get_template('network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template network.jinja')
return ''
network = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(network)
# Write settings
_write_file_network(network, _DEB_NETWORKING_FILE, True)
# Get hostname and domain from opts
sline = opts['hostname'].split('.', 1)
opts['hostname'] = sline[0]
current_domainname = current_network_settings['domainname']
current_searchdomain = current_network_settings['searchdomain']
new_domain = False
if len(sline) > 1:
new_domainname = sline[1]
if new_domainname != current_domainname:
domainname = new_domainname
opts['domainname'] = new_domainname
new_domain = True
else:
domainname = current_domainname
opts['domainname'] = domainname
else:
domainname = current_domainname
opts['domainname'] = domainname
new_search = False
if 'search' in opts:
new_searchdomain = opts['search']
if new_searchdomain != current_searchdomain:
searchdomain = new_searchdomain
opts['searchdomain'] = new_searchdomain
new_search = True
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
# If the domain changes, then we should write the resolv.conf file.
if new_domain or new_search:
# Look for existing domain line and update if necessary
resolve = _parse_resolve()
domain_prog = re.compile(r'domain\s+')
search_prog = re.compile(r'search\s+')
new_contents = []
for item in _read_file(_DEB_RESOLV_FILE):
if domain_prog.match(item):
item = 'domain {0}'.format(domainname)
elif search_prog.match(item):
item = 'search {0}'.format(searchdomain)
new_contents.append(item)
# A domain line didn't exist so we'll add one in
# with the new domainname
if 'domain' not in resolve:
new_contents.insert(0, 'domain {0}' . format(domainname))
# A search line didn't exist so we'll add one in
# with the new search domain
if 'search' not in resolve:
new_contents.insert('domain' in resolve, 'search {0}'.format(searchdomain))
new_resolv = '\n'.join(new_contents)
# Write /etc/resolv.conf
if not ('test' in settings and settings['test']):
_write_file_network(new_resolv, _DEB_RESOLV_FILE)
# used for returning the results back
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(opts)
changes.extend(_read_temp(network))
return changes
|
saltstack/salt
|
salt/modules/debian_ip.py
|
build_routes
|
python
|
def build_routes(iface, **settings):
'''
Add route scripts for a network interface using up commands.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
'''
opts = _parse_routes(iface, settings)
try:
template = JINJA.get_template('route_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template route_eth.jinja')
return ''
add_routecfg = template.render(route_type='add',
routes=opts['routes'],
iface=iface)
del_routecfg = template.render(route_type='del',
routes=opts['routes'],
iface=iface)
if 'test' in settings and settings['test']:
return _read_temp(add_routecfg + del_routecfg)
filename = _write_file_routes(iface,
add_routecfg,
_DEB_NETWORK_UP_DIR,
'route-{0}')
results = _read_file(filename)
filename = _write_file_routes(iface,
del_routecfg,
_DEB_NETWORK_DOWN_DIR,
'route-{0}')
results += _read_file(filename)
return results
|
Add route scripts for a network interface using up commands.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_ip.py#L1673-L1714
|
[
"def _read_file(path):\n '''\n Reads and returns the contents of a text file\n '''\n try:\n with salt.utils.files.flopen(path, 'rb') as contents:\n return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]\n except (OSError, IOError):\n return ''\n",
"def _parse_routes(iface, opts):\n '''\n Filters given options and outputs valid settings for\n the route settings file.\n '''\n # Normalize keys\n opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))\n result = {}\n if 'routes' not in opts:\n _raise_error_routes(iface, 'routes', 'List of routes')\n\n for opt in opts:\n result[opt] = opts[opt]\n\n return result\n",
"def _write_file_routes(iface, data, folder, pattern):\n '''\n Writes a file to disk\n '''\n # ifup / ifdown is executing given folder via run-parts.\n # according to run-parts man-page, only filenames with this pattern are\n # executed: (^[a-zA-Z0-9_-]+$)\n\n # In order to make the routes file work for vlan interfaces\n # (default would have been in example /etc/network/if-up.d/route-bond0.12)\n # these dots in the iface name need to be replaced by underscores, so it\n # can be executed by run-parts\n iface = iface.replace('.', '_')\n\n filename = os.path.join(folder, pattern.format(iface))\n if not os.path.exists(folder):\n msg = '{0} cannot be written. {1} does not exist'\n msg = msg.format(filename, folder)\n log.error(msg)\n raise AttributeError(msg)\n with salt.utils.files.flopen(filename, 'w') as fout:\n fout.write(salt.utils.stringutils.to_str(data))\n\n __salt__['file.set_mode'](filename, '0755')\n return filename\n",
"def _read_temp(data):\n '''\n Return what would be written to disk\n '''\n tout = StringIO()\n tout.write(data)\n tout.seek(0)\n output = tout.readlines()\n tout.close()\n\n return output\n"
] |
# -*- coding: utf-8 -*-
'''
The networking module for Debian-based distros
References:
* http://www.debian.org/doc/manuals/debian-reference/ch05.en.html
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import functools
import logging
import os.path
import os
import re
import time
# Import third party libs
import jinja2
import jinja2.exceptions
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error,no-name-in-module
# Import salt libs
import salt.utils.dns
import salt.utils.files
import salt.utils.odict
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.validate.net
# Set up logging
log = logging.getLogger(__name__)
# Set up template environment
JINJA = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'debian_ip')
)
)
# Define the module's virtual name
__virtualname__ = 'ip'
def __virtual__():
'''
Confine this module to Debian-based distros
'''
if __grains__['os_family'] == 'Debian':
return __virtualname__
return (False, 'The debian_ip module could not be loaded: '
'unsupported OS family')
_ETHTOOL_CONFIG_OPTS = {
'speed': 'link-speed',
'duplex': 'link-duplex',
'autoneg': 'ethernet-autoneg',
'ethernet-port': 'ethernet-port',
'wol': 'ethernet-wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'rx': 'offload-rx',
'tx': 'offload-tx',
'sg': 'offload-sg',
'tso': 'offload-tso',
'ufo': 'offload-ufo',
'gso': 'offload-gso',
'gro': 'offload-gro',
'lro': 'offload-lro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_REV_ETHTOOL_CONFIG_OPTS = {
'link-speed': 'speed',
'link-duplex': 'duplex',
'ethernet-autoneg': 'autoneg',
'ethernet-port': 'ethernet-port',
'ethernet-wol': 'wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'offload-rx': 'rx',
'offload-tx': 'tx',
'offload-sg': 'sg',
'offload-tso': 'tso',
'offload-ufo': 'ufo',
'offload-gso': 'gso',
'offload-lro': 'lro',
'offload-gro': 'gro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_DEB_CONFIG_PPPOE_OPTS = {
'user': 'user',
'password': 'password',
'provider': 'provider',
'pppoe_iface': 'pppoe_iface',
'noipdefault': 'noipdefault',
'usepeerdns': 'usepeerdns',
'defaultroute': 'defaultroute',
'holdoff': 'holdoff',
'maxfail': 'maxfail',
'hide-password': 'hide-password',
'lcp-echo-interval': 'lcp-echo-interval',
'lcp-echo-failure': 'lcp-echo-failure',
'connect': 'connect',
'noauth': 'noauth',
'persist': 'persist',
'mtu': 'mtu',
'noaccomp': 'noaccomp',
'linkname': 'linkname',
}
_DEB_ROUTES_FILE = '/etc/network/routes'
_DEB_NETWORK_FILE = '/etc/network/interfaces'
_DEB_NETWORK_DIR = '/etc/network/interfaces.d/'
_DEB_NETWORK_UP_DIR = '/etc/network/if-up.d/'
_DEB_NETWORK_DOWN_DIR = '/etc/network/if-down.d/'
_DEB_NETWORK_CONF_FILES = '/etc/modprobe.d/'
_DEB_NETWORKING_FILE = '/etc/default/networking'
_DEB_HOSTNAME_FILE = '/etc/hostname'
_DEB_RESOLV_FILE = '/etc/resolv.conf'
_DEB_PPP_DIR = '/etc/ppp/peers/'
_CONFIG_TRUE = ['yes', 'on', 'true', '1', True]
_CONFIG_FALSE = ['no', 'off', 'false', '0', False]
_IFACE_TYPES = [
'eth', 'bond', 'alias', 'clone',
'ipsec', 'dialup', 'bridge', 'slave',
'vlan', 'pppoe', 'source',
]
def _error_msg_iface(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, '|'.join(str(e) for e in expected))
def _error_msg_routes(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, expected)
def _log_default_iface(iface, opt, value):
log.info(
'Using default option -- Interface: %s Option: %s Value: %s',
iface, opt, value
)
def _error_msg_network(option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]'
return msg.format(option, '|'.join(str(e) for e in expected))
def _log_default_network(opt, value):
log.info('Using existing setting -- Setting: %s Value: %s', opt, value)
def _raise_error_iface(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_iface(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_network(option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_network(option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_routes(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_routes(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _read_file(path):
'''
Reads and returns the contents of a text file
'''
try:
with salt.utils.files.flopen(path, 'rb') as contents:
return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]
except (OSError, IOError):
return ''
def _parse_resolve():
'''
Parse /etc/resolv.conf
'''
return salt.utils.dns.parse_resolv(_DEB_RESOLV_FILE)
def _parse_domainname():
'''
Parse /etc/resolv.conf and return domainname
'''
return _parse_resolve().get('domain', '')
def _parse_searchdomain():
'''
Parse /etc/resolv.conf and return searchdomain
'''
return _parse_resolve().get('search', '')
def _parse_hostname():
'''
Parse /etc/hostname and return hostname
'''
contents = _read_file(_DEB_HOSTNAME_FILE)
if contents:
return contents[0].split('\n')[0]
else:
return ''
def _parse_current_network_settings():
'''
Parse /etc/default/networking and return current configuration
'''
opts = salt.utils.odict.OrderedDict()
opts['networking'] = ''
if os.path.isfile(_DEB_NETWORKING_FILE):
with salt.utils.files.fopen(_DEB_NETWORKING_FILE) as contents:
for line in contents:
salt.utils.stringutils.to_unicode(line)
if line.startswith('#'):
continue
elif line.startswith('CONFIGURE_INTERFACES'):
opts['networking'] = line.split('=', 1)[1].strip()
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
opts['hostname'] = hostname
opts['domainname'] = domainname
opts['searchdomain'] = searchdomain
return opts
# def __validator_func(value):
# return (valid: True/False, (transformed) value, error message)
def __ipv4_quad(value):
'''validate an IPv4 address'''
return (salt.utils.validate.net.ipv4_addr(value), value,
'dotted IPv4 address')
def __ipv6(value):
'''validate an IPv6 address'''
return (salt.utils.validate.net.ipv6_addr(value), value,
'IPv6 address')
def __mac(value):
'''validate a mac address'''
return (salt.utils.validate.net.mac(value), value,
'MAC address')
def __anything(value):
return (True, value, None)
def __int(value):
'''validate an integer'''
valid, _value = False, value
try:
_value = int(value)
valid = True
except ValueError:
pass
return (valid, _value, 'integer')
def __float(value):
'''validate a float'''
valid, _value = False, value
try:
_value = float(value)
valid = True
except ValueError:
pass
return (valid, _value, 'float')
def __ipv4_netmask(value):
'''validate an IPv4 dotted quad or integer CIDR netmask'''
valid, errmsg = False, 'dotted quad or integer CIDR (0->32)'
valid, value, _ = __int(value)
if not (valid and 0 <= value <= 32):
valid = salt.utils.validate.net.netmask(value)
return (valid, value, errmsg)
def __ipv6_netmask(value):
'''validate an IPv6 integer netmask'''
valid, errmsg = False, 'IPv6 netmask (0->128)'
valid, value, _ = __int(value)
valid = (valid and 0 <= value <= 128)
return (valid, value, errmsg)
def __within2(value, within=None, errmsg=None, dtype=None):
'''validate that a value is in ``within`` and optionally a ``dtype``'''
valid, _value = False, value
if dtype:
try:
_value = dtype(value) # TODO: this is a bit loose when dtype is a class
valid = _value in within
except ValueError:
pass
else:
valid = _value in within
if errmsg is None:
if dtype:
typename = getattr(dtype, '__name__',
hasattr(dtype, '__class__')
and getattr(dtype.__class__, 'name', dtype))
errmsg = '{0} within \'{1}\''.format(typename, within)
else:
errmsg = 'within \'{0}\''.format(within)
return (valid, _value, errmsg)
def __within(within=None, errmsg=None, dtype=None):
return functools.partial(__within2, within=within,
errmsg=errmsg, dtype=dtype)
def __space_delimited_list(value):
'''validate that a value contains one or more space-delimited values'''
if isinstance(value, six.string_types):
value = value.strip().split()
if hasattr(value, '__iter__') and value != []:
return (True, value, 'space-delimited string')
else:
return (False, value, '{0} is not a valid space-delimited value.\n'.format(value))
SALT_ATTR_TO_DEBIAN_ATTR_MAP = {
'dns': 'dns-nameservers',
'search': 'dns-search',
'hwaddr': 'hwaddress', # TODO: this limits bootp functionality
'ipaddr': 'address',
'ipaddrs': 'addresses',
}
DEBIAN_ATTR_TO_SALT_ATTR_MAP = dict(
(v, k) for (k, v) in six.iteritems(SALT_ATTR_TO_DEBIAN_ATTR_MAP))
# TODO
DEBIAN_ATTR_TO_SALT_ATTR_MAP['address'] = 'address'
DEBIAN_ATTR_TO_SALT_ATTR_MAP['hwaddress'] = 'hwaddress'
IPV4_VALID_PROTO = ['bootp', 'dhcp', 'static', 'manual', 'loopback', 'ppp']
IPV4_ATTR_MAP = {
'proto': __within(IPV4_VALID_PROTO, dtype=six.text_type),
# ipv4 static & manual
'address': __ipv4_quad,
'addresses': __anything,
'netmask': __ipv4_netmask,
'broadcast': __ipv4_quad,
'metric': __int,
'gateway': __ipv4_quad, # supports a colon-delimited list
'pointopoint': __ipv4_quad,
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'link', 'host'], dtype=six.text_type),
# dhcp
'hostname': __anything,
'leasehours': __int,
'leasetime': __int,
'vendor': __anything,
'client': __anything,
# bootp
'bootfile': __anything,
'server': __ipv4_quad,
'hwaddr': __mac,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'dstaddr': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# bond
'slaves': __anything,
# ppp
'provider': __anything,
'unit': __int,
'options': __anything,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
#
'network': __anything, # i don't know what this is
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
IPV6_VALID_PROTO = ['auto', 'loopback', 'static', 'manual',
'dhcp', 'v4tunnel', '6to4']
IPV6_ATTR_MAP = {
'proto': __within(IPV6_VALID_PROTO),
# ipv6 static & manual
'address': __ipv6,
'addresses': __anything,
'netmask': __ipv6_netmask,
'broadcast': __ipv6,
'gateway': __ipv6, # supports a colon-delimited list
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'site', 'link', 'host'], dtype=six.text_type),
# inet6 auto
'privext': __within([0, 1, 2], dtype=int),
'dhcp': __within([0, 1], dtype=int),
# inet6 static & manual & dhcp
'media': __anything,
'accept_ra': __within([0, 1], dtype=int),
'autoconf': __within([0, 1], dtype=int),
'preferred-lifetime': __int,
'dad-attempts': __int, # 0 to disable
'dad-interval': __float,
# bond
'slaves': __anything,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
WIRELESS_ATTR_MAP = {
'wireless-essid': __anything,
'wireless-mode': __anything, # TODO
'wpa-ap-scan': __within([0, 1, 2], dtype=int), # TODO
'wpa-conf': __anything,
'wpa-driver': __anything,
'wpa-group': __anything,
'wpa-key-mgmt': __anything,
'wpa-pairwise': __anything,
'wpa-psk': __anything,
'wpa-proto': __anything, # partial(__within,
'wpa-roam': __anything,
'wpa-ssid': __anything, # TODO
}
ATTRMAPS = {
'inet': [IPV4_ATTR_MAP, WIRELESS_ATTR_MAP],
'inet6': [IPV6_ATTR_MAP, WIRELESS_ATTR_MAP]
}
def _validate_interface_option(attr, value, addrfam='inet'):
'''lookup the validation function for a [addrfam][attr] and
return the results
:param attr: attribute name
:param value: raw setting value
:param addrfam: address family (inet, inet6,
'''
valid, _value, errmsg = False, value, 'Unknown validator'
attrmaps = ATTRMAPS.get(addrfam, [])
for attrmap in attrmaps:
if attr in attrmap:
validate_func = attrmap[attr]
(valid, _value, errmsg) = validate_func(value)
break
return (valid, _value, errmsg)
def _attrmaps_contain_attr(attr):
return (
attr in WIRELESS_ATTR_MAP or
attr in IPV4_ATTR_MAP or
attr in IPV6_ATTR_MAP)
def _parse_interfaces(interface_files=None):
'''
Parse /etc/network/interfaces and return current configured interfaces
'''
if interface_files is None:
interface_files = []
# Add this later.
if os.path.exists(_DEB_NETWORK_DIR):
interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]
if os.path.isfile(_DEB_NETWORK_FILE):
interface_files.insert(0, _DEB_NETWORK_FILE)
adapters = salt.utils.odict.OrderedDict()
method = -1
for interface_file in interface_files:
with salt.utils.files.fopen(interface_file) as interfaces:
# This ensures iface_dict exists, but does not ensure we're not reading a new interface.
iface_dict = {}
for line in interfaces:
line = salt.utils.stringutils.to_unicode(line)
# Identify the clauses by the first word of each line.
# Go to the next line if the current line is a comment
# or all spaces.
if line.lstrip().startswith('#') or line.isspace():
continue
# Parse the iface clause
if line.startswith('iface'):
sline = line.split()
if len(sline) != 4:
msg = 'Interface file malformed: {0}.'
msg = msg.format(sline)
log.error(msg)
raise AttributeError(msg)
iface_name = sline[1]
addrfam = sline[2]
method = sline[3]
# Create item in dict, if not already there
if iface_name not in adapters:
adapters[iface_name] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters[iface_name]:
adapters[iface_name]['data'] = salt.utils.odict.OrderedDict()
if addrfam not in adapters[iface_name]['data']:
adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict()
iface_dict = adapters[iface_name]['data'][addrfam]
iface_dict['addrfam'] = addrfam
iface_dict['proto'] = method
iface_dict['filename'] = interface_file
# Parse the detail clauses.
elif line[0].isspace():
sline = line.split()
# conf file attr: dns-nameservers
# salt states.network attr: dns
attr, valuestr = line.rstrip().split(None, 1)
if _attrmaps_contain_attr(attr):
if '-' in attr:
attrname = attr.replace('-', '_')
else:
attrname = attr
(valid, value, errmsg) = _validate_interface_option(
attr, valuestr, addrfam)
if attrname == 'address' and 'address' in iface_dict:
if 'addresses' not in iface_dict:
iface_dict['addresses'] = []
iface_dict['addresses'].append(value)
else:
iface_dict[attrname] = value
elif attr in _REV_ETHTOOL_CONFIG_OPTS:
if 'ethtool' not in iface_dict:
iface_dict['ethtool'] = salt.utils.odict.OrderedDict()
iface_dict['ethtool'][attr] = valuestr
elif attr.startswith('bond'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bonding' not in iface_dict:
iface_dict['bonding'] = salt.utils.odict.OrderedDict()
iface_dict['bonding'][opt] = valuestr
elif attr.startswith('bridge'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bridging' not in iface_dict:
iface_dict['bridging'] = salt.utils.odict.OrderedDict()
iface_dict['bridging'][opt] = valuestr
elif attr in ['up', 'pre-up', 'post-up',
'down', 'pre-down', 'post-down']:
cmd = valuestr
cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr))
if cmd_key not in iface_dict:
iface_dict[cmd_key] = []
iface_dict[cmd_key].append(cmd)
elif line.startswith('auto'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['enabled'] = True
elif line.startswith('allow-hotplug'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['hotplug'] = True
elif line.startswith('source'):
if 'source' not in adapters:
adapters['source'] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters['source']:
adapters['source']['data'] = salt.utils.odict.OrderedDict()
adapters['source']['data']['sources'] = []
adapters['source']['data']['sources'].append(line.split()[1])
# Return a sorted list of the keys for bond, bridge and ethtool options to
# ensure a consistent order
for iface_name in adapters:
if iface_name == 'source':
continue
if 'data' not in adapters[iface_name]:
msg = 'Interface file malformed for interface: {0}.'.format(iface_name)
log.error(msg)
adapters.pop(iface_name)
continue
for opt in ['ethtool', 'bonding', 'bridging']:
for inet in ['inet', 'inet6']:
if inet in adapters[iface_name]['data']:
if opt in adapters[iface_name]['data'][inet]:
opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys())
adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys
return adapters
def _parse_ethtool_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
if 'autoneg' in opts:
if opts['autoneg'] in _CONFIG_TRUE:
config.update({'autoneg': 'on'})
elif opts['autoneg'] in _CONFIG_FALSE:
config.update({'autoneg': 'off'})
else:
_raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE)
if 'duplex' in opts:
valid = ['full', 'half']
if opts['duplex'] in valid:
config.update({'duplex': opts['duplex']})
else:
_raise_error_iface(iface, 'duplex', valid)
if 'speed' in opts:
valid = ['10', '100', '1000', '10000']
if six.text_type(opts['speed']) in valid:
config.update({'speed': opts['speed']})
else:
_raise_error_iface(iface, opts['speed'], valid)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'on'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'off'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_ethtool_pppoe_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
for opt in _DEB_CONFIG_PPPOE_OPTS:
if opt in opts:
config[opt] = opts[opt]
if 'provider' in opts and not opts['provider']:
_raise_error_iface(iface, 'provider', _CONFIG_TRUE + _CONFIG_FALSE)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('noipdefault', 'usepeerdns', 'defaultroute', 'hide-password', 'noauth', 'persist', 'noaccomp'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'True'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'False'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_settings_bond(opts, iface):
'''
Filters given options and outputs valid settings for requested
operation. If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond_def = {
# 803.ad aggregation selection logic
# 0 for stable (default)
# 1 for bandwidth
# 2 for count
'ad_select': '0',
# Max number of transmit queues (default = 16)
'tx_queues': '16',
# Link monitoring in milliseconds. Most NICs support this
'miimon': '100',
# ARP interval in milliseconds
'arp_interval': '250',
# Delay before considering link down in milliseconds (miimon * 2)
'downdelay': '200',
# lacp_rate 0: Slow - every 30 seconds
# lacp_rate 1: Fast - every 1 second
'lacp_rate': '0',
# Max bonds for this driver
'max_bonds': '1',
# Specifies the time, in milliseconds, to wait before
# enabling a slave after a link recovery has been
# detected. Only used with miimon.
'updelay': '0',
# Used with miimon.
# On: driver sends mii
# Off: ethtool sends mii
'use_carrier': 'on',
# Default. Don't change unless you know what you are doing.
'xmit_hash_policy': 'layer2',
}
if opts['mode'] in ['balance-rr', '0']:
log.info('Device: %s Bonding Mode: load balancing (round-robin)', iface)
return _parse_settings_bond_0(opts, iface, bond_def)
elif opts['mode'] in ['active-backup', '1']:
log.info('Device: %s Bonding Mode: fault-tolerance (active-backup)', iface)
return _parse_settings_bond_1(opts, iface, bond_def)
elif opts['mode'] in ['balance-xor', '2']:
log.info('Device: %s Bonding Mode: load balancing (xor)', iface)
return _parse_settings_bond_2(opts, iface, bond_def)
elif opts['mode'] in ['broadcast', '3']:
log.info('Device: %s Bonding Mode: fault-tolerance (broadcast)', iface)
return _parse_settings_bond_3(opts, iface, bond_def)
elif opts['mode'] in ['802.3ad', '4']:
log.info('Device: %s Bonding Mode: IEEE 802.3ad Dynamic link '
'aggregation', iface)
return _parse_settings_bond_4(opts, iface, bond_def)
elif opts['mode'] in ['balance-tlb', '5']:
log.info('Device: %s Bonding Mode: transmit load balancing', iface)
return _parse_settings_bond_5(opts, iface, bond_def)
elif opts['mode'] in ['balance-alb', '6']:
log.info('Device: %s Bonding Mode: adaptive load balancing', iface)
return _parse_settings_bond_6(opts, iface, bond_def)
else:
valid = [
'0', '1', '2', '3', '4', '5', '6',
'balance-rr', 'active-backup', 'balance-xor',
'broadcast', '802.3ad', 'balance-tlb', 'balance-alb'
]
_raise_error_iface(iface, 'mode', valid)
def _parse_settings_bond_0(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond0.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '0'}
# ARP targets in n.n.n.n form
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
return bond
def _parse_settings_bond_1(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '1'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
if not (__grains__['os'] == "Ubuntu" and __grains__['osrelease_info'][0] >= 16):
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_2(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond2.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '2'}
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_3(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond3.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '3'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_4(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond4.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '4'}
for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']:
if binding in opts:
if binding == 'lacp_rate':
if opts[binding] == 'fast':
opts.update({binding: '1'})
if opts[binding] == 'slow':
opts.update({binding: '0'})
valid = ['fast', '1', 'slow', '0']
else:
valid = ['integer']
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, valid)
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_5(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond5.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '5'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_settings_bond_6(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond6.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '6'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_bridge_opts(opts, iface):
'''
Filters given options and outputs valid settings for BRIDGING_OPTS
If an option has a value that is not expected, this
function will log the Interface, Setting and what was expected.
'''
config = {}
if 'ports' in opts:
if isinstance(opts['ports'], list):
opts['ports'] = ' '.join(opts['ports'])
config.update({'ports': opts['ports']})
for opt in ['ageing', 'fd', 'gcint', 'hello', 'maxage']:
if opt in opts:
try:
float(opts[opt])
config.update({opt: opts[opt]})
except ValueError:
_raise_error_iface(iface, opt, ['float'])
for opt in ['bridgeprio', 'maxwait']:
if opt in opts:
if isinstance(opts[opt], int):
config.update({opt: opts[opt]})
else:
_raise_error_iface(iface, opt, ['integer'])
if 'hw' in opts:
# match 12 hex digits with either : or - as separators between pairs
if re.match('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$',
opts['hw'].lower()):
config.update({'hw': opts['hw']})
else:
_raise_error_iface(iface, 'hw', ['valid MAC address'])
for opt in ['pathcost', 'portprio']:
if opt in opts:
try:
port, cost_or_prio = opts[opt].split()
int(cost_or_prio)
config.update({opt: '{0} {1}'.format(port, cost_or_prio)})
except ValueError:
_raise_error_iface(iface, opt, ['interface integer'])
if 'stp' in opts:
if opts['stp'] in _CONFIG_TRUE:
config.update({'stp': 'on'})
elif opts['stp'] in _CONFIG_FALSE:
config.update({'stp': 'off'})
else:
_raise_error_iface(iface, 'stp', _CONFIG_TRUE + _CONFIG_FALSE)
if 'waitport' in opts:
if isinstance(opts['waitport'], int):
config.update({'waitport': opts['waitport']})
else:
values = opts['waitport'].split()
waitport_time = values.pop(0)
if waitport_time.isdigit() and values:
config.update({
'waitport': '{0} {1}'.format(
waitport_time, ' '.join(values)
)
})
else:
_raise_error_iface(iface, opt, ['integer [interfaces]'])
return config
def _parse_settings_eth(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['inet'] = salt.utils.odict.OrderedDict()
iface_data['inet6'] = salt.utils.odict.OrderedDict()
if enabled:
adapters[iface]['enabled'] = True
if opts.get('hotplug', False):
adapters[iface]['hotplug'] = True
if opts.get('enable_ipv6', None) and opts.get('iface_type', '') == 'vlan':
iface_data['inet6']['vlan_raw_device'] = (
re.sub(r'\.\d*', '', iface))
for addrfam in ['inet', 'inet6']:
if iface_type not in ['bridge']:
tmp_ethtool = _parse_ethtool_opts(opts, iface)
if tmp_ethtool:
ethtool = {}
for item in tmp_ethtool:
ethtool[_ETHTOOL_CONFIG_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['ethtool'] = ethtool
# return a list of sorted keys to ensure consistent order
iface_data[addrfam]['ethtool_keys'] = sorted(ethtool)
if iface_type == 'bridge':
bridging = _parse_bridge_opts(opts, iface)
if bridging:
iface_data[addrfam]['bridging'] = bridging
iface_data[addrfam]['bridging_keys'] = sorted(bridging)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'bond':
bonding = _parse_settings_bond(opts, iface)
if bonding:
iface_data[addrfam]['bonding'] = bonding
iface_data[addrfam]['bonding']['slaves'] = opts['slaves']
iface_data[addrfam]['bonding_keys'] = sorted(bonding)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'slave':
adapters[iface]['master'] = opts['master']
opts['proto'] = 'manual'
iface_data[addrfam]['master'] = adapters[iface]['master']
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'vlan':
iface_data[addrfam]['vlan_raw_device'] = re.sub(r'\.\d*', '', iface)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'pppoe':
tmp_ethtool = _parse_ethtool_pppoe_opts(opts, iface)
if tmp_ethtool:
for item in tmp_ethtool:
adapters[iface]['data'][addrfam][_DEB_CONFIG_PPPOE_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['addrfam'] = addrfam
opts.pop('mode', None)
for opt, val in opts.items():
inet = None
if opt.startswith('ipv4'):
opt = opt[4:]
inet = 'inet'
iface_data['inet']['addrfam'] = 'inet'
elif opt.startswith('ipv6'):
iface_data['inet6']['addrfam'] = 'inet6'
opt = opt[4:]
inet = 'inet6'
elif opt in ['ipaddr', 'address', 'ipaddresses', 'addresses', 'gateway', 'proto']:
iface_data['inet']['addrfam'] = 'inet'
inet = 'inet'
_opt = SALT_ATTR_TO_DEBIAN_ATTR_MAP.get(opt, opt)
_debopt = _opt.replace('-', '_')
for addrfam in ['inet', 'inet6']:
(valid, value, errmsg) = _validate_interface_option(_opt, val, addrfam=addrfam)
if not valid:
continue
if inet is None and _debopt not in iface_data[addrfam]:
iface_data[addrfam][_debopt] = value
elif inet == addrfam:
iface_data[addrfam][_debopt] = value
for opt in ['up_cmds', 'pre_up_cmds', 'post_up_cmds',
'down_cmds', 'pre_down_cmds', 'post_down_cmds']:
if opt in opts:
iface_data['inet'][opt] = opts[opt]
iface_data['inet6'][opt] = opts[opt]
# Remove incomplete/disabled inet blocks
for (addrfam, opt) in [('inet', 'enable_ipv4'), ('inet6', 'enable_ipv6')]:
if opts.get(opt, None) is False:
iface_data.pop(addrfam)
elif iface_data[addrfam].get('addrfam', '') != addrfam:
iface_data.pop(addrfam)
return adapters
def _parse_settings_source(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['sources'] = [opts['source']]
return adapters
def _parse_network_settings(opts, current):
'''
Filters given options and outputs valid settings for
the global network settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
current = dict((k.lower(), v) for (k, v) in six.iteritems(current))
result = {}
valid = _CONFIG_TRUE + _CONFIG_FALSE
if 'enabled' not in opts:
try:
opts['networking'] = current['networking']
_log_default_network('networking', current['networking'])
except ValueError:
_raise_error_network('networking', valid)
else:
opts['networking'] = opts['enabled']
if opts['networking'] in valid:
if opts['networking'] in _CONFIG_TRUE:
result['networking'] = 'yes'
elif opts['networking'] in _CONFIG_FALSE:
result['networking'] = 'no'
else:
_raise_error_network('networking', valid)
if 'hostname' not in opts:
try:
opts['hostname'] = current['hostname']
_log_default_network('hostname', current['hostname'])
except ValueError:
_raise_error_network('hostname', ['server1.example.com'])
if opts['hostname']:
result['hostname'] = opts['hostname']
else:
_raise_error_network('hostname', ['server1.example.com'])
if 'search' in opts:
result['search'] = opts['search']
return result
def _parse_routes(iface, opts):
'''
Filters given options and outputs valid settings for
the route settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
result = {}
if 'routes' not in opts:
_raise_error_routes(iface, 'routes', 'List of routes')
for opt in opts:
result[opt] = opts[opt]
return result
def _write_file(iface, data, folder, pattern):
'''
Writes a file to disk
'''
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
return filename
def _write_file_routes(iface, data, folder, pattern):
'''
Writes a file to disk
'''
# ifup / ifdown is executing given folder via run-parts.
# according to run-parts man-page, only filenames with this pattern are
# executed: (^[a-zA-Z0-9_-]+$)
# In order to make the routes file work for vlan interfaces
# (default would have been in example /etc/network/if-up.d/route-bond0.12)
# these dots in the iface name need to be replaced by underscores, so it
# can be executed by run-parts
iface = iface.replace('.', '_')
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
__salt__['file.set_mode'](filename, '0755')
return filename
def _write_file_network(data, filename, create=False):
'''
Writes a file to disk
If file does not exist, only create if create
argument is True
'''
if not os.path.exists(filename) and not create:
msg = '{0} cannot be written. {0} does not exist\
and create is set to False'
msg = msg.format(filename)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
def _read_temp(data):
'''
Return what would be written to disk
'''
tout = StringIO()
tout.write(data)
tout.seek(0)
output = tout.readlines()
tout.close()
return output
def _read_temp_ifaces(iface, data):
'''
Return what would be written to disk for interfaces
'''
try:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': data})
# Return as an array so the difflib works
return [item + '\n' for item in ifcfg.split('\n')]
def _write_file_ifaces(iface, data, **settings):
'''
Writes a file to disk
'''
try:
eth_template = JINJA.get_template('debian_eth.jinja')
source_template = JINJA.get_template('debian_source.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
# Read /etc/network/interfaces into a dict
adapters = _parse_interfaces()
# Apply supplied settings over on-disk settings
adapters[iface] = data
ifcfg = ''
for adapter in adapters:
if 'type' in adapters[adapter] and adapters[adapter]['type'] == 'source':
tmp = source_template.render({'name': adapter, 'data': adapters[adapter]})
else:
tmp = eth_template.render({'name': adapter, 'data': adapters[adapter]})
ifcfg = ifcfg + tmp
if adapter == iface:
saved_ifcfg = tmp
_SEPARATE_FILE = False
if 'filename' in settings:
if not settings['filename'].startswith('/'):
filename = '{0}/{1}'.format(_DEB_NETWORK_DIR, settings['filename'])
else:
filename = settings['filename']
_SEPARATE_FILE = True
else:
if 'filename' in adapters[adapter]['data']:
filename = adapters[adapter]['data']
else:
filename = _DEB_NETWORK_FILE
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
if _SEPARATE_FILE:
fout.write(salt.utils.stringutils.to_str(saved_ifcfg))
else:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return saved_ifcfg.split('\n')
def _write_file_ppp_ifaces(iface, data):
'''
Writes a file to disk
'''
try:
template = JINJA.get_template('debian_ppp_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_ppp_eth.jinja')
return ''
adapters = _parse_interfaces()
adapters[iface] = data
ifcfg = ''
tmp = template.render({'data': adapters[iface]})
ifcfg = tmp + ifcfg
filename = _DEB_PPP_DIR + '/' + adapters[iface]['data']['inet']['provider']
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.fopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return filename
def build_bond(iface, **settings):
'''
Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb
'''
deb_major = __grains__['osrelease'][:1]
opts = _parse_settings_bond(settings, iface)
try:
template = JINJA.get_template('conf.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template conf.jinja')
return ''
data = template.render({'name': iface, 'bonding': opts})
if 'test' in settings and settings['test']:
return _read_temp(data)
_write_file(iface, data, _DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
if deb_major == '5':
for line_type in ('alias', 'options'):
cmd = ['sed', '-i', '-e', r'/^{0}\s{1}.*/d'.format(line_type, iface),
'/etc/modprobe.conf']
__salt__['cmd.run'](cmd, python_shell=False)
__salt__['file.append']('/etc/modprobe.conf', path)
# Load kernel module
__salt__['kmod.load']('bonding')
# install ifenslave-2.6
__salt__['pkg.install']('ifenslave-2.6')
return _read_file(path)
def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'vlan':
settings['vlan'] = 'yes'
__salt__['pkg.install']('vlan')
elif iface_type == 'pppoe':
settings['pppoe'] = 'yes'
if not __salt__['pkg.version']('ppp'):
inst = __salt__['pkg.install']('ppp')
elif iface_type == 'bond':
if 'slaves' not in settings:
msg = 'slaves is a required setting for bond interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'bridge':
if 'ports' not in settings:
msg = (
'ports is a required setting for bridge interfaces on Debian '
'or Ubuntu based systems'
)
log.error(msg)
raise AttributeError(msg)
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'pppoe']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
if iface_type in ['source']:
opts = _parse_settings_source(settings, iface_type, enabled, iface)
if 'test' in settings and settings['test']:
return _read_temp_ifaces(iface, opts[iface])
ifcfg = _write_file_ifaces(iface, opts[iface], **settings)
if iface_type == 'pppoe':
_write_file_ppp_ifaces(iface, opts[iface])
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg]
def down(iface, iface_type):
'''
Shutdown a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.down eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought down.
if iface_type not in ['slave', 'source']:
return __salt__['cmd.run'](['ifdown', iface])
return None
def get_bond(iface):
'''
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
'''
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
return _read_file(path)
def get_interface(iface):
'''
Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
adapters = _parse_interfaces()
if iface in adapters:
try:
if iface == 'source':
template = JINJA.get_template('debian_source.jinja')
else:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': adapters[iface]})
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg.split('\n')]
else:
return []
def up(iface, iface_type): # pylint: disable=C0103
'''
Start up a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.up eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought up.
if iface_type not in ('slave', 'source'):
return __salt__['cmd.run'](['ifup', iface])
return None
def get_network_settings():
'''
Return the contents of the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_network_settings
'''
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
settings = {}
if __salt__['service.available']('networking'):
if __salt__['service.status']('networking'):
settings['networking'] = "yes"
else:
settings['networking'] = "no"
else:
settings['networking'] = "no"
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
settings['hostname'] = hostname
settings['domainname'] = domainname
settings['searchdomain'] = searchdomain
else:
settings = _parse_current_network_settings()
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(settings)
return _read_temp(network)
def get_routes(iface):
'''
Return the routes for the interface
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0
'''
filename = os.path.join(_DEB_NETWORK_UP_DIR, 'route-{0}'.format(iface))
results = _read_file(filename)
filename = os.path.join(_DEB_NETWORK_DOWN_DIR, 'route-{0}'.format(iface))
results += _read_file(filename)
return results
def apply_network_settings(**settings):
'''
Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings
'''
if 'require_reboot' not in settings:
settings['require_reboot'] = False
if 'apply_hostname' not in settings:
settings['apply_hostname'] = False
hostname_res = True
if settings['apply_hostname'] in _CONFIG_TRUE:
if 'hostname' in settings:
hostname_res = __salt__['network.mod_hostname'](settings['hostname'])
else:
log.warning(
'The network state sls is trying to apply hostname '
'changes but no hostname is defined.'
)
hostname_res = False
res = True
if settings['require_reboot'] in _CONFIG_TRUE:
log.warning(
'The network state sls is requiring a reboot of the system to '
'properly apply network configuration.'
)
res = True
else:
stop = __salt__['service.stop']('networking')
time.sleep(2)
res = stop and __salt__['service.start']('networking')
return hostname_res and res
def build_network_settings(**settings):
'''
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
'''
changes = []
# Read current configuration and store default values
current_network_settings = _parse_current_network_settings()
# Build settings
opts = _parse_network_settings(settings, current_network_settings)
# Ubuntu has moved away from /etc/default/networking
# beginning with the 12.04 release so we disable or enable
# the networking related services on boot
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
if opts['networking'] == 'yes':
service_cmd = 'service.enable'
else:
service_cmd = 'service.disable'
if __salt__['service.available']('NetworkManager'):
__salt__[service_cmd]('NetworkManager')
if __salt__['service.available']('networking'):
__salt__[service_cmd]('networking')
else:
try:
template = JINJA.get_template('network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template network.jinja')
return ''
network = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(network)
# Write settings
_write_file_network(network, _DEB_NETWORKING_FILE, True)
# Get hostname and domain from opts
sline = opts['hostname'].split('.', 1)
opts['hostname'] = sline[0]
current_domainname = current_network_settings['domainname']
current_searchdomain = current_network_settings['searchdomain']
new_domain = False
if len(sline) > 1:
new_domainname = sline[1]
if new_domainname != current_domainname:
domainname = new_domainname
opts['domainname'] = new_domainname
new_domain = True
else:
domainname = current_domainname
opts['domainname'] = domainname
else:
domainname = current_domainname
opts['domainname'] = domainname
new_search = False
if 'search' in opts:
new_searchdomain = opts['search']
if new_searchdomain != current_searchdomain:
searchdomain = new_searchdomain
opts['searchdomain'] = new_searchdomain
new_search = True
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
# If the domain changes, then we should write the resolv.conf file.
if new_domain or new_search:
# Look for existing domain line and update if necessary
resolve = _parse_resolve()
domain_prog = re.compile(r'domain\s+')
search_prog = re.compile(r'search\s+')
new_contents = []
for item in _read_file(_DEB_RESOLV_FILE):
if domain_prog.match(item):
item = 'domain {0}'.format(domainname)
elif search_prog.match(item):
item = 'search {0}'.format(searchdomain)
new_contents.append(item)
# A domain line didn't exist so we'll add one in
# with the new domainname
if 'domain' not in resolve:
new_contents.insert(0, 'domain {0}' . format(domainname))
# A search line didn't exist so we'll add one in
# with the new search domain
if 'search' not in resolve:
new_contents.insert('domain' in resolve, 'search {0}'.format(searchdomain))
new_resolv = '\n'.join(new_contents)
# Write /etc/resolv.conf
if not ('test' in settings and settings['test']):
_write_file_network(new_resolv, _DEB_RESOLV_FILE)
# used for returning the results back
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(opts)
changes.extend(_read_temp(network))
return changes
|
saltstack/salt
|
salt/modules/debian_ip.py
|
get_bond
|
python
|
def get_bond(iface):
'''
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
'''
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
return _read_file(path)
|
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_ip.py#L1734-L1745
|
[
"def _read_file(path):\n '''\n Reads and returns the contents of a text file\n '''\n try:\n with salt.utils.files.flopen(path, 'rb') as contents:\n return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]\n except (OSError, IOError):\n return ''\n"
] |
# -*- coding: utf-8 -*-
'''
The networking module for Debian-based distros
References:
* http://www.debian.org/doc/manuals/debian-reference/ch05.en.html
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import functools
import logging
import os.path
import os
import re
import time
# Import third party libs
import jinja2
import jinja2.exceptions
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error,no-name-in-module
# Import salt libs
import salt.utils.dns
import salt.utils.files
import salt.utils.odict
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.validate.net
# Set up logging
log = logging.getLogger(__name__)
# Set up template environment
JINJA = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'debian_ip')
)
)
# Define the module's virtual name
__virtualname__ = 'ip'
def __virtual__():
'''
Confine this module to Debian-based distros
'''
if __grains__['os_family'] == 'Debian':
return __virtualname__
return (False, 'The debian_ip module could not be loaded: '
'unsupported OS family')
_ETHTOOL_CONFIG_OPTS = {
'speed': 'link-speed',
'duplex': 'link-duplex',
'autoneg': 'ethernet-autoneg',
'ethernet-port': 'ethernet-port',
'wol': 'ethernet-wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'rx': 'offload-rx',
'tx': 'offload-tx',
'sg': 'offload-sg',
'tso': 'offload-tso',
'ufo': 'offload-ufo',
'gso': 'offload-gso',
'gro': 'offload-gro',
'lro': 'offload-lro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_REV_ETHTOOL_CONFIG_OPTS = {
'link-speed': 'speed',
'link-duplex': 'duplex',
'ethernet-autoneg': 'autoneg',
'ethernet-port': 'ethernet-port',
'ethernet-wol': 'wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'offload-rx': 'rx',
'offload-tx': 'tx',
'offload-sg': 'sg',
'offload-tso': 'tso',
'offload-ufo': 'ufo',
'offload-gso': 'gso',
'offload-lro': 'lro',
'offload-gro': 'gro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_DEB_CONFIG_PPPOE_OPTS = {
'user': 'user',
'password': 'password',
'provider': 'provider',
'pppoe_iface': 'pppoe_iface',
'noipdefault': 'noipdefault',
'usepeerdns': 'usepeerdns',
'defaultroute': 'defaultroute',
'holdoff': 'holdoff',
'maxfail': 'maxfail',
'hide-password': 'hide-password',
'lcp-echo-interval': 'lcp-echo-interval',
'lcp-echo-failure': 'lcp-echo-failure',
'connect': 'connect',
'noauth': 'noauth',
'persist': 'persist',
'mtu': 'mtu',
'noaccomp': 'noaccomp',
'linkname': 'linkname',
}
_DEB_ROUTES_FILE = '/etc/network/routes'
_DEB_NETWORK_FILE = '/etc/network/interfaces'
_DEB_NETWORK_DIR = '/etc/network/interfaces.d/'
_DEB_NETWORK_UP_DIR = '/etc/network/if-up.d/'
_DEB_NETWORK_DOWN_DIR = '/etc/network/if-down.d/'
_DEB_NETWORK_CONF_FILES = '/etc/modprobe.d/'
_DEB_NETWORKING_FILE = '/etc/default/networking'
_DEB_HOSTNAME_FILE = '/etc/hostname'
_DEB_RESOLV_FILE = '/etc/resolv.conf'
_DEB_PPP_DIR = '/etc/ppp/peers/'
_CONFIG_TRUE = ['yes', 'on', 'true', '1', True]
_CONFIG_FALSE = ['no', 'off', 'false', '0', False]
_IFACE_TYPES = [
'eth', 'bond', 'alias', 'clone',
'ipsec', 'dialup', 'bridge', 'slave',
'vlan', 'pppoe', 'source',
]
def _error_msg_iface(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, '|'.join(str(e) for e in expected))
def _error_msg_routes(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, expected)
def _log_default_iface(iface, opt, value):
log.info(
'Using default option -- Interface: %s Option: %s Value: %s',
iface, opt, value
)
def _error_msg_network(option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]'
return msg.format(option, '|'.join(str(e) for e in expected))
def _log_default_network(opt, value):
log.info('Using existing setting -- Setting: %s Value: %s', opt, value)
def _raise_error_iface(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_iface(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_network(option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_network(option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_routes(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_routes(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _read_file(path):
'''
Reads and returns the contents of a text file
'''
try:
with salt.utils.files.flopen(path, 'rb') as contents:
return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]
except (OSError, IOError):
return ''
def _parse_resolve():
'''
Parse /etc/resolv.conf
'''
return salt.utils.dns.parse_resolv(_DEB_RESOLV_FILE)
def _parse_domainname():
'''
Parse /etc/resolv.conf and return domainname
'''
return _parse_resolve().get('domain', '')
def _parse_searchdomain():
'''
Parse /etc/resolv.conf and return searchdomain
'''
return _parse_resolve().get('search', '')
def _parse_hostname():
'''
Parse /etc/hostname and return hostname
'''
contents = _read_file(_DEB_HOSTNAME_FILE)
if contents:
return contents[0].split('\n')[0]
else:
return ''
def _parse_current_network_settings():
'''
Parse /etc/default/networking and return current configuration
'''
opts = salt.utils.odict.OrderedDict()
opts['networking'] = ''
if os.path.isfile(_DEB_NETWORKING_FILE):
with salt.utils.files.fopen(_DEB_NETWORKING_FILE) as contents:
for line in contents:
salt.utils.stringutils.to_unicode(line)
if line.startswith('#'):
continue
elif line.startswith('CONFIGURE_INTERFACES'):
opts['networking'] = line.split('=', 1)[1].strip()
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
opts['hostname'] = hostname
opts['domainname'] = domainname
opts['searchdomain'] = searchdomain
return opts
# def __validator_func(value):
# return (valid: True/False, (transformed) value, error message)
def __ipv4_quad(value):
'''validate an IPv4 address'''
return (salt.utils.validate.net.ipv4_addr(value), value,
'dotted IPv4 address')
def __ipv6(value):
'''validate an IPv6 address'''
return (salt.utils.validate.net.ipv6_addr(value), value,
'IPv6 address')
def __mac(value):
'''validate a mac address'''
return (salt.utils.validate.net.mac(value), value,
'MAC address')
def __anything(value):
return (True, value, None)
def __int(value):
'''validate an integer'''
valid, _value = False, value
try:
_value = int(value)
valid = True
except ValueError:
pass
return (valid, _value, 'integer')
def __float(value):
'''validate a float'''
valid, _value = False, value
try:
_value = float(value)
valid = True
except ValueError:
pass
return (valid, _value, 'float')
def __ipv4_netmask(value):
'''validate an IPv4 dotted quad or integer CIDR netmask'''
valid, errmsg = False, 'dotted quad or integer CIDR (0->32)'
valid, value, _ = __int(value)
if not (valid and 0 <= value <= 32):
valid = salt.utils.validate.net.netmask(value)
return (valid, value, errmsg)
def __ipv6_netmask(value):
'''validate an IPv6 integer netmask'''
valid, errmsg = False, 'IPv6 netmask (0->128)'
valid, value, _ = __int(value)
valid = (valid and 0 <= value <= 128)
return (valid, value, errmsg)
def __within2(value, within=None, errmsg=None, dtype=None):
'''validate that a value is in ``within`` and optionally a ``dtype``'''
valid, _value = False, value
if dtype:
try:
_value = dtype(value) # TODO: this is a bit loose when dtype is a class
valid = _value in within
except ValueError:
pass
else:
valid = _value in within
if errmsg is None:
if dtype:
typename = getattr(dtype, '__name__',
hasattr(dtype, '__class__')
and getattr(dtype.__class__, 'name', dtype))
errmsg = '{0} within \'{1}\''.format(typename, within)
else:
errmsg = 'within \'{0}\''.format(within)
return (valid, _value, errmsg)
def __within(within=None, errmsg=None, dtype=None):
return functools.partial(__within2, within=within,
errmsg=errmsg, dtype=dtype)
def __space_delimited_list(value):
'''validate that a value contains one or more space-delimited values'''
if isinstance(value, six.string_types):
value = value.strip().split()
if hasattr(value, '__iter__') and value != []:
return (True, value, 'space-delimited string')
else:
return (False, value, '{0} is not a valid space-delimited value.\n'.format(value))
SALT_ATTR_TO_DEBIAN_ATTR_MAP = {
'dns': 'dns-nameservers',
'search': 'dns-search',
'hwaddr': 'hwaddress', # TODO: this limits bootp functionality
'ipaddr': 'address',
'ipaddrs': 'addresses',
}
DEBIAN_ATTR_TO_SALT_ATTR_MAP = dict(
(v, k) for (k, v) in six.iteritems(SALT_ATTR_TO_DEBIAN_ATTR_MAP))
# TODO
DEBIAN_ATTR_TO_SALT_ATTR_MAP['address'] = 'address'
DEBIAN_ATTR_TO_SALT_ATTR_MAP['hwaddress'] = 'hwaddress'
IPV4_VALID_PROTO = ['bootp', 'dhcp', 'static', 'manual', 'loopback', 'ppp']
IPV4_ATTR_MAP = {
'proto': __within(IPV4_VALID_PROTO, dtype=six.text_type),
# ipv4 static & manual
'address': __ipv4_quad,
'addresses': __anything,
'netmask': __ipv4_netmask,
'broadcast': __ipv4_quad,
'metric': __int,
'gateway': __ipv4_quad, # supports a colon-delimited list
'pointopoint': __ipv4_quad,
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'link', 'host'], dtype=six.text_type),
# dhcp
'hostname': __anything,
'leasehours': __int,
'leasetime': __int,
'vendor': __anything,
'client': __anything,
# bootp
'bootfile': __anything,
'server': __ipv4_quad,
'hwaddr': __mac,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'dstaddr': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# bond
'slaves': __anything,
# ppp
'provider': __anything,
'unit': __int,
'options': __anything,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
#
'network': __anything, # i don't know what this is
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
IPV6_VALID_PROTO = ['auto', 'loopback', 'static', 'manual',
'dhcp', 'v4tunnel', '6to4']
IPV6_ATTR_MAP = {
'proto': __within(IPV6_VALID_PROTO),
# ipv6 static & manual
'address': __ipv6,
'addresses': __anything,
'netmask': __ipv6_netmask,
'broadcast': __ipv6,
'gateway': __ipv6, # supports a colon-delimited list
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'site', 'link', 'host'], dtype=six.text_type),
# inet6 auto
'privext': __within([0, 1, 2], dtype=int),
'dhcp': __within([0, 1], dtype=int),
# inet6 static & manual & dhcp
'media': __anything,
'accept_ra': __within([0, 1], dtype=int),
'autoconf': __within([0, 1], dtype=int),
'preferred-lifetime': __int,
'dad-attempts': __int, # 0 to disable
'dad-interval': __float,
# bond
'slaves': __anything,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
WIRELESS_ATTR_MAP = {
'wireless-essid': __anything,
'wireless-mode': __anything, # TODO
'wpa-ap-scan': __within([0, 1, 2], dtype=int), # TODO
'wpa-conf': __anything,
'wpa-driver': __anything,
'wpa-group': __anything,
'wpa-key-mgmt': __anything,
'wpa-pairwise': __anything,
'wpa-psk': __anything,
'wpa-proto': __anything, # partial(__within,
'wpa-roam': __anything,
'wpa-ssid': __anything, # TODO
}
ATTRMAPS = {
'inet': [IPV4_ATTR_MAP, WIRELESS_ATTR_MAP],
'inet6': [IPV6_ATTR_MAP, WIRELESS_ATTR_MAP]
}
def _validate_interface_option(attr, value, addrfam='inet'):
'''lookup the validation function for a [addrfam][attr] and
return the results
:param attr: attribute name
:param value: raw setting value
:param addrfam: address family (inet, inet6,
'''
valid, _value, errmsg = False, value, 'Unknown validator'
attrmaps = ATTRMAPS.get(addrfam, [])
for attrmap in attrmaps:
if attr in attrmap:
validate_func = attrmap[attr]
(valid, _value, errmsg) = validate_func(value)
break
return (valid, _value, errmsg)
def _attrmaps_contain_attr(attr):
return (
attr in WIRELESS_ATTR_MAP or
attr in IPV4_ATTR_MAP or
attr in IPV6_ATTR_MAP)
def _parse_interfaces(interface_files=None):
'''
Parse /etc/network/interfaces and return current configured interfaces
'''
if interface_files is None:
interface_files = []
# Add this later.
if os.path.exists(_DEB_NETWORK_DIR):
interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]
if os.path.isfile(_DEB_NETWORK_FILE):
interface_files.insert(0, _DEB_NETWORK_FILE)
adapters = salt.utils.odict.OrderedDict()
method = -1
for interface_file in interface_files:
with salt.utils.files.fopen(interface_file) as interfaces:
# This ensures iface_dict exists, but does not ensure we're not reading a new interface.
iface_dict = {}
for line in interfaces:
line = salt.utils.stringutils.to_unicode(line)
# Identify the clauses by the first word of each line.
# Go to the next line if the current line is a comment
# or all spaces.
if line.lstrip().startswith('#') or line.isspace():
continue
# Parse the iface clause
if line.startswith('iface'):
sline = line.split()
if len(sline) != 4:
msg = 'Interface file malformed: {0}.'
msg = msg.format(sline)
log.error(msg)
raise AttributeError(msg)
iface_name = sline[1]
addrfam = sline[2]
method = sline[3]
# Create item in dict, if not already there
if iface_name not in adapters:
adapters[iface_name] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters[iface_name]:
adapters[iface_name]['data'] = salt.utils.odict.OrderedDict()
if addrfam not in adapters[iface_name]['data']:
adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict()
iface_dict = adapters[iface_name]['data'][addrfam]
iface_dict['addrfam'] = addrfam
iface_dict['proto'] = method
iface_dict['filename'] = interface_file
# Parse the detail clauses.
elif line[0].isspace():
sline = line.split()
# conf file attr: dns-nameservers
# salt states.network attr: dns
attr, valuestr = line.rstrip().split(None, 1)
if _attrmaps_contain_attr(attr):
if '-' in attr:
attrname = attr.replace('-', '_')
else:
attrname = attr
(valid, value, errmsg) = _validate_interface_option(
attr, valuestr, addrfam)
if attrname == 'address' and 'address' in iface_dict:
if 'addresses' not in iface_dict:
iface_dict['addresses'] = []
iface_dict['addresses'].append(value)
else:
iface_dict[attrname] = value
elif attr in _REV_ETHTOOL_CONFIG_OPTS:
if 'ethtool' not in iface_dict:
iface_dict['ethtool'] = salt.utils.odict.OrderedDict()
iface_dict['ethtool'][attr] = valuestr
elif attr.startswith('bond'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bonding' not in iface_dict:
iface_dict['bonding'] = salt.utils.odict.OrderedDict()
iface_dict['bonding'][opt] = valuestr
elif attr.startswith('bridge'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bridging' not in iface_dict:
iface_dict['bridging'] = salt.utils.odict.OrderedDict()
iface_dict['bridging'][opt] = valuestr
elif attr in ['up', 'pre-up', 'post-up',
'down', 'pre-down', 'post-down']:
cmd = valuestr
cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr))
if cmd_key not in iface_dict:
iface_dict[cmd_key] = []
iface_dict[cmd_key].append(cmd)
elif line.startswith('auto'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['enabled'] = True
elif line.startswith('allow-hotplug'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['hotplug'] = True
elif line.startswith('source'):
if 'source' not in adapters:
adapters['source'] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters['source']:
adapters['source']['data'] = salt.utils.odict.OrderedDict()
adapters['source']['data']['sources'] = []
adapters['source']['data']['sources'].append(line.split()[1])
# Return a sorted list of the keys for bond, bridge and ethtool options to
# ensure a consistent order
for iface_name in adapters:
if iface_name == 'source':
continue
if 'data' not in adapters[iface_name]:
msg = 'Interface file malformed for interface: {0}.'.format(iface_name)
log.error(msg)
adapters.pop(iface_name)
continue
for opt in ['ethtool', 'bonding', 'bridging']:
for inet in ['inet', 'inet6']:
if inet in adapters[iface_name]['data']:
if opt in adapters[iface_name]['data'][inet]:
opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys())
adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys
return adapters
def _parse_ethtool_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
if 'autoneg' in opts:
if opts['autoneg'] in _CONFIG_TRUE:
config.update({'autoneg': 'on'})
elif opts['autoneg'] in _CONFIG_FALSE:
config.update({'autoneg': 'off'})
else:
_raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE)
if 'duplex' in opts:
valid = ['full', 'half']
if opts['duplex'] in valid:
config.update({'duplex': opts['duplex']})
else:
_raise_error_iface(iface, 'duplex', valid)
if 'speed' in opts:
valid = ['10', '100', '1000', '10000']
if six.text_type(opts['speed']) in valid:
config.update({'speed': opts['speed']})
else:
_raise_error_iface(iface, opts['speed'], valid)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'on'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'off'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_ethtool_pppoe_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
for opt in _DEB_CONFIG_PPPOE_OPTS:
if opt in opts:
config[opt] = opts[opt]
if 'provider' in opts and not opts['provider']:
_raise_error_iface(iface, 'provider', _CONFIG_TRUE + _CONFIG_FALSE)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('noipdefault', 'usepeerdns', 'defaultroute', 'hide-password', 'noauth', 'persist', 'noaccomp'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'True'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'False'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_settings_bond(opts, iface):
'''
Filters given options and outputs valid settings for requested
operation. If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond_def = {
# 803.ad aggregation selection logic
# 0 for stable (default)
# 1 for bandwidth
# 2 for count
'ad_select': '0',
# Max number of transmit queues (default = 16)
'tx_queues': '16',
# Link monitoring in milliseconds. Most NICs support this
'miimon': '100',
# ARP interval in milliseconds
'arp_interval': '250',
# Delay before considering link down in milliseconds (miimon * 2)
'downdelay': '200',
# lacp_rate 0: Slow - every 30 seconds
# lacp_rate 1: Fast - every 1 second
'lacp_rate': '0',
# Max bonds for this driver
'max_bonds': '1',
# Specifies the time, in milliseconds, to wait before
# enabling a slave after a link recovery has been
# detected. Only used with miimon.
'updelay': '0',
# Used with miimon.
# On: driver sends mii
# Off: ethtool sends mii
'use_carrier': 'on',
# Default. Don't change unless you know what you are doing.
'xmit_hash_policy': 'layer2',
}
if opts['mode'] in ['balance-rr', '0']:
log.info('Device: %s Bonding Mode: load balancing (round-robin)', iface)
return _parse_settings_bond_0(opts, iface, bond_def)
elif opts['mode'] in ['active-backup', '1']:
log.info('Device: %s Bonding Mode: fault-tolerance (active-backup)', iface)
return _parse_settings_bond_1(opts, iface, bond_def)
elif opts['mode'] in ['balance-xor', '2']:
log.info('Device: %s Bonding Mode: load balancing (xor)', iface)
return _parse_settings_bond_2(opts, iface, bond_def)
elif opts['mode'] in ['broadcast', '3']:
log.info('Device: %s Bonding Mode: fault-tolerance (broadcast)', iface)
return _parse_settings_bond_3(opts, iface, bond_def)
elif opts['mode'] in ['802.3ad', '4']:
log.info('Device: %s Bonding Mode: IEEE 802.3ad Dynamic link '
'aggregation', iface)
return _parse_settings_bond_4(opts, iface, bond_def)
elif opts['mode'] in ['balance-tlb', '5']:
log.info('Device: %s Bonding Mode: transmit load balancing', iface)
return _parse_settings_bond_5(opts, iface, bond_def)
elif opts['mode'] in ['balance-alb', '6']:
log.info('Device: %s Bonding Mode: adaptive load balancing', iface)
return _parse_settings_bond_6(opts, iface, bond_def)
else:
valid = [
'0', '1', '2', '3', '4', '5', '6',
'balance-rr', 'active-backup', 'balance-xor',
'broadcast', '802.3ad', 'balance-tlb', 'balance-alb'
]
_raise_error_iface(iface, 'mode', valid)
def _parse_settings_bond_0(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond0.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '0'}
# ARP targets in n.n.n.n form
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
return bond
def _parse_settings_bond_1(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '1'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
if not (__grains__['os'] == "Ubuntu" and __grains__['osrelease_info'][0] >= 16):
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_2(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond2.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '2'}
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_3(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond3.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '3'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_4(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond4.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '4'}
for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']:
if binding in opts:
if binding == 'lacp_rate':
if opts[binding] == 'fast':
opts.update({binding: '1'})
if opts[binding] == 'slow':
opts.update({binding: '0'})
valid = ['fast', '1', 'slow', '0']
else:
valid = ['integer']
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, valid)
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_5(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond5.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '5'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_settings_bond_6(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond6.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '6'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_bridge_opts(opts, iface):
'''
Filters given options and outputs valid settings for BRIDGING_OPTS
If an option has a value that is not expected, this
function will log the Interface, Setting and what was expected.
'''
config = {}
if 'ports' in opts:
if isinstance(opts['ports'], list):
opts['ports'] = ' '.join(opts['ports'])
config.update({'ports': opts['ports']})
for opt in ['ageing', 'fd', 'gcint', 'hello', 'maxage']:
if opt in opts:
try:
float(opts[opt])
config.update({opt: opts[opt]})
except ValueError:
_raise_error_iface(iface, opt, ['float'])
for opt in ['bridgeprio', 'maxwait']:
if opt in opts:
if isinstance(opts[opt], int):
config.update({opt: opts[opt]})
else:
_raise_error_iface(iface, opt, ['integer'])
if 'hw' in opts:
# match 12 hex digits with either : or - as separators between pairs
if re.match('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$',
opts['hw'].lower()):
config.update({'hw': opts['hw']})
else:
_raise_error_iface(iface, 'hw', ['valid MAC address'])
for opt in ['pathcost', 'portprio']:
if opt in opts:
try:
port, cost_or_prio = opts[opt].split()
int(cost_or_prio)
config.update({opt: '{0} {1}'.format(port, cost_or_prio)})
except ValueError:
_raise_error_iface(iface, opt, ['interface integer'])
if 'stp' in opts:
if opts['stp'] in _CONFIG_TRUE:
config.update({'stp': 'on'})
elif opts['stp'] in _CONFIG_FALSE:
config.update({'stp': 'off'})
else:
_raise_error_iface(iface, 'stp', _CONFIG_TRUE + _CONFIG_FALSE)
if 'waitport' in opts:
if isinstance(opts['waitport'], int):
config.update({'waitport': opts['waitport']})
else:
values = opts['waitport'].split()
waitport_time = values.pop(0)
if waitport_time.isdigit() and values:
config.update({
'waitport': '{0} {1}'.format(
waitport_time, ' '.join(values)
)
})
else:
_raise_error_iface(iface, opt, ['integer [interfaces]'])
return config
def _parse_settings_eth(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['inet'] = salt.utils.odict.OrderedDict()
iface_data['inet6'] = salt.utils.odict.OrderedDict()
if enabled:
adapters[iface]['enabled'] = True
if opts.get('hotplug', False):
adapters[iface]['hotplug'] = True
if opts.get('enable_ipv6', None) and opts.get('iface_type', '') == 'vlan':
iface_data['inet6']['vlan_raw_device'] = (
re.sub(r'\.\d*', '', iface))
for addrfam in ['inet', 'inet6']:
if iface_type not in ['bridge']:
tmp_ethtool = _parse_ethtool_opts(opts, iface)
if tmp_ethtool:
ethtool = {}
for item in tmp_ethtool:
ethtool[_ETHTOOL_CONFIG_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['ethtool'] = ethtool
# return a list of sorted keys to ensure consistent order
iface_data[addrfam]['ethtool_keys'] = sorted(ethtool)
if iface_type == 'bridge':
bridging = _parse_bridge_opts(opts, iface)
if bridging:
iface_data[addrfam]['bridging'] = bridging
iface_data[addrfam]['bridging_keys'] = sorted(bridging)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'bond':
bonding = _parse_settings_bond(opts, iface)
if bonding:
iface_data[addrfam]['bonding'] = bonding
iface_data[addrfam]['bonding']['slaves'] = opts['slaves']
iface_data[addrfam]['bonding_keys'] = sorted(bonding)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'slave':
adapters[iface]['master'] = opts['master']
opts['proto'] = 'manual'
iface_data[addrfam]['master'] = adapters[iface]['master']
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'vlan':
iface_data[addrfam]['vlan_raw_device'] = re.sub(r'\.\d*', '', iface)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'pppoe':
tmp_ethtool = _parse_ethtool_pppoe_opts(opts, iface)
if tmp_ethtool:
for item in tmp_ethtool:
adapters[iface]['data'][addrfam][_DEB_CONFIG_PPPOE_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['addrfam'] = addrfam
opts.pop('mode', None)
for opt, val in opts.items():
inet = None
if opt.startswith('ipv4'):
opt = opt[4:]
inet = 'inet'
iface_data['inet']['addrfam'] = 'inet'
elif opt.startswith('ipv6'):
iface_data['inet6']['addrfam'] = 'inet6'
opt = opt[4:]
inet = 'inet6'
elif opt in ['ipaddr', 'address', 'ipaddresses', 'addresses', 'gateway', 'proto']:
iface_data['inet']['addrfam'] = 'inet'
inet = 'inet'
_opt = SALT_ATTR_TO_DEBIAN_ATTR_MAP.get(opt, opt)
_debopt = _opt.replace('-', '_')
for addrfam in ['inet', 'inet6']:
(valid, value, errmsg) = _validate_interface_option(_opt, val, addrfam=addrfam)
if not valid:
continue
if inet is None and _debopt not in iface_data[addrfam]:
iface_data[addrfam][_debopt] = value
elif inet == addrfam:
iface_data[addrfam][_debopt] = value
for opt in ['up_cmds', 'pre_up_cmds', 'post_up_cmds',
'down_cmds', 'pre_down_cmds', 'post_down_cmds']:
if opt in opts:
iface_data['inet'][opt] = opts[opt]
iface_data['inet6'][opt] = opts[opt]
# Remove incomplete/disabled inet blocks
for (addrfam, opt) in [('inet', 'enable_ipv4'), ('inet6', 'enable_ipv6')]:
if opts.get(opt, None) is False:
iface_data.pop(addrfam)
elif iface_data[addrfam].get('addrfam', '') != addrfam:
iface_data.pop(addrfam)
return adapters
def _parse_settings_source(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['sources'] = [opts['source']]
return adapters
def _parse_network_settings(opts, current):
'''
Filters given options and outputs valid settings for
the global network settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
current = dict((k.lower(), v) for (k, v) in six.iteritems(current))
result = {}
valid = _CONFIG_TRUE + _CONFIG_FALSE
if 'enabled' not in opts:
try:
opts['networking'] = current['networking']
_log_default_network('networking', current['networking'])
except ValueError:
_raise_error_network('networking', valid)
else:
opts['networking'] = opts['enabled']
if opts['networking'] in valid:
if opts['networking'] in _CONFIG_TRUE:
result['networking'] = 'yes'
elif opts['networking'] in _CONFIG_FALSE:
result['networking'] = 'no'
else:
_raise_error_network('networking', valid)
if 'hostname' not in opts:
try:
opts['hostname'] = current['hostname']
_log_default_network('hostname', current['hostname'])
except ValueError:
_raise_error_network('hostname', ['server1.example.com'])
if opts['hostname']:
result['hostname'] = opts['hostname']
else:
_raise_error_network('hostname', ['server1.example.com'])
if 'search' in opts:
result['search'] = opts['search']
return result
def _parse_routes(iface, opts):
'''
Filters given options and outputs valid settings for
the route settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
result = {}
if 'routes' not in opts:
_raise_error_routes(iface, 'routes', 'List of routes')
for opt in opts:
result[opt] = opts[opt]
return result
def _write_file(iface, data, folder, pattern):
'''
Writes a file to disk
'''
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
return filename
def _write_file_routes(iface, data, folder, pattern):
'''
Writes a file to disk
'''
# ifup / ifdown is executing given folder via run-parts.
# according to run-parts man-page, only filenames with this pattern are
# executed: (^[a-zA-Z0-9_-]+$)
# In order to make the routes file work for vlan interfaces
# (default would have been in example /etc/network/if-up.d/route-bond0.12)
# these dots in the iface name need to be replaced by underscores, so it
# can be executed by run-parts
iface = iface.replace('.', '_')
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
__salt__['file.set_mode'](filename, '0755')
return filename
def _write_file_network(data, filename, create=False):
'''
Writes a file to disk
If file does not exist, only create if create
argument is True
'''
if not os.path.exists(filename) and not create:
msg = '{0} cannot be written. {0} does not exist\
and create is set to False'
msg = msg.format(filename)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
def _read_temp(data):
'''
Return what would be written to disk
'''
tout = StringIO()
tout.write(data)
tout.seek(0)
output = tout.readlines()
tout.close()
return output
def _read_temp_ifaces(iface, data):
'''
Return what would be written to disk for interfaces
'''
try:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': data})
# Return as an array so the difflib works
return [item + '\n' for item in ifcfg.split('\n')]
def _write_file_ifaces(iface, data, **settings):
'''
Writes a file to disk
'''
try:
eth_template = JINJA.get_template('debian_eth.jinja')
source_template = JINJA.get_template('debian_source.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
# Read /etc/network/interfaces into a dict
adapters = _parse_interfaces()
# Apply supplied settings over on-disk settings
adapters[iface] = data
ifcfg = ''
for adapter in adapters:
if 'type' in adapters[adapter] and adapters[adapter]['type'] == 'source':
tmp = source_template.render({'name': adapter, 'data': adapters[adapter]})
else:
tmp = eth_template.render({'name': adapter, 'data': adapters[adapter]})
ifcfg = ifcfg + tmp
if adapter == iface:
saved_ifcfg = tmp
_SEPARATE_FILE = False
if 'filename' in settings:
if not settings['filename'].startswith('/'):
filename = '{0}/{1}'.format(_DEB_NETWORK_DIR, settings['filename'])
else:
filename = settings['filename']
_SEPARATE_FILE = True
else:
if 'filename' in adapters[adapter]['data']:
filename = adapters[adapter]['data']
else:
filename = _DEB_NETWORK_FILE
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
if _SEPARATE_FILE:
fout.write(salt.utils.stringutils.to_str(saved_ifcfg))
else:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return saved_ifcfg.split('\n')
def _write_file_ppp_ifaces(iface, data):
'''
Writes a file to disk
'''
try:
template = JINJA.get_template('debian_ppp_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_ppp_eth.jinja')
return ''
adapters = _parse_interfaces()
adapters[iface] = data
ifcfg = ''
tmp = template.render({'data': adapters[iface]})
ifcfg = tmp + ifcfg
filename = _DEB_PPP_DIR + '/' + adapters[iface]['data']['inet']['provider']
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.fopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return filename
def build_bond(iface, **settings):
'''
Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb
'''
deb_major = __grains__['osrelease'][:1]
opts = _parse_settings_bond(settings, iface)
try:
template = JINJA.get_template('conf.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template conf.jinja')
return ''
data = template.render({'name': iface, 'bonding': opts})
if 'test' in settings and settings['test']:
return _read_temp(data)
_write_file(iface, data, _DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
if deb_major == '5':
for line_type in ('alias', 'options'):
cmd = ['sed', '-i', '-e', r'/^{0}\s{1}.*/d'.format(line_type, iface),
'/etc/modprobe.conf']
__salt__['cmd.run'](cmd, python_shell=False)
__salt__['file.append']('/etc/modprobe.conf', path)
# Load kernel module
__salt__['kmod.load']('bonding')
# install ifenslave-2.6
__salt__['pkg.install']('ifenslave-2.6')
return _read_file(path)
def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'vlan':
settings['vlan'] = 'yes'
__salt__['pkg.install']('vlan')
elif iface_type == 'pppoe':
settings['pppoe'] = 'yes'
if not __salt__['pkg.version']('ppp'):
inst = __salt__['pkg.install']('ppp')
elif iface_type == 'bond':
if 'slaves' not in settings:
msg = 'slaves is a required setting for bond interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'bridge':
if 'ports' not in settings:
msg = (
'ports is a required setting for bridge interfaces on Debian '
'or Ubuntu based systems'
)
log.error(msg)
raise AttributeError(msg)
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'pppoe']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
if iface_type in ['source']:
opts = _parse_settings_source(settings, iface_type, enabled, iface)
if 'test' in settings and settings['test']:
return _read_temp_ifaces(iface, opts[iface])
ifcfg = _write_file_ifaces(iface, opts[iface], **settings)
if iface_type == 'pppoe':
_write_file_ppp_ifaces(iface, opts[iface])
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg]
def build_routes(iface, **settings):
'''
Add route scripts for a network interface using up commands.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
'''
opts = _parse_routes(iface, settings)
try:
template = JINJA.get_template('route_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template route_eth.jinja')
return ''
add_routecfg = template.render(route_type='add',
routes=opts['routes'],
iface=iface)
del_routecfg = template.render(route_type='del',
routes=opts['routes'],
iface=iface)
if 'test' in settings and settings['test']:
return _read_temp(add_routecfg + del_routecfg)
filename = _write_file_routes(iface,
add_routecfg,
_DEB_NETWORK_UP_DIR,
'route-{0}')
results = _read_file(filename)
filename = _write_file_routes(iface,
del_routecfg,
_DEB_NETWORK_DOWN_DIR,
'route-{0}')
results += _read_file(filename)
return results
def down(iface, iface_type):
'''
Shutdown a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.down eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought down.
if iface_type not in ['slave', 'source']:
return __salt__['cmd.run'](['ifdown', iface])
return None
def get_interface(iface):
'''
Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
adapters = _parse_interfaces()
if iface in adapters:
try:
if iface == 'source':
template = JINJA.get_template('debian_source.jinja')
else:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': adapters[iface]})
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg.split('\n')]
else:
return []
def up(iface, iface_type): # pylint: disable=C0103
'''
Start up a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.up eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought up.
if iface_type not in ('slave', 'source'):
return __salt__['cmd.run'](['ifup', iface])
return None
def get_network_settings():
'''
Return the contents of the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_network_settings
'''
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
settings = {}
if __salt__['service.available']('networking'):
if __salt__['service.status']('networking'):
settings['networking'] = "yes"
else:
settings['networking'] = "no"
else:
settings['networking'] = "no"
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
settings['hostname'] = hostname
settings['domainname'] = domainname
settings['searchdomain'] = searchdomain
else:
settings = _parse_current_network_settings()
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(settings)
return _read_temp(network)
def get_routes(iface):
'''
Return the routes for the interface
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0
'''
filename = os.path.join(_DEB_NETWORK_UP_DIR, 'route-{0}'.format(iface))
results = _read_file(filename)
filename = os.path.join(_DEB_NETWORK_DOWN_DIR, 'route-{0}'.format(iface))
results += _read_file(filename)
return results
def apply_network_settings(**settings):
'''
Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings
'''
if 'require_reboot' not in settings:
settings['require_reboot'] = False
if 'apply_hostname' not in settings:
settings['apply_hostname'] = False
hostname_res = True
if settings['apply_hostname'] in _CONFIG_TRUE:
if 'hostname' in settings:
hostname_res = __salt__['network.mod_hostname'](settings['hostname'])
else:
log.warning(
'The network state sls is trying to apply hostname '
'changes but no hostname is defined.'
)
hostname_res = False
res = True
if settings['require_reboot'] in _CONFIG_TRUE:
log.warning(
'The network state sls is requiring a reboot of the system to '
'properly apply network configuration.'
)
res = True
else:
stop = __salt__['service.stop']('networking')
time.sleep(2)
res = stop and __salt__['service.start']('networking')
return hostname_res and res
def build_network_settings(**settings):
'''
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
'''
changes = []
# Read current configuration and store default values
current_network_settings = _parse_current_network_settings()
# Build settings
opts = _parse_network_settings(settings, current_network_settings)
# Ubuntu has moved away from /etc/default/networking
# beginning with the 12.04 release so we disable or enable
# the networking related services on boot
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
if opts['networking'] == 'yes':
service_cmd = 'service.enable'
else:
service_cmd = 'service.disable'
if __salt__['service.available']('NetworkManager'):
__salt__[service_cmd]('NetworkManager')
if __salt__['service.available']('networking'):
__salt__[service_cmd]('networking')
else:
try:
template = JINJA.get_template('network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template network.jinja')
return ''
network = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(network)
# Write settings
_write_file_network(network, _DEB_NETWORKING_FILE, True)
# Get hostname and domain from opts
sline = opts['hostname'].split('.', 1)
opts['hostname'] = sline[0]
current_domainname = current_network_settings['domainname']
current_searchdomain = current_network_settings['searchdomain']
new_domain = False
if len(sline) > 1:
new_domainname = sline[1]
if new_domainname != current_domainname:
domainname = new_domainname
opts['domainname'] = new_domainname
new_domain = True
else:
domainname = current_domainname
opts['domainname'] = domainname
else:
domainname = current_domainname
opts['domainname'] = domainname
new_search = False
if 'search' in opts:
new_searchdomain = opts['search']
if new_searchdomain != current_searchdomain:
searchdomain = new_searchdomain
opts['searchdomain'] = new_searchdomain
new_search = True
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
# If the domain changes, then we should write the resolv.conf file.
if new_domain or new_search:
# Look for existing domain line and update if necessary
resolve = _parse_resolve()
domain_prog = re.compile(r'domain\s+')
search_prog = re.compile(r'search\s+')
new_contents = []
for item in _read_file(_DEB_RESOLV_FILE):
if domain_prog.match(item):
item = 'domain {0}'.format(domainname)
elif search_prog.match(item):
item = 'search {0}'.format(searchdomain)
new_contents.append(item)
# A domain line didn't exist so we'll add one in
# with the new domainname
if 'domain' not in resolve:
new_contents.insert(0, 'domain {0}' . format(domainname))
# A search line didn't exist so we'll add one in
# with the new search domain
if 'search' not in resolve:
new_contents.insert('domain' in resolve, 'search {0}'.format(searchdomain))
new_resolv = '\n'.join(new_contents)
# Write /etc/resolv.conf
if not ('test' in settings and settings['test']):
_write_file_network(new_resolv, _DEB_RESOLV_FILE)
# used for returning the results back
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(opts)
changes.extend(_read_temp(network))
return changes
|
saltstack/salt
|
salt/modules/debian_ip.py
|
get_interface
|
python
|
def get_interface(iface):
'''
Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
adapters = _parse_interfaces()
if iface in adapters:
try:
if iface == 'source':
template = JINJA.get_template('debian_source.jinja')
else:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': adapters[iface]})
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg.split('\n')]
else:
return []
|
Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_ip.py#L1748-L1775
|
[
"def _parse_interfaces(interface_files=None):\n '''\n Parse /etc/network/interfaces and return current configured interfaces\n '''\n if interface_files is None:\n interface_files = []\n # Add this later.\n if os.path.exists(_DEB_NETWORK_DIR):\n interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]\n\n if os.path.isfile(_DEB_NETWORK_FILE):\n interface_files.insert(0, _DEB_NETWORK_FILE)\n\n adapters = salt.utils.odict.OrderedDict()\n method = -1\n\n for interface_file in interface_files:\n with salt.utils.files.fopen(interface_file) as interfaces:\n # This ensures iface_dict exists, but does not ensure we're not reading a new interface.\n iface_dict = {}\n for line in interfaces:\n line = salt.utils.stringutils.to_unicode(line)\n # Identify the clauses by the first word of each line.\n # Go to the next line if the current line is a comment\n # or all spaces.\n if line.lstrip().startswith('#') or line.isspace():\n continue\n # Parse the iface clause\n if line.startswith('iface'):\n sline = line.split()\n\n if len(sline) != 4:\n msg = 'Interface file malformed: {0}.'\n msg = msg.format(sline)\n log.error(msg)\n raise AttributeError(msg)\n\n iface_name = sline[1]\n addrfam = sline[2]\n method = sline[3]\n\n # Create item in dict, if not already there\n if iface_name not in adapters:\n adapters[iface_name] = salt.utils.odict.OrderedDict()\n\n # Create item in dict, if not already there\n if 'data' not in adapters[iface_name]:\n adapters[iface_name]['data'] = salt.utils.odict.OrderedDict()\n\n if addrfam not in adapters[iface_name]['data']:\n adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict()\n\n iface_dict = adapters[iface_name]['data'][addrfam]\n\n iface_dict['addrfam'] = addrfam\n iface_dict['proto'] = method\n iface_dict['filename'] = interface_file\n\n # Parse the detail clauses.\n elif line[0].isspace():\n sline = line.split()\n\n # conf file attr: dns-nameservers\n # salt states.network attr: dns\n\n attr, valuestr = line.rstrip().split(None, 1)\n if _attrmaps_contain_attr(attr):\n if '-' in attr:\n attrname = attr.replace('-', '_')\n else:\n attrname = attr\n (valid, value, errmsg) = _validate_interface_option(\n attr, valuestr, addrfam)\n if attrname == 'address' and 'address' in iface_dict:\n if 'addresses' not in iface_dict:\n iface_dict['addresses'] = []\n iface_dict['addresses'].append(value)\n else:\n iface_dict[attrname] = value\n\n elif attr in _REV_ETHTOOL_CONFIG_OPTS:\n if 'ethtool' not in iface_dict:\n iface_dict['ethtool'] = salt.utils.odict.OrderedDict()\n iface_dict['ethtool'][attr] = valuestr\n\n elif attr.startswith('bond'):\n opt = re.split(r'[_-]', attr, maxsplit=1)[1]\n if 'bonding' not in iface_dict:\n iface_dict['bonding'] = salt.utils.odict.OrderedDict()\n iface_dict['bonding'][opt] = valuestr\n\n elif attr.startswith('bridge'):\n opt = re.split(r'[_-]', attr, maxsplit=1)[1]\n if 'bridging' not in iface_dict:\n iface_dict['bridging'] = salt.utils.odict.OrderedDict()\n iface_dict['bridging'][opt] = valuestr\n\n elif attr in ['up', 'pre-up', 'post-up',\n 'down', 'pre-down', 'post-down']:\n cmd = valuestr\n cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr))\n if cmd_key not in iface_dict:\n iface_dict[cmd_key] = []\n iface_dict[cmd_key].append(cmd)\n\n elif line.startswith('auto'):\n for word in line.split()[1:]:\n if word not in adapters:\n adapters[word] = salt.utils.odict.OrderedDict()\n adapters[word]['enabled'] = True\n\n elif line.startswith('allow-hotplug'):\n for word in line.split()[1:]:\n if word not in adapters:\n adapters[word] = salt.utils.odict.OrderedDict()\n adapters[word]['hotplug'] = True\n\n elif line.startswith('source'):\n if 'source' not in adapters:\n adapters['source'] = salt.utils.odict.OrderedDict()\n\n # Create item in dict, if not already there\n if 'data' not in adapters['source']:\n adapters['source']['data'] = salt.utils.odict.OrderedDict()\n adapters['source']['data']['sources'] = []\n adapters['source']['data']['sources'].append(line.split()[1])\n\n # Return a sorted list of the keys for bond, bridge and ethtool options to\n # ensure a consistent order\n for iface_name in adapters:\n if iface_name == 'source':\n continue\n if 'data' not in adapters[iface_name]:\n msg = 'Interface file malformed for interface: {0}.'.format(iface_name)\n log.error(msg)\n adapters.pop(iface_name)\n continue\n for opt in ['ethtool', 'bonding', 'bridging']:\n for inet in ['inet', 'inet6']:\n if inet in adapters[iface_name]['data']:\n if opt in adapters[iface_name]['data'][inet]:\n opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys())\n adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys\n\n return adapters\n"
] |
# -*- coding: utf-8 -*-
'''
The networking module for Debian-based distros
References:
* http://www.debian.org/doc/manuals/debian-reference/ch05.en.html
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import functools
import logging
import os.path
import os
import re
import time
# Import third party libs
import jinja2
import jinja2.exceptions
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error,no-name-in-module
# Import salt libs
import salt.utils.dns
import salt.utils.files
import salt.utils.odict
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.validate.net
# Set up logging
log = logging.getLogger(__name__)
# Set up template environment
JINJA = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'debian_ip')
)
)
# Define the module's virtual name
__virtualname__ = 'ip'
def __virtual__():
'''
Confine this module to Debian-based distros
'''
if __grains__['os_family'] == 'Debian':
return __virtualname__
return (False, 'The debian_ip module could not be loaded: '
'unsupported OS family')
_ETHTOOL_CONFIG_OPTS = {
'speed': 'link-speed',
'duplex': 'link-duplex',
'autoneg': 'ethernet-autoneg',
'ethernet-port': 'ethernet-port',
'wol': 'ethernet-wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'rx': 'offload-rx',
'tx': 'offload-tx',
'sg': 'offload-sg',
'tso': 'offload-tso',
'ufo': 'offload-ufo',
'gso': 'offload-gso',
'gro': 'offload-gro',
'lro': 'offload-lro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_REV_ETHTOOL_CONFIG_OPTS = {
'link-speed': 'speed',
'link-duplex': 'duplex',
'ethernet-autoneg': 'autoneg',
'ethernet-port': 'ethernet-port',
'ethernet-wol': 'wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'offload-rx': 'rx',
'offload-tx': 'tx',
'offload-sg': 'sg',
'offload-tso': 'tso',
'offload-ufo': 'ufo',
'offload-gso': 'gso',
'offload-lro': 'lro',
'offload-gro': 'gro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_DEB_CONFIG_PPPOE_OPTS = {
'user': 'user',
'password': 'password',
'provider': 'provider',
'pppoe_iface': 'pppoe_iface',
'noipdefault': 'noipdefault',
'usepeerdns': 'usepeerdns',
'defaultroute': 'defaultroute',
'holdoff': 'holdoff',
'maxfail': 'maxfail',
'hide-password': 'hide-password',
'lcp-echo-interval': 'lcp-echo-interval',
'lcp-echo-failure': 'lcp-echo-failure',
'connect': 'connect',
'noauth': 'noauth',
'persist': 'persist',
'mtu': 'mtu',
'noaccomp': 'noaccomp',
'linkname': 'linkname',
}
_DEB_ROUTES_FILE = '/etc/network/routes'
_DEB_NETWORK_FILE = '/etc/network/interfaces'
_DEB_NETWORK_DIR = '/etc/network/interfaces.d/'
_DEB_NETWORK_UP_DIR = '/etc/network/if-up.d/'
_DEB_NETWORK_DOWN_DIR = '/etc/network/if-down.d/'
_DEB_NETWORK_CONF_FILES = '/etc/modprobe.d/'
_DEB_NETWORKING_FILE = '/etc/default/networking'
_DEB_HOSTNAME_FILE = '/etc/hostname'
_DEB_RESOLV_FILE = '/etc/resolv.conf'
_DEB_PPP_DIR = '/etc/ppp/peers/'
_CONFIG_TRUE = ['yes', 'on', 'true', '1', True]
_CONFIG_FALSE = ['no', 'off', 'false', '0', False]
_IFACE_TYPES = [
'eth', 'bond', 'alias', 'clone',
'ipsec', 'dialup', 'bridge', 'slave',
'vlan', 'pppoe', 'source',
]
def _error_msg_iface(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, '|'.join(str(e) for e in expected))
def _error_msg_routes(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, expected)
def _log_default_iface(iface, opt, value):
log.info(
'Using default option -- Interface: %s Option: %s Value: %s',
iface, opt, value
)
def _error_msg_network(option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]'
return msg.format(option, '|'.join(str(e) for e in expected))
def _log_default_network(opt, value):
log.info('Using existing setting -- Setting: %s Value: %s', opt, value)
def _raise_error_iface(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_iface(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_network(option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_network(option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_routes(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_routes(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _read_file(path):
'''
Reads and returns the contents of a text file
'''
try:
with salt.utils.files.flopen(path, 'rb') as contents:
return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]
except (OSError, IOError):
return ''
def _parse_resolve():
'''
Parse /etc/resolv.conf
'''
return salt.utils.dns.parse_resolv(_DEB_RESOLV_FILE)
def _parse_domainname():
'''
Parse /etc/resolv.conf and return domainname
'''
return _parse_resolve().get('domain', '')
def _parse_searchdomain():
'''
Parse /etc/resolv.conf and return searchdomain
'''
return _parse_resolve().get('search', '')
def _parse_hostname():
'''
Parse /etc/hostname and return hostname
'''
contents = _read_file(_DEB_HOSTNAME_FILE)
if contents:
return contents[0].split('\n')[0]
else:
return ''
def _parse_current_network_settings():
'''
Parse /etc/default/networking and return current configuration
'''
opts = salt.utils.odict.OrderedDict()
opts['networking'] = ''
if os.path.isfile(_DEB_NETWORKING_FILE):
with salt.utils.files.fopen(_DEB_NETWORKING_FILE) as contents:
for line in contents:
salt.utils.stringutils.to_unicode(line)
if line.startswith('#'):
continue
elif line.startswith('CONFIGURE_INTERFACES'):
opts['networking'] = line.split('=', 1)[1].strip()
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
opts['hostname'] = hostname
opts['domainname'] = domainname
opts['searchdomain'] = searchdomain
return opts
# def __validator_func(value):
# return (valid: True/False, (transformed) value, error message)
def __ipv4_quad(value):
'''validate an IPv4 address'''
return (salt.utils.validate.net.ipv4_addr(value), value,
'dotted IPv4 address')
def __ipv6(value):
'''validate an IPv6 address'''
return (salt.utils.validate.net.ipv6_addr(value), value,
'IPv6 address')
def __mac(value):
'''validate a mac address'''
return (salt.utils.validate.net.mac(value), value,
'MAC address')
def __anything(value):
return (True, value, None)
def __int(value):
'''validate an integer'''
valid, _value = False, value
try:
_value = int(value)
valid = True
except ValueError:
pass
return (valid, _value, 'integer')
def __float(value):
'''validate a float'''
valid, _value = False, value
try:
_value = float(value)
valid = True
except ValueError:
pass
return (valid, _value, 'float')
def __ipv4_netmask(value):
'''validate an IPv4 dotted quad or integer CIDR netmask'''
valid, errmsg = False, 'dotted quad or integer CIDR (0->32)'
valid, value, _ = __int(value)
if not (valid and 0 <= value <= 32):
valid = salt.utils.validate.net.netmask(value)
return (valid, value, errmsg)
def __ipv6_netmask(value):
'''validate an IPv6 integer netmask'''
valid, errmsg = False, 'IPv6 netmask (0->128)'
valid, value, _ = __int(value)
valid = (valid and 0 <= value <= 128)
return (valid, value, errmsg)
def __within2(value, within=None, errmsg=None, dtype=None):
'''validate that a value is in ``within`` and optionally a ``dtype``'''
valid, _value = False, value
if dtype:
try:
_value = dtype(value) # TODO: this is a bit loose when dtype is a class
valid = _value in within
except ValueError:
pass
else:
valid = _value in within
if errmsg is None:
if dtype:
typename = getattr(dtype, '__name__',
hasattr(dtype, '__class__')
and getattr(dtype.__class__, 'name', dtype))
errmsg = '{0} within \'{1}\''.format(typename, within)
else:
errmsg = 'within \'{0}\''.format(within)
return (valid, _value, errmsg)
def __within(within=None, errmsg=None, dtype=None):
return functools.partial(__within2, within=within,
errmsg=errmsg, dtype=dtype)
def __space_delimited_list(value):
'''validate that a value contains one or more space-delimited values'''
if isinstance(value, six.string_types):
value = value.strip().split()
if hasattr(value, '__iter__') and value != []:
return (True, value, 'space-delimited string')
else:
return (False, value, '{0} is not a valid space-delimited value.\n'.format(value))
SALT_ATTR_TO_DEBIAN_ATTR_MAP = {
'dns': 'dns-nameservers',
'search': 'dns-search',
'hwaddr': 'hwaddress', # TODO: this limits bootp functionality
'ipaddr': 'address',
'ipaddrs': 'addresses',
}
DEBIAN_ATTR_TO_SALT_ATTR_MAP = dict(
(v, k) for (k, v) in six.iteritems(SALT_ATTR_TO_DEBIAN_ATTR_MAP))
# TODO
DEBIAN_ATTR_TO_SALT_ATTR_MAP['address'] = 'address'
DEBIAN_ATTR_TO_SALT_ATTR_MAP['hwaddress'] = 'hwaddress'
IPV4_VALID_PROTO = ['bootp', 'dhcp', 'static', 'manual', 'loopback', 'ppp']
IPV4_ATTR_MAP = {
'proto': __within(IPV4_VALID_PROTO, dtype=six.text_type),
# ipv4 static & manual
'address': __ipv4_quad,
'addresses': __anything,
'netmask': __ipv4_netmask,
'broadcast': __ipv4_quad,
'metric': __int,
'gateway': __ipv4_quad, # supports a colon-delimited list
'pointopoint': __ipv4_quad,
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'link', 'host'], dtype=six.text_type),
# dhcp
'hostname': __anything,
'leasehours': __int,
'leasetime': __int,
'vendor': __anything,
'client': __anything,
# bootp
'bootfile': __anything,
'server': __ipv4_quad,
'hwaddr': __mac,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'dstaddr': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# bond
'slaves': __anything,
# ppp
'provider': __anything,
'unit': __int,
'options': __anything,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
#
'network': __anything, # i don't know what this is
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
IPV6_VALID_PROTO = ['auto', 'loopback', 'static', 'manual',
'dhcp', 'v4tunnel', '6to4']
IPV6_ATTR_MAP = {
'proto': __within(IPV6_VALID_PROTO),
# ipv6 static & manual
'address': __ipv6,
'addresses': __anything,
'netmask': __ipv6_netmask,
'broadcast': __ipv6,
'gateway': __ipv6, # supports a colon-delimited list
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'site', 'link', 'host'], dtype=six.text_type),
# inet6 auto
'privext': __within([0, 1, 2], dtype=int),
'dhcp': __within([0, 1], dtype=int),
# inet6 static & manual & dhcp
'media': __anything,
'accept_ra': __within([0, 1], dtype=int),
'autoconf': __within([0, 1], dtype=int),
'preferred-lifetime': __int,
'dad-attempts': __int, # 0 to disable
'dad-interval': __float,
# bond
'slaves': __anything,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
WIRELESS_ATTR_MAP = {
'wireless-essid': __anything,
'wireless-mode': __anything, # TODO
'wpa-ap-scan': __within([0, 1, 2], dtype=int), # TODO
'wpa-conf': __anything,
'wpa-driver': __anything,
'wpa-group': __anything,
'wpa-key-mgmt': __anything,
'wpa-pairwise': __anything,
'wpa-psk': __anything,
'wpa-proto': __anything, # partial(__within,
'wpa-roam': __anything,
'wpa-ssid': __anything, # TODO
}
ATTRMAPS = {
'inet': [IPV4_ATTR_MAP, WIRELESS_ATTR_MAP],
'inet6': [IPV6_ATTR_MAP, WIRELESS_ATTR_MAP]
}
def _validate_interface_option(attr, value, addrfam='inet'):
'''lookup the validation function for a [addrfam][attr] and
return the results
:param attr: attribute name
:param value: raw setting value
:param addrfam: address family (inet, inet6,
'''
valid, _value, errmsg = False, value, 'Unknown validator'
attrmaps = ATTRMAPS.get(addrfam, [])
for attrmap in attrmaps:
if attr in attrmap:
validate_func = attrmap[attr]
(valid, _value, errmsg) = validate_func(value)
break
return (valid, _value, errmsg)
def _attrmaps_contain_attr(attr):
return (
attr in WIRELESS_ATTR_MAP or
attr in IPV4_ATTR_MAP or
attr in IPV6_ATTR_MAP)
def _parse_interfaces(interface_files=None):
'''
Parse /etc/network/interfaces and return current configured interfaces
'''
if interface_files is None:
interface_files = []
# Add this later.
if os.path.exists(_DEB_NETWORK_DIR):
interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]
if os.path.isfile(_DEB_NETWORK_FILE):
interface_files.insert(0, _DEB_NETWORK_FILE)
adapters = salt.utils.odict.OrderedDict()
method = -1
for interface_file in interface_files:
with salt.utils.files.fopen(interface_file) as interfaces:
# This ensures iface_dict exists, but does not ensure we're not reading a new interface.
iface_dict = {}
for line in interfaces:
line = salt.utils.stringutils.to_unicode(line)
# Identify the clauses by the first word of each line.
# Go to the next line if the current line is a comment
# or all spaces.
if line.lstrip().startswith('#') or line.isspace():
continue
# Parse the iface clause
if line.startswith('iface'):
sline = line.split()
if len(sline) != 4:
msg = 'Interface file malformed: {0}.'
msg = msg.format(sline)
log.error(msg)
raise AttributeError(msg)
iface_name = sline[1]
addrfam = sline[2]
method = sline[3]
# Create item in dict, if not already there
if iface_name not in adapters:
adapters[iface_name] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters[iface_name]:
adapters[iface_name]['data'] = salt.utils.odict.OrderedDict()
if addrfam not in adapters[iface_name]['data']:
adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict()
iface_dict = adapters[iface_name]['data'][addrfam]
iface_dict['addrfam'] = addrfam
iface_dict['proto'] = method
iface_dict['filename'] = interface_file
# Parse the detail clauses.
elif line[0].isspace():
sline = line.split()
# conf file attr: dns-nameservers
# salt states.network attr: dns
attr, valuestr = line.rstrip().split(None, 1)
if _attrmaps_contain_attr(attr):
if '-' in attr:
attrname = attr.replace('-', '_')
else:
attrname = attr
(valid, value, errmsg) = _validate_interface_option(
attr, valuestr, addrfam)
if attrname == 'address' and 'address' in iface_dict:
if 'addresses' not in iface_dict:
iface_dict['addresses'] = []
iface_dict['addresses'].append(value)
else:
iface_dict[attrname] = value
elif attr in _REV_ETHTOOL_CONFIG_OPTS:
if 'ethtool' not in iface_dict:
iface_dict['ethtool'] = salt.utils.odict.OrderedDict()
iface_dict['ethtool'][attr] = valuestr
elif attr.startswith('bond'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bonding' not in iface_dict:
iface_dict['bonding'] = salt.utils.odict.OrderedDict()
iface_dict['bonding'][opt] = valuestr
elif attr.startswith('bridge'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bridging' not in iface_dict:
iface_dict['bridging'] = salt.utils.odict.OrderedDict()
iface_dict['bridging'][opt] = valuestr
elif attr in ['up', 'pre-up', 'post-up',
'down', 'pre-down', 'post-down']:
cmd = valuestr
cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr))
if cmd_key not in iface_dict:
iface_dict[cmd_key] = []
iface_dict[cmd_key].append(cmd)
elif line.startswith('auto'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['enabled'] = True
elif line.startswith('allow-hotplug'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['hotplug'] = True
elif line.startswith('source'):
if 'source' not in adapters:
adapters['source'] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters['source']:
adapters['source']['data'] = salt.utils.odict.OrderedDict()
adapters['source']['data']['sources'] = []
adapters['source']['data']['sources'].append(line.split()[1])
# Return a sorted list of the keys for bond, bridge and ethtool options to
# ensure a consistent order
for iface_name in adapters:
if iface_name == 'source':
continue
if 'data' not in adapters[iface_name]:
msg = 'Interface file malformed for interface: {0}.'.format(iface_name)
log.error(msg)
adapters.pop(iface_name)
continue
for opt in ['ethtool', 'bonding', 'bridging']:
for inet in ['inet', 'inet6']:
if inet in adapters[iface_name]['data']:
if opt in adapters[iface_name]['data'][inet]:
opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys())
adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys
return adapters
def _parse_ethtool_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
if 'autoneg' in opts:
if opts['autoneg'] in _CONFIG_TRUE:
config.update({'autoneg': 'on'})
elif opts['autoneg'] in _CONFIG_FALSE:
config.update({'autoneg': 'off'})
else:
_raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE)
if 'duplex' in opts:
valid = ['full', 'half']
if opts['duplex'] in valid:
config.update({'duplex': opts['duplex']})
else:
_raise_error_iface(iface, 'duplex', valid)
if 'speed' in opts:
valid = ['10', '100', '1000', '10000']
if six.text_type(opts['speed']) in valid:
config.update({'speed': opts['speed']})
else:
_raise_error_iface(iface, opts['speed'], valid)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'on'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'off'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_ethtool_pppoe_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
for opt in _DEB_CONFIG_PPPOE_OPTS:
if opt in opts:
config[opt] = opts[opt]
if 'provider' in opts and not opts['provider']:
_raise_error_iface(iface, 'provider', _CONFIG_TRUE + _CONFIG_FALSE)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('noipdefault', 'usepeerdns', 'defaultroute', 'hide-password', 'noauth', 'persist', 'noaccomp'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'True'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'False'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_settings_bond(opts, iface):
'''
Filters given options and outputs valid settings for requested
operation. If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond_def = {
# 803.ad aggregation selection logic
# 0 for stable (default)
# 1 for bandwidth
# 2 for count
'ad_select': '0',
# Max number of transmit queues (default = 16)
'tx_queues': '16',
# Link monitoring in milliseconds. Most NICs support this
'miimon': '100',
# ARP interval in milliseconds
'arp_interval': '250',
# Delay before considering link down in milliseconds (miimon * 2)
'downdelay': '200',
# lacp_rate 0: Slow - every 30 seconds
# lacp_rate 1: Fast - every 1 second
'lacp_rate': '0',
# Max bonds for this driver
'max_bonds': '1',
# Specifies the time, in milliseconds, to wait before
# enabling a slave after a link recovery has been
# detected. Only used with miimon.
'updelay': '0',
# Used with miimon.
# On: driver sends mii
# Off: ethtool sends mii
'use_carrier': 'on',
# Default. Don't change unless you know what you are doing.
'xmit_hash_policy': 'layer2',
}
if opts['mode'] in ['balance-rr', '0']:
log.info('Device: %s Bonding Mode: load balancing (round-robin)', iface)
return _parse_settings_bond_0(opts, iface, bond_def)
elif opts['mode'] in ['active-backup', '1']:
log.info('Device: %s Bonding Mode: fault-tolerance (active-backup)', iface)
return _parse_settings_bond_1(opts, iface, bond_def)
elif opts['mode'] in ['balance-xor', '2']:
log.info('Device: %s Bonding Mode: load balancing (xor)', iface)
return _parse_settings_bond_2(opts, iface, bond_def)
elif opts['mode'] in ['broadcast', '3']:
log.info('Device: %s Bonding Mode: fault-tolerance (broadcast)', iface)
return _parse_settings_bond_3(opts, iface, bond_def)
elif opts['mode'] in ['802.3ad', '4']:
log.info('Device: %s Bonding Mode: IEEE 802.3ad Dynamic link '
'aggregation', iface)
return _parse_settings_bond_4(opts, iface, bond_def)
elif opts['mode'] in ['balance-tlb', '5']:
log.info('Device: %s Bonding Mode: transmit load balancing', iface)
return _parse_settings_bond_5(opts, iface, bond_def)
elif opts['mode'] in ['balance-alb', '6']:
log.info('Device: %s Bonding Mode: adaptive load balancing', iface)
return _parse_settings_bond_6(opts, iface, bond_def)
else:
valid = [
'0', '1', '2', '3', '4', '5', '6',
'balance-rr', 'active-backup', 'balance-xor',
'broadcast', '802.3ad', 'balance-tlb', 'balance-alb'
]
_raise_error_iface(iface, 'mode', valid)
def _parse_settings_bond_0(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond0.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '0'}
# ARP targets in n.n.n.n form
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
return bond
def _parse_settings_bond_1(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '1'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
if not (__grains__['os'] == "Ubuntu" and __grains__['osrelease_info'][0] >= 16):
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_2(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond2.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '2'}
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_3(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond3.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '3'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_4(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond4.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '4'}
for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']:
if binding in opts:
if binding == 'lacp_rate':
if opts[binding] == 'fast':
opts.update({binding: '1'})
if opts[binding] == 'slow':
opts.update({binding: '0'})
valid = ['fast', '1', 'slow', '0']
else:
valid = ['integer']
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, valid)
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_5(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond5.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '5'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_settings_bond_6(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond6.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '6'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_bridge_opts(opts, iface):
'''
Filters given options and outputs valid settings for BRIDGING_OPTS
If an option has a value that is not expected, this
function will log the Interface, Setting and what was expected.
'''
config = {}
if 'ports' in opts:
if isinstance(opts['ports'], list):
opts['ports'] = ' '.join(opts['ports'])
config.update({'ports': opts['ports']})
for opt in ['ageing', 'fd', 'gcint', 'hello', 'maxage']:
if opt in opts:
try:
float(opts[opt])
config.update({opt: opts[opt]})
except ValueError:
_raise_error_iface(iface, opt, ['float'])
for opt in ['bridgeprio', 'maxwait']:
if opt in opts:
if isinstance(opts[opt], int):
config.update({opt: opts[opt]})
else:
_raise_error_iface(iface, opt, ['integer'])
if 'hw' in opts:
# match 12 hex digits with either : or - as separators between pairs
if re.match('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$',
opts['hw'].lower()):
config.update({'hw': opts['hw']})
else:
_raise_error_iface(iface, 'hw', ['valid MAC address'])
for opt in ['pathcost', 'portprio']:
if opt in opts:
try:
port, cost_or_prio = opts[opt].split()
int(cost_or_prio)
config.update({opt: '{0} {1}'.format(port, cost_or_prio)})
except ValueError:
_raise_error_iface(iface, opt, ['interface integer'])
if 'stp' in opts:
if opts['stp'] in _CONFIG_TRUE:
config.update({'stp': 'on'})
elif opts['stp'] in _CONFIG_FALSE:
config.update({'stp': 'off'})
else:
_raise_error_iface(iface, 'stp', _CONFIG_TRUE + _CONFIG_FALSE)
if 'waitport' in opts:
if isinstance(opts['waitport'], int):
config.update({'waitport': opts['waitport']})
else:
values = opts['waitport'].split()
waitport_time = values.pop(0)
if waitport_time.isdigit() and values:
config.update({
'waitport': '{0} {1}'.format(
waitport_time, ' '.join(values)
)
})
else:
_raise_error_iface(iface, opt, ['integer [interfaces]'])
return config
def _parse_settings_eth(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['inet'] = salt.utils.odict.OrderedDict()
iface_data['inet6'] = salt.utils.odict.OrderedDict()
if enabled:
adapters[iface]['enabled'] = True
if opts.get('hotplug', False):
adapters[iface]['hotplug'] = True
if opts.get('enable_ipv6', None) and opts.get('iface_type', '') == 'vlan':
iface_data['inet6']['vlan_raw_device'] = (
re.sub(r'\.\d*', '', iface))
for addrfam in ['inet', 'inet6']:
if iface_type not in ['bridge']:
tmp_ethtool = _parse_ethtool_opts(opts, iface)
if tmp_ethtool:
ethtool = {}
for item in tmp_ethtool:
ethtool[_ETHTOOL_CONFIG_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['ethtool'] = ethtool
# return a list of sorted keys to ensure consistent order
iface_data[addrfam]['ethtool_keys'] = sorted(ethtool)
if iface_type == 'bridge':
bridging = _parse_bridge_opts(opts, iface)
if bridging:
iface_data[addrfam]['bridging'] = bridging
iface_data[addrfam]['bridging_keys'] = sorted(bridging)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'bond':
bonding = _parse_settings_bond(opts, iface)
if bonding:
iface_data[addrfam]['bonding'] = bonding
iface_data[addrfam]['bonding']['slaves'] = opts['slaves']
iface_data[addrfam]['bonding_keys'] = sorted(bonding)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'slave':
adapters[iface]['master'] = opts['master']
opts['proto'] = 'manual'
iface_data[addrfam]['master'] = adapters[iface]['master']
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'vlan':
iface_data[addrfam]['vlan_raw_device'] = re.sub(r'\.\d*', '', iface)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'pppoe':
tmp_ethtool = _parse_ethtool_pppoe_opts(opts, iface)
if tmp_ethtool:
for item in tmp_ethtool:
adapters[iface]['data'][addrfam][_DEB_CONFIG_PPPOE_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['addrfam'] = addrfam
opts.pop('mode', None)
for opt, val in opts.items():
inet = None
if opt.startswith('ipv4'):
opt = opt[4:]
inet = 'inet'
iface_data['inet']['addrfam'] = 'inet'
elif opt.startswith('ipv6'):
iface_data['inet6']['addrfam'] = 'inet6'
opt = opt[4:]
inet = 'inet6'
elif opt in ['ipaddr', 'address', 'ipaddresses', 'addresses', 'gateway', 'proto']:
iface_data['inet']['addrfam'] = 'inet'
inet = 'inet'
_opt = SALT_ATTR_TO_DEBIAN_ATTR_MAP.get(opt, opt)
_debopt = _opt.replace('-', '_')
for addrfam in ['inet', 'inet6']:
(valid, value, errmsg) = _validate_interface_option(_opt, val, addrfam=addrfam)
if not valid:
continue
if inet is None and _debopt not in iface_data[addrfam]:
iface_data[addrfam][_debopt] = value
elif inet == addrfam:
iface_data[addrfam][_debopt] = value
for opt in ['up_cmds', 'pre_up_cmds', 'post_up_cmds',
'down_cmds', 'pre_down_cmds', 'post_down_cmds']:
if opt in opts:
iface_data['inet'][opt] = opts[opt]
iface_data['inet6'][opt] = opts[opt]
# Remove incomplete/disabled inet blocks
for (addrfam, opt) in [('inet', 'enable_ipv4'), ('inet6', 'enable_ipv6')]:
if opts.get(opt, None) is False:
iface_data.pop(addrfam)
elif iface_data[addrfam].get('addrfam', '') != addrfam:
iface_data.pop(addrfam)
return adapters
def _parse_settings_source(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['sources'] = [opts['source']]
return adapters
def _parse_network_settings(opts, current):
'''
Filters given options and outputs valid settings for
the global network settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
current = dict((k.lower(), v) for (k, v) in six.iteritems(current))
result = {}
valid = _CONFIG_TRUE + _CONFIG_FALSE
if 'enabled' not in opts:
try:
opts['networking'] = current['networking']
_log_default_network('networking', current['networking'])
except ValueError:
_raise_error_network('networking', valid)
else:
opts['networking'] = opts['enabled']
if opts['networking'] in valid:
if opts['networking'] in _CONFIG_TRUE:
result['networking'] = 'yes'
elif opts['networking'] in _CONFIG_FALSE:
result['networking'] = 'no'
else:
_raise_error_network('networking', valid)
if 'hostname' not in opts:
try:
opts['hostname'] = current['hostname']
_log_default_network('hostname', current['hostname'])
except ValueError:
_raise_error_network('hostname', ['server1.example.com'])
if opts['hostname']:
result['hostname'] = opts['hostname']
else:
_raise_error_network('hostname', ['server1.example.com'])
if 'search' in opts:
result['search'] = opts['search']
return result
def _parse_routes(iface, opts):
'''
Filters given options and outputs valid settings for
the route settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
result = {}
if 'routes' not in opts:
_raise_error_routes(iface, 'routes', 'List of routes')
for opt in opts:
result[opt] = opts[opt]
return result
def _write_file(iface, data, folder, pattern):
'''
Writes a file to disk
'''
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
return filename
def _write_file_routes(iface, data, folder, pattern):
'''
Writes a file to disk
'''
# ifup / ifdown is executing given folder via run-parts.
# according to run-parts man-page, only filenames with this pattern are
# executed: (^[a-zA-Z0-9_-]+$)
# In order to make the routes file work for vlan interfaces
# (default would have been in example /etc/network/if-up.d/route-bond0.12)
# these dots in the iface name need to be replaced by underscores, so it
# can be executed by run-parts
iface = iface.replace('.', '_')
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
__salt__['file.set_mode'](filename, '0755')
return filename
def _write_file_network(data, filename, create=False):
'''
Writes a file to disk
If file does not exist, only create if create
argument is True
'''
if not os.path.exists(filename) and not create:
msg = '{0} cannot be written. {0} does not exist\
and create is set to False'
msg = msg.format(filename)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
def _read_temp(data):
'''
Return what would be written to disk
'''
tout = StringIO()
tout.write(data)
tout.seek(0)
output = tout.readlines()
tout.close()
return output
def _read_temp_ifaces(iface, data):
'''
Return what would be written to disk for interfaces
'''
try:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': data})
# Return as an array so the difflib works
return [item + '\n' for item in ifcfg.split('\n')]
def _write_file_ifaces(iface, data, **settings):
'''
Writes a file to disk
'''
try:
eth_template = JINJA.get_template('debian_eth.jinja')
source_template = JINJA.get_template('debian_source.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
# Read /etc/network/interfaces into a dict
adapters = _parse_interfaces()
# Apply supplied settings over on-disk settings
adapters[iface] = data
ifcfg = ''
for adapter in adapters:
if 'type' in adapters[adapter] and adapters[adapter]['type'] == 'source':
tmp = source_template.render({'name': adapter, 'data': adapters[adapter]})
else:
tmp = eth_template.render({'name': adapter, 'data': adapters[adapter]})
ifcfg = ifcfg + tmp
if adapter == iface:
saved_ifcfg = tmp
_SEPARATE_FILE = False
if 'filename' in settings:
if not settings['filename'].startswith('/'):
filename = '{0}/{1}'.format(_DEB_NETWORK_DIR, settings['filename'])
else:
filename = settings['filename']
_SEPARATE_FILE = True
else:
if 'filename' in adapters[adapter]['data']:
filename = adapters[adapter]['data']
else:
filename = _DEB_NETWORK_FILE
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
if _SEPARATE_FILE:
fout.write(salt.utils.stringutils.to_str(saved_ifcfg))
else:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return saved_ifcfg.split('\n')
def _write_file_ppp_ifaces(iface, data):
'''
Writes a file to disk
'''
try:
template = JINJA.get_template('debian_ppp_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_ppp_eth.jinja')
return ''
adapters = _parse_interfaces()
adapters[iface] = data
ifcfg = ''
tmp = template.render({'data': adapters[iface]})
ifcfg = tmp + ifcfg
filename = _DEB_PPP_DIR + '/' + adapters[iface]['data']['inet']['provider']
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.fopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return filename
def build_bond(iface, **settings):
'''
Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb
'''
deb_major = __grains__['osrelease'][:1]
opts = _parse_settings_bond(settings, iface)
try:
template = JINJA.get_template('conf.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template conf.jinja')
return ''
data = template.render({'name': iface, 'bonding': opts})
if 'test' in settings and settings['test']:
return _read_temp(data)
_write_file(iface, data, _DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
if deb_major == '5':
for line_type in ('alias', 'options'):
cmd = ['sed', '-i', '-e', r'/^{0}\s{1}.*/d'.format(line_type, iface),
'/etc/modprobe.conf']
__salt__['cmd.run'](cmd, python_shell=False)
__salt__['file.append']('/etc/modprobe.conf', path)
# Load kernel module
__salt__['kmod.load']('bonding')
# install ifenslave-2.6
__salt__['pkg.install']('ifenslave-2.6')
return _read_file(path)
def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'vlan':
settings['vlan'] = 'yes'
__salt__['pkg.install']('vlan')
elif iface_type == 'pppoe':
settings['pppoe'] = 'yes'
if not __salt__['pkg.version']('ppp'):
inst = __salt__['pkg.install']('ppp')
elif iface_type == 'bond':
if 'slaves' not in settings:
msg = 'slaves is a required setting for bond interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'bridge':
if 'ports' not in settings:
msg = (
'ports is a required setting for bridge interfaces on Debian '
'or Ubuntu based systems'
)
log.error(msg)
raise AttributeError(msg)
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'pppoe']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
if iface_type in ['source']:
opts = _parse_settings_source(settings, iface_type, enabled, iface)
if 'test' in settings and settings['test']:
return _read_temp_ifaces(iface, opts[iface])
ifcfg = _write_file_ifaces(iface, opts[iface], **settings)
if iface_type == 'pppoe':
_write_file_ppp_ifaces(iface, opts[iface])
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg]
def build_routes(iface, **settings):
'''
Add route scripts for a network interface using up commands.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
'''
opts = _parse_routes(iface, settings)
try:
template = JINJA.get_template('route_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template route_eth.jinja')
return ''
add_routecfg = template.render(route_type='add',
routes=opts['routes'],
iface=iface)
del_routecfg = template.render(route_type='del',
routes=opts['routes'],
iface=iface)
if 'test' in settings and settings['test']:
return _read_temp(add_routecfg + del_routecfg)
filename = _write_file_routes(iface,
add_routecfg,
_DEB_NETWORK_UP_DIR,
'route-{0}')
results = _read_file(filename)
filename = _write_file_routes(iface,
del_routecfg,
_DEB_NETWORK_DOWN_DIR,
'route-{0}')
results += _read_file(filename)
return results
def down(iface, iface_type):
'''
Shutdown a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.down eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought down.
if iface_type not in ['slave', 'source']:
return __salt__['cmd.run'](['ifdown', iface])
return None
def get_bond(iface):
'''
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
'''
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
return _read_file(path)
def up(iface, iface_type): # pylint: disable=C0103
'''
Start up a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.up eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought up.
if iface_type not in ('slave', 'source'):
return __salt__['cmd.run'](['ifup', iface])
return None
def get_network_settings():
'''
Return the contents of the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_network_settings
'''
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
settings = {}
if __salt__['service.available']('networking'):
if __salt__['service.status']('networking'):
settings['networking'] = "yes"
else:
settings['networking'] = "no"
else:
settings['networking'] = "no"
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
settings['hostname'] = hostname
settings['domainname'] = domainname
settings['searchdomain'] = searchdomain
else:
settings = _parse_current_network_settings()
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(settings)
return _read_temp(network)
def get_routes(iface):
'''
Return the routes for the interface
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0
'''
filename = os.path.join(_DEB_NETWORK_UP_DIR, 'route-{0}'.format(iface))
results = _read_file(filename)
filename = os.path.join(_DEB_NETWORK_DOWN_DIR, 'route-{0}'.format(iface))
results += _read_file(filename)
return results
def apply_network_settings(**settings):
'''
Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings
'''
if 'require_reboot' not in settings:
settings['require_reboot'] = False
if 'apply_hostname' not in settings:
settings['apply_hostname'] = False
hostname_res = True
if settings['apply_hostname'] in _CONFIG_TRUE:
if 'hostname' in settings:
hostname_res = __salt__['network.mod_hostname'](settings['hostname'])
else:
log.warning(
'The network state sls is trying to apply hostname '
'changes but no hostname is defined.'
)
hostname_res = False
res = True
if settings['require_reboot'] in _CONFIG_TRUE:
log.warning(
'The network state sls is requiring a reboot of the system to '
'properly apply network configuration.'
)
res = True
else:
stop = __salt__['service.stop']('networking')
time.sleep(2)
res = stop and __salt__['service.start']('networking')
return hostname_res and res
def build_network_settings(**settings):
'''
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
'''
changes = []
# Read current configuration and store default values
current_network_settings = _parse_current_network_settings()
# Build settings
opts = _parse_network_settings(settings, current_network_settings)
# Ubuntu has moved away from /etc/default/networking
# beginning with the 12.04 release so we disable or enable
# the networking related services on boot
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
if opts['networking'] == 'yes':
service_cmd = 'service.enable'
else:
service_cmd = 'service.disable'
if __salt__['service.available']('NetworkManager'):
__salt__[service_cmd]('NetworkManager')
if __salt__['service.available']('networking'):
__salt__[service_cmd]('networking')
else:
try:
template = JINJA.get_template('network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template network.jinja')
return ''
network = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(network)
# Write settings
_write_file_network(network, _DEB_NETWORKING_FILE, True)
# Get hostname and domain from opts
sline = opts['hostname'].split('.', 1)
opts['hostname'] = sline[0]
current_domainname = current_network_settings['domainname']
current_searchdomain = current_network_settings['searchdomain']
new_domain = False
if len(sline) > 1:
new_domainname = sline[1]
if new_domainname != current_domainname:
domainname = new_domainname
opts['domainname'] = new_domainname
new_domain = True
else:
domainname = current_domainname
opts['domainname'] = domainname
else:
domainname = current_domainname
opts['domainname'] = domainname
new_search = False
if 'search' in opts:
new_searchdomain = opts['search']
if new_searchdomain != current_searchdomain:
searchdomain = new_searchdomain
opts['searchdomain'] = new_searchdomain
new_search = True
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
# If the domain changes, then we should write the resolv.conf file.
if new_domain or new_search:
# Look for existing domain line and update if necessary
resolve = _parse_resolve()
domain_prog = re.compile(r'domain\s+')
search_prog = re.compile(r'search\s+')
new_contents = []
for item in _read_file(_DEB_RESOLV_FILE):
if domain_prog.match(item):
item = 'domain {0}'.format(domainname)
elif search_prog.match(item):
item = 'search {0}'.format(searchdomain)
new_contents.append(item)
# A domain line didn't exist so we'll add one in
# with the new domainname
if 'domain' not in resolve:
new_contents.insert(0, 'domain {0}' . format(domainname))
# A search line didn't exist so we'll add one in
# with the new search domain
if 'search' not in resolve:
new_contents.insert('domain' in resolve, 'search {0}'.format(searchdomain))
new_resolv = '\n'.join(new_contents)
# Write /etc/resolv.conf
if not ('test' in settings and settings['test']):
_write_file_network(new_resolv, _DEB_RESOLV_FILE)
# used for returning the results back
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(opts)
changes.extend(_read_temp(network))
return changes
|
saltstack/salt
|
salt/modules/debian_ip.py
|
get_network_settings
|
python
|
def get_network_settings():
'''
Return the contents of the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_network_settings
'''
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
settings = {}
if __salt__['service.available']('networking'):
if __salt__['service.status']('networking'):
settings['networking'] = "yes"
else:
settings['networking'] = "no"
else:
settings['networking'] = "no"
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
settings['hostname'] = hostname
settings['domainname'] = domainname
settings['searchdomain'] = searchdomain
else:
settings = _parse_current_network_settings()
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(settings)
return _read_temp(network)
|
Return the contents of the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_network_settings
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_ip.py#L1795-L1837
|
[
"def _read_temp(data):\n '''\n Return what would be written to disk\n '''\n tout = StringIO()\n tout.write(data)\n tout.seek(0)\n output = tout.readlines()\n tout.close()\n\n return output\n"
] |
# -*- coding: utf-8 -*-
'''
The networking module for Debian-based distros
References:
* http://www.debian.org/doc/manuals/debian-reference/ch05.en.html
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import functools
import logging
import os.path
import os
import re
import time
# Import third party libs
import jinja2
import jinja2.exceptions
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error,no-name-in-module
# Import salt libs
import salt.utils.dns
import salt.utils.files
import salt.utils.odict
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.validate.net
# Set up logging
log = logging.getLogger(__name__)
# Set up template environment
JINJA = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'debian_ip')
)
)
# Define the module's virtual name
__virtualname__ = 'ip'
def __virtual__():
'''
Confine this module to Debian-based distros
'''
if __grains__['os_family'] == 'Debian':
return __virtualname__
return (False, 'The debian_ip module could not be loaded: '
'unsupported OS family')
_ETHTOOL_CONFIG_OPTS = {
'speed': 'link-speed',
'duplex': 'link-duplex',
'autoneg': 'ethernet-autoneg',
'ethernet-port': 'ethernet-port',
'wol': 'ethernet-wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'rx': 'offload-rx',
'tx': 'offload-tx',
'sg': 'offload-sg',
'tso': 'offload-tso',
'ufo': 'offload-ufo',
'gso': 'offload-gso',
'gro': 'offload-gro',
'lro': 'offload-lro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_REV_ETHTOOL_CONFIG_OPTS = {
'link-speed': 'speed',
'link-duplex': 'duplex',
'ethernet-autoneg': 'autoneg',
'ethernet-port': 'ethernet-port',
'ethernet-wol': 'wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'offload-rx': 'rx',
'offload-tx': 'tx',
'offload-sg': 'sg',
'offload-tso': 'tso',
'offload-ufo': 'ufo',
'offload-gso': 'gso',
'offload-lro': 'lro',
'offload-gro': 'gro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_DEB_CONFIG_PPPOE_OPTS = {
'user': 'user',
'password': 'password',
'provider': 'provider',
'pppoe_iface': 'pppoe_iface',
'noipdefault': 'noipdefault',
'usepeerdns': 'usepeerdns',
'defaultroute': 'defaultroute',
'holdoff': 'holdoff',
'maxfail': 'maxfail',
'hide-password': 'hide-password',
'lcp-echo-interval': 'lcp-echo-interval',
'lcp-echo-failure': 'lcp-echo-failure',
'connect': 'connect',
'noauth': 'noauth',
'persist': 'persist',
'mtu': 'mtu',
'noaccomp': 'noaccomp',
'linkname': 'linkname',
}
_DEB_ROUTES_FILE = '/etc/network/routes'
_DEB_NETWORK_FILE = '/etc/network/interfaces'
_DEB_NETWORK_DIR = '/etc/network/interfaces.d/'
_DEB_NETWORK_UP_DIR = '/etc/network/if-up.d/'
_DEB_NETWORK_DOWN_DIR = '/etc/network/if-down.d/'
_DEB_NETWORK_CONF_FILES = '/etc/modprobe.d/'
_DEB_NETWORKING_FILE = '/etc/default/networking'
_DEB_HOSTNAME_FILE = '/etc/hostname'
_DEB_RESOLV_FILE = '/etc/resolv.conf'
_DEB_PPP_DIR = '/etc/ppp/peers/'
_CONFIG_TRUE = ['yes', 'on', 'true', '1', True]
_CONFIG_FALSE = ['no', 'off', 'false', '0', False]
_IFACE_TYPES = [
'eth', 'bond', 'alias', 'clone',
'ipsec', 'dialup', 'bridge', 'slave',
'vlan', 'pppoe', 'source',
]
def _error_msg_iface(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, '|'.join(str(e) for e in expected))
def _error_msg_routes(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, expected)
def _log_default_iface(iface, opt, value):
log.info(
'Using default option -- Interface: %s Option: %s Value: %s',
iface, opt, value
)
def _error_msg_network(option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]'
return msg.format(option, '|'.join(str(e) for e in expected))
def _log_default_network(opt, value):
log.info('Using existing setting -- Setting: %s Value: %s', opt, value)
def _raise_error_iface(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_iface(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_network(option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_network(option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_routes(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_routes(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _read_file(path):
'''
Reads and returns the contents of a text file
'''
try:
with salt.utils.files.flopen(path, 'rb') as contents:
return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]
except (OSError, IOError):
return ''
def _parse_resolve():
'''
Parse /etc/resolv.conf
'''
return salt.utils.dns.parse_resolv(_DEB_RESOLV_FILE)
def _parse_domainname():
'''
Parse /etc/resolv.conf and return domainname
'''
return _parse_resolve().get('domain', '')
def _parse_searchdomain():
'''
Parse /etc/resolv.conf and return searchdomain
'''
return _parse_resolve().get('search', '')
def _parse_hostname():
'''
Parse /etc/hostname and return hostname
'''
contents = _read_file(_DEB_HOSTNAME_FILE)
if contents:
return contents[0].split('\n')[0]
else:
return ''
def _parse_current_network_settings():
'''
Parse /etc/default/networking and return current configuration
'''
opts = salt.utils.odict.OrderedDict()
opts['networking'] = ''
if os.path.isfile(_DEB_NETWORKING_FILE):
with salt.utils.files.fopen(_DEB_NETWORKING_FILE) as contents:
for line in contents:
salt.utils.stringutils.to_unicode(line)
if line.startswith('#'):
continue
elif line.startswith('CONFIGURE_INTERFACES'):
opts['networking'] = line.split('=', 1)[1].strip()
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
opts['hostname'] = hostname
opts['domainname'] = domainname
opts['searchdomain'] = searchdomain
return opts
# def __validator_func(value):
# return (valid: True/False, (transformed) value, error message)
def __ipv4_quad(value):
'''validate an IPv4 address'''
return (salt.utils.validate.net.ipv4_addr(value), value,
'dotted IPv4 address')
def __ipv6(value):
'''validate an IPv6 address'''
return (salt.utils.validate.net.ipv6_addr(value), value,
'IPv6 address')
def __mac(value):
'''validate a mac address'''
return (salt.utils.validate.net.mac(value), value,
'MAC address')
def __anything(value):
return (True, value, None)
def __int(value):
'''validate an integer'''
valid, _value = False, value
try:
_value = int(value)
valid = True
except ValueError:
pass
return (valid, _value, 'integer')
def __float(value):
'''validate a float'''
valid, _value = False, value
try:
_value = float(value)
valid = True
except ValueError:
pass
return (valid, _value, 'float')
def __ipv4_netmask(value):
'''validate an IPv4 dotted quad or integer CIDR netmask'''
valid, errmsg = False, 'dotted quad or integer CIDR (0->32)'
valid, value, _ = __int(value)
if not (valid and 0 <= value <= 32):
valid = salt.utils.validate.net.netmask(value)
return (valid, value, errmsg)
def __ipv6_netmask(value):
'''validate an IPv6 integer netmask'''
valid, errmsg = False, 'IPv6 netmask (0->128)'
valid, value, _ = __int(value)
valid = (valid and 0 <= value <= 128)
return (valid, value, errmsg)
def __within2(value, within=None, errmsg=None, dtype=None):
'''validate that a value is in ``within`` and optionally a ``dtype``'''
valid, _value = False, value
if dtype:
try:
_value = dtype(value) # TODO: this is a bit loose when dtype is a class
valid = _value in within
except ValueError:
pass
else:
valid = _value in within
if errmsg is None:
if dtype:
typename = getattr(dtype, '__name__',
hasattr(dtype, '__class__')
and getattr(dtype.__class__, 'name', dtype))
errmsg = '{0} within \'{1}\''.format(typename, within)
else:
errmsg = 'within \'{0}\''.format(within)
return (valid, _value, errmsg)
def __within(within=None, errmsg=None, dtype=None):
return functools.partial(__within2, within=within,
errmsg=errmsg, dtype=dtype)
def __space_delimited_list(value):
'''validate that a value contains one or more space-delimited values'''
if isinstance(value, six.string_types):
value = value.strip().split()
if hasattr(value, '__iter__') and value != []:
return (True, value, 'space-delimited string')
else:
return (False, value, '{0} is not a valid space-delimited value.\n'.format(value))
SALT_ATTR_TO_DEBIAN_ATTR_MAP = {
'dns': 'dns-nameservers',
'search': 'dns-search',
'hwaddr': 'hwaddress', # TODO: this limits bootp functionality
'ipaddr': 'address',
'ipaddrs': 'addresses',
}
DEBIAN_ATTR_TO_SALT_ATTR_MAP = dict(
(v, k) for (k, v) in six.iteritems(SALT_ATTR_TO_DEBIAN_ATTR_MAP))
# TODO
DEBIAN_ATTR_TO_SALT_ATTR_MAP['address'] = 'address'
DEBIAN_ATTR_TO_SALT_ATTR_MAP['hwaddress'] = 'hwaddress'
IPV4_VALID_PROTO = ['bootp', 'dhcp', 'static', 'manual', 'loopback', 'ppp']
IPV4_ATTR_MAP = {
'proto': __within(IPV4_VALID_PROTO, dtype=six.text_type),
# ipv4 static & manual
'address': __ipv4_quad,
'addresses': __anything,
'netmask': __ipv4_netmask,
'broadcast': __ipv4_quad,
'metric': __int,
'gateway': __ipv4_quad, # supports a colon-delimited list
'pointopoint': __ipv4_quad,
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'link', 'host'], dtype=six.text_type),
# dhcp
'hostname': __anything,
'leasehours': __int,
'leasetime': __int,
'vendor': __anything,
'client': __anything,
# bootp
'bootfile': __anything,
'server': __ipv4_quad,
'hwaddr': __mac,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'dstaddr': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# bond
'slaves': __anything,
# ppp
'provider': __anything,
'unit': __int,
'options': __anything,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
#
'network': __anything, # i don't know what this is
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
IPV6_VALID_PROTO = ['auto', 'loopback', 'static', 'manual',
'dhcp', 'v4tunnel', '6to4']
IPV6_ATTR_MAP = {
'proto': __within(IPV6_VALID_PROTO),
# ipv6 static & manual
'address': __ipv6,
'addresses': __anything,
'netmask': __ipv6_netmask,
'broadcast': __ipv6,
'gateway': __ipv6, # supports a colon-delimited list
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'site', 'link', 'host'], dtype=six.text_type),
# inet6 auto
'privext': __within([0, 1, 2], dtype=int),
'dhcp': __within([0, 1], dtype=int),
# inet6 static & manual & dhcp
'media': __anything,
'accept_ra': __within([0, 1], dtype=int),
'autoconf': __within([0, 1], dtype=int),
'preferred-lifetime': __int,
'dad-attempts': __int, # 0 to disable
'dad-interval': __float,
# bond
'slaves': __anything,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
WIRELESS_ATTR_MAP = {
'wireless-essid': __anything,
'wireless-mode': __anything, # TODO
'wpa-ap-scan': __within([0, 1, 2], dtype=int), # TODO
'wpa-conf': __anything,
'wpa-driver': __anything,
'wpa-group': __anything,
'wpa-key-mgmt': __anything,
'wpa-pairwise': __anything,
'wpa-psk': __anything,
'wpa-proto': __anything, # partial(__within,
'wpa-roam': __anything,
'wpa-ssid': __anything, # TODO
}
ATTRMAPS = {
'inet': [IPV4_ATTR_MAP, WIRELESS_ATTR_MAP],
'inet6': [IPV6_ATTR_MAP, WIRELESS_ATTR_MAP]
}
def _validate_interface_option(attr, value, addrfam='inet'):
'''lookup the validation function for a [addrfam][attr] and
return the results
:param attr: attribute name
:param value: raw setting value
:param addrfam: address family (inet, inet6,
'''
valid, _value, errmsg = False, value, 'Unknown validator'
attrmaps = ATTRMAPS.get(addrfam, [])
for attrmap in attrmaps:
if attr in attrmap:
validate_func = attrmap[attr]
(valid, _value, errmsg) = validate_func(value)
break
return (valid, _value, errmsg)
def _attrmaps_contain_attr(attr):
return (
attr in WIRELESS_ATTR_MAP or
attr in IPV4_ATTR_MAP or
attr in IPV6_ATTR_MAP)
def _parse_interfaces(interface_files=None):
'''
Parse /etc/network/interfaces and return current configured interfaces
'''
if interface_files is None:
interface_files = []
# Add this later.
if os.path.exists(_DEB_NETWORK_DIR):
interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]
if os.path.isfile(_DEB_NETWORK_FILE):
interface_files.insert(0, _DEB_NETWORK_FILE)
adapters = salt.utils.odict.OrderedDict()
method = -1
for interface_file in interface_files:
with salt.utils.files.fopen(interface_file) as interfaces:
# This ensures iface_dict exists, but does not ensure we're not reading a new interface.
iface_dict = {}
for line in interfaces:
line = salt.utils.stringutils.to_unicode(line)
# Identify the clauses by the first word of each line.
# Go to the next line if the current line is a comment
# or all spaces.
if line.lstrip().startswith('#') or line.isspace():
continue
# Parse the iface clause
if line.startswith('iface'):
sline = line.split()
if len(sline) != 4:
msg = 'Interface file malformed: {0}.'
msg = msg.format(sline)
log.error(msg)
raise AttributeError(msg)
iface_name = sline[1]
addrfam = sline[2]
method = sline[3]
# Create item in dict, if not already there
if iface_name not in adapters:
adapters[iface_name] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters[iface_name]:
adapters[iface_name]['data'] = salt.utils.odict.OrderedDict()
if addrfam not in adapters[iface_name]['data']:
adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict()
iface_dict = adapters[iface_name]['data'][addrfam]
iface_dict['addrfam'] = addrfam
iface_dict['proto'] = method
iface_dict['filename'] = interface_file
# Parse the detail clauses.
elif line[0].isspace():
sline = line.split()
# conf file attr: dns-nameservers
# salt states.network attr: dns
attr, valuestr = line.rstrip().split(None, 1)
if _attrmaps_contain_attr(attr):
if '-' in attr:
attrname = attr.replace('-', '_')
else:
attrname = attr
(valid, value, errmsg) = _validate_interface_option(
attr, valuestr, addrfam)
if attrname == 'address' and 'address' in iface_dict:
if 'addresses' not in iface_dict:
iface_dict['addresses'] = []
iface_dict['addresses'].append(value)
else:
iface_dict[attrname] = value
elif attr in _REV_ETHTOOL_CONFIG_OPTS:
if 'ethtool' not in iface_dict:
iface_dict['ethtool'] = salt.utils.odict.OrderedDict()
iface_dict['ethtool'][attr] = valuestr
elif attr.startswith('bond'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bonding' not in iface_dict:
iface_dict['bonding'] = salt.utils.odict.OrderedDict()
iface_dict['bonding'][opt] = valuestr
elif attr.startswith('bridge'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bridging' not in iface_dict:
iface_dict['bridging'] = salt.utils.odict.OrderedDict()
iface_dict['bridging'][opt] = valuestr
elif attr in ['up', 'pre-up', 'post-up',
'down', 'pre-down', 'post-down']:
cmd = valuestr
cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr))
if cmd_key not in iface_dict:
iface_dict[cmd_key] = []
iface_dict[cmd_key].append(cmd)
elif line.startswith('auto'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['enabled'] = True
elif line.startswith('allow-hotplug'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['hotplug'] = True
elif line.startswith('source'):
if 'source' not in adapters:
adapters['source'] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters['source']:
adapters['source']['data'] = salt.utils.odict.OrderedDict()
adapters['source']['data']['sources'] = []
adapters['source']['data']['sources'].append(line.split()[1])
# Return a sorted list of the keys for bond, bridge and ethtool options to
# ensure a consistent order
for iface_name in adapters:
if iface_name == 'source':
continue
if 'data' not in adapters[iface_name]:
msg = 'Interface file malformed for interface: {0}.'.format(iface_name)
log.error(msg)
adapters.pop(iface_name)
continue
for opt in ['ethtool', 'bonding', 'bridging']:
for inet in ['inet', 'inet6']:
if inet in adapters[iface_name]['data']:
if opt in adapters[iface_name]['data'][inet]:
opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys())
adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys
return adapters
def _parse_ethtool_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
if 'autoneg' in opts:
if opts['autoneg'] in _CONFIG_TRUE:
config.update({'autoneg': 'on'})
elif opts['autoneg'] in _CONFIG_FALSE:
config.update({'autoneg': 'off'})
else:
_raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE)
if 'duplex' in opts:
valid = ['full', 'half']
if opts['duplex'] in valid:
config.update({'duplex': opts['duplex']})
else:
_raise_error_iface(iface, 'duplex', valid)
if 'speed' in opts:
valid = ['10', '100', '1000', '10000']
if six.text_type(opts['speed']) in valid:
config.update({'speed': opts['speed']})
else:
_raise_error_iface(iface, opts['speed'], valid)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'on'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'off'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_ethtool_pppoe_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
for opt in _DEB_CONFIG_PPPOE_OPTS:
if opt in opts:
config[opt] = opts[opt]
if 'provider' in opts and not opts['provider']:
_raise_error_iface(iface, 'provider', _CONFIG_TRUE + _CONFIG_FALSE)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('noipdefault', 'usepeerdns', 'defaultroute', 'hide-password', 'noauth', 'persist', 'noaccomp'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'True'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'False'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_settings_bond(opts, iface):
'''
Filters given options and outputs valid settings for requested
operation. If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond_def = {
# 803.ad aggregation selection logic
# 0 for stable (default)
# 1 for bandwidth
# 2 for count
'ad_select': '0',
# Max number of transmit queues (default = 16)
'tx_queues': '16',
# Link monitoring in milliseconds. Most NICs support this
'miimon': '100',
# ARP interval in milliseconds
'arp_interval': '250',
# Delay before considering link down in milliseconds (miimon * 2)
'downdelay': '200',
# lacp_rate 0: Slow - every 30 seconds
# lacp_rate 1: Fast - every 1 second
'lacp_rate': '0',
# Max bonds for this driver
'max_bonds': '1',
# Specifies the time, in milliseconds, to wait before
# enabling a slave after a link recovery has been
# detected. Only used with miimon.
'updelay': '0',
# Used with miimon.
# On: driver sends mii
# Off: ethtool sends mii
'use_carrier': 'on',
# Default. Don't change unless you know what you are doing.
'xmit_hash_policy': 'layer2',
}
if opts['mode'] in ['balance-rr', '0']:
log.info('Device: %s Bonding Mode: load balancing (round-robin)', iface)
return _parse_settings_bond_0(opts, iface, bond_def)
elif opts['mode'] in ['active-backup', '1']:
log.info('Device: %s Bonding Mode: fault-tolerance (active-backup)', iface)
return _parse_settings_bond_1(opts, iface, bond_def)
elif opts['mode'] in ['balance-xor', '2']:
log.info('Device: %s Bonding Mode: load balancing (xor)', iface)
return _parse_settings_bond_2(opts, iface, bond_def)
elif opts['mode'] in ['broadcast', '3']:
log.info('Device: %s Bonding Mode: fault-tolerance (broadcast)', iface)
return _parse_settings_bond_3(opts, iface, bond_def)
elif opts['mode'] in ['802.3ad', '4']:
log.info('Device: %s Bonding Mode: IEEE 802.3ad Dynamic link '
'aggregation', iface)
return _parse_settings_bond_4(opts, iface, bond_def)
elif opts['mode'] in ['balance-tlb', '5']:
log.info('Device: %s Bonding Mode: transmit load balancing', iface)
return _parse_settings_bond_5(opts, iface, bond_def)
elif opts['mode'] in ['balance-alb', '6']:
log.info('Device: %s Bonding Mode: adaptive load balancing', iface)
return _parse_settings_bond_6(opts, iface, bond_def)
else:
valid = [
'0', '1', '2', '3', '4', '5', '6',
'balance-rr', 'active-backup', 'balance-xor',
'broadcast', '802.3ad', 'balance-tlb', 'balance-alb'
]
_raise_error_iface(iface, 'mode', valid)
def _parse_settings_bond_0(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond0.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '0'}
# ARP targets in n.n.n.n form
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
return bond
def _parse_settings_bond_1(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '1'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
if not (__grains__['os'] == "Ubuntu" and __grains__['osrelease_info'][0] >= 16):
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_2(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond2.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '2'}
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_3(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond3.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '3'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_4(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond4.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '4'}
for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']:
if binding in opts:
if binding == 'lacp_rate':
if opts[binding] == 'fast':
opts.update({binding: '1'})
if opts[binding] == 'slow':
opts.update({binding: '0'})
valid = ['fast', '1', 'slow', '0']
else:
valid = ['integer']
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, valid)
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_5(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond5.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '5'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_settings_bond_6(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond6.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '6'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_bridge_opts(opts, iface):
'''
Filters given options and outputs valid settings for BRIDGING_OPTS
If an option has a value that is not expected, this
function will log the Interface, Setting and what was expected.
'''
config = {}
if 'ports' in opts:
if isinstance(opts['ports'], list):
opts['ports'] = ' '.join(opts['ports'])
config.update({'ports': opts['ports']})
for opt in ['ageing', 'fd', 'gcint', 'hello', 'maxage']:
if opt in opts:
try:
float(opts[opt])
config.update({opt: opts[opt]})
except ValueError:
_raise_error_iface(iface, opt, ['float'])
for opt in ['bridgeprio', 'maxwait']:
if opt in opts:
if isinstance(opts[opt], int):
config.update({opt: opts[opt]})
else:
_raise_error_iface(iface, opt, ['integer'])
if 'hw' in opts:
# match 12 hex digits with either : or - as separators between pairs
if re.match('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$',
opts['hw'].lower()):
config.update({'hw': opts['hw']})
else:
_raise_error_iface(iface, 'hw', ['valid MAC address'])
for opt in ['pathcost', 'portprio']:
if opt in opts:
try:
port, cost_or_prio = opts[opt].split()
int(cost_or_prio)
config.update({opt: '{0} {1}'.format(port, cost_or_prio)})
except ValueError:
_raise_error_iface(iface, opt, ['interface integer'])
if 'stp' in opts:
if opts['stp'] in _CONFIG_TRUE:
config.update({'stp': 'on'})
elif opts['stp'] in _CONFIG_FALSE:
config.update({'stp': 'off'})
else:
_raise_error_iface(iface, 'stp', _CONFIG_TRUE + _CONFIG_FALSE)
if 'waitport' in opts:
if isinstance(opts['waitport'], int):
config.update({'waitport': opts['waitport']})
else:
values = opts['waitport'].split()
waitport_time = values.pop(0)
if waitport_time.isdigit() and values:
config.update({
'waitport': '{0} {1}'.format(
waitport_time, ' '.join(values)
)
})
else:
_raise_error_iface(iface, opt, ['integer [interfaces]'])
return config
def _parse_settings_eth(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['inet'] = salt.utils.odict.OrderedDict()
iface_data['inet6'] = salt.utils.odict.OrderedDict()
if enabled:
adapters[iface]['enabled'] = True
if opts.get('hotplug', False):
adapters[iface]['hotplug'] = True
if opts.get('enable_ipv6', None) and opts.get('iface_type', '') == 'vlan':
iface_data['inet6']['vlan_raw_device'] = (
re.sub(r'\.\d*', '', iface))
for addrfam in ['inet', 'inet6']:
if iface_type not in ['bridge']:
tmp_ethtool = _parse_ethtool_opts(opts, iface)
if tmp_ethtool:
ethtool = {}
for item in tmp_ethtool:
ethtool[_ETHTOOL_CONFIG_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['ethtool'] = ethtool
# return a list of sorted keys to ensure consistent order
iface_data[addrfam]['ethtool_keys'] = sorted(ethtool)
if iface_type == 'bridge':
bridging = _parse_bridge_opts(opts, iface)
if bridging:
iface_data[addrfam]['bridging'] = bridging
iface_data[addrfam]['bridging_keys'] = sorted(bridging)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'bond':
bonding = _parse_settings_bond(opts, iface)
if bonding:
iface_data[addrfam]['bonding'] = bonding
iface_data[addrfam]['bonding']['slaves'] = opts['slaves']
iface_data[addrfam]['bonding_keys'] = sorted(bonding)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'slave':
adapters[iface]['master'] = opts['master']
opts['proto'] = 'manual'
iface_data[addrfam]['master'] = adapters[iface]['master']
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'vlan':
iface_data[addrfam]['vlan_raw_device'] = re.sub(r'\.\d*', '', iface)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'pppoe':
tmp_ethtool = _parse_ethtool_pppoe_opts(opts, iface)
if tmp_ethtool:
for item in tmp_ethtool:
adapters[iface]['data'][addrfam][_DEB_CONFIG_PPPOE_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['addrfam'] = addrfam
opts.pop('mode', None)
for opt, val in opts.items():
inet = None
if opt.startswith('ipv4'):
opt = opt[4:]
inet = 'inet'
iface_data['inet']['addrfam'] = 'inet'
elif opt.startswith('ipv6'):
iface_data['inet6']['addrfam'] = 'inet6'
opt = opt[4:]
inet = 'inet6'
elif opt in ['ipaddr', 'address', 'ipaddresses', 'addresses', 'gateway', 'proto']:
iface_data['inet']['addrfam'] = 'inet'
inet = 'inet'
_opt = SALT_ATTR_TO_DEBIAN_ATTR_MAP.get(opt, opt)
_debopt = _opt.replace('-', '_')
for addrfam in ['inet', 'inet6']:
(valid, value, errmsg) = _validate_interface_option(_opt, val, addrfam=addrfam)
if not valid:
continue
if inet is None and _debopt not in iface_data[addrfam]:
iface_data[addrfam][_debopt] = value
elif inet == addrfam:
iface_data[addrfam][_debopt] = value
for opt in ['up_cmds', 'pre_up_cmds', 'post_up_cmds',
'down_cmds', 'pre_down_cmds', 'post_down_cmds']:
if opt in opts:
iface_data['inet'][opt] = opts[opt]
iface_data['inet6'][opt] = opts[opt]
# Remove incomplete/disabled inet blocks
for (addrfam, opt) in [('inet', 'enable_ipv4'), ('inet6', 'enable_ipv6')]:
if opts.get(opt, None) is False:
iface_data.pop(addrfam)
elif iface_data[addrfam].get('addrfam', '') != addrfam:
iface_data.pop(addrfam)
return adapters
def _parse_settings_source(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['sources'] = [opts['source']]
return adapters
def _parse_network_settings(opts, current):
'''
Filters given options and outputs valid settings for
the global network settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
current = dict((k.lower(), v) for (k, v) in six.iteritems(current))
result = {}
valid = _CONFIG_TRUE + _CONFIG_FALSE
if 'enabled' not in opts:
try:
opts['networking'] = current['networking']
_log_default_network('networking', current['networking'])
except ValueError:
_raise_error_network('networking', valid)
else:
opts['networking'] = opts['enabled']
if opts['networking'] in valid:
if opts['networking'] in _CONFIG_TRUE:
result['networking'] = 'yes'
elif opts['networking'] in _CONFIG_FALSE:
result['networking'] = 'no'
else:
_raise_error_network('networking', valid)
if 'hostname' not in opts:
try:
opts['hostname'] = current['hostname']
_log_default_network('hostname', current['hostname'])
except ValueError:
_raise_error_network('hostname', ['server1.example.com'])
if opts['hostname']:
result['hostname'] = opts['hostname']
else:
_raise_error_network('hostname', ['server1.example.com'])
if 'search' in opts:
result['search'] = opts['search']
return result
def _parse_routes(iface, opts):
'''
Filters given options and outputs valid settings for
the route settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
result = {}
if 'routes' not in opts:
_raise_error_routes(iface, 'routes', 'List of routes')
for opt in opts:
result[opt] = opts[opt]
return result
def _write_file(iface, data, folder, pattern):
'''
Writes a file to disk
'''
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
return filename
def _write_file_routes(iface, data, folder, pattern):
'''
Writes a file to disk
'''
# ifup / ifdown is executing given folder via run-parts.
# according to run-parts man-page, only filenames with this pattern are
# executed: (^[a-zA-Z0-9_-]+$)
# In order to make the routes file work for vlan interfaces
# (default would have been in example /etc/network/if-up.d/route-bond0.12)
# these dots in the iface name need to be replaced by underscores, so it
# can be executed by run-parts
iface = iface.replace('.', '_')
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
__salt__['file.set_mode'](filename, '0755')
return filename
def _write_file_network(data, filename, create=False):
'''
Writes a file to disk
If file does not exist, only create if create
argument is True
'''
if not os.path.exists(filename) and not create:
msg = '{0} cannot be written. {0} does not exist\
and create is set to False'
msg = msg.format(filename)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
def _read_temp(data):
'''
Return what would be written to disk
'''
tout = StringIO()
tout.write(data)
tout.seek(0)
output = tout.readlines()
tout.close()
return output
def _read_temp_ifaces(iface, data):
'''
Return what would be written to disk for interfaces
'''
try:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': data})
# Return as an array so the difflib works
return [item + '\n' for item in ifcfg.split('\n')]
def _write_file_ifaces(iface, data, **settings):
'''
Writes a file to disk
'''
try:
eth_template = JINJA.get_template('debian_eth.jinja')
source_template = JINJA.get_template('debian_source.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
# Read /etc/network/interfaces into a dict
adapters = _parse_interfaces()
# Apply supplied settings over on-disk settings
adapters[iface] = data
ifcfg = ''
for adapter in adapters:
if 'type' in adapters[adapter] and adapters[adapter]['type'] == 'source':
tmp = source_template.render({'name': adapter, 'data': adapters[adapter]})
else:
tmp = eth_template.render({'name': adapter, 'data': adapters[adapter]})
ifcfg = ifcfg + tmp
if adapter == iface:
saved_ifcfg = tmp
_SEPARATE_FILE = False
if 'filename' in settings:
if not settings['filename'].startswith('/'):
filename = '{0}/{1}'.format(_DEB_NETWORK_DIR, settings['filename'])
else:
filename = settings['filename']
_SEPARATE_FILE = True
else:
if 'filename' in adapters[adapter]['data']:
filename = adapters[adapter]['data']
else:
filename = _DEB_NETWORK_FILE
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
if _SEPARATE_FILE:
fout.write(salt.utils.stringutils.to_str(saved_ifcfg))
else:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return saved_ifcfg.split('\n')
def _write_file_ppp_ifaces(iface, data):
'''
Writes a file to disk
'''
try:
template = JINJA.get_template('debian_ppp_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_ppp_eth.jinja')
return ''
adapters = _parse_interfaces()
adapters[iface] = data
ifcfg = ''
tmp = template.render({'data': adapters[iface]})
ifcfg = tmp + ifcfg
filename = _DEB_PPP_DIR + '/' + adapters[iface]['data']['inet']['provider']
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.fopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return filename
def build_bond(iface, **settings):
'''
Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb
'''
deb_major = __grains__['osrelease'][:1]
opts = _parse_settings_bond(settings, iface)
try:
template = JINJA.get_template('conf.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template conf.jinja')
return ''
data = template.render({'name': iface, 'bonding': opts})
if 'test' in settings and settings['test']:
return _read_temp(data)
_write_file(iface, data, _DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
if deb_major == '5':
for line_type in ('alias', 'options'):
cmd = ['sed', '-i', '-e', r'/^{0}\s{1}.*/d'.format(line_type, iface),
'/etc/modprobe.conf']
__salt__['cmd.run'](cmd, python_shell=False)
__salt__['file.append']('/etc/modprobe.conf', path)
# Load kernel module
__salt__['kmod.load']('bonding')
# install ifenslave-2.6
__salt__['pkg.install']('ifenslave-2.6')
return _read_file(path)
def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'vlan':
settings['vlan'] = 'yes'
__salt__['pkg.install']('vlan')
elif iface_type == 'pppoe':
settings['pppoe'] = 'yes'
if not __salt__['pkg.version']('ppp'):
inst = __salt__['pkg.install']('ppp')
elif iface_type == 'bond':
if 'slaves' not in settings:
msg = 'slaves is a required setting for bond interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'bridge':
if 'ports' not in settings:
msg = (
'ports is a required setting for bridge interfaces on Debian '
'or Ubuntu based systems'
)
log.error(msg)
raise AttributeError(msg)
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'pppoe']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
if iface_type in ['source']:
opts = _parse_settings_source(settings, iface_type, enabled, iface)
if 'test' in settings and settings['test']:
return _read_temp_ifaces(iface, opts[iface])
ifcfg = _write_file_ifaces(iface, opts[iface], **settings)
if iface_type == 'pppoe':
_write_file_ppp_ifaces(iface, opts[iface])
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg]
def build_routes(iface, **settings):
'''
Add route scripts for a network interface using up commands.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
'''
opts = _parse_routes(iface, settings)
try:
template = JINJA.get_template('route_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template route_eth.jinja')
return ''
add_routecfg = template.render(route_type='add',
routes=opts['routes'],
iface=iface)
del_routecfg = template.render(route_type='del',
routes=opts['routes'],
iface=iface)
if 'test' in settings and settings['test']:
return _read_temp(add_routecfg + del_routecfg)
filename = _write_file_routes(iface,
add_routecfg,
_DEB_NETWORK_UP_DIR,
'route-{0}')
results = _read_file(filename)
filename = _write_file_routes(iface,
del_routecfg,
_DEB_NETWORK_DOWN_DIR,
'route-{0}')
results += _read_file(filename)
return results
def down(iface, iface_type):
'''
Shutdown a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.down eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought down.
if iface_type not in ['slave', 'source']:
return __salt__['cmd.run'](['ifdown', iface])
return None
def get_bond(iface):
'''
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
'''
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
return _read_file(path)
def get_interface(iface):
'''
Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
adapters = _parse_interfaces()
if iface in adapters:
try:
if iface == 'source':
template = JINJA.get_template('debian_source.jinja')
else:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': adapters[iface]})
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg.split('\n')]
else:
return []
def up(iface, iface_type): # pylint: disable=C0103
'''
Start up a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.up eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought up.
if iface_type not in ('slave', 'source'):
return __salt__['cmd.run'](['ifup', iface])
return None
def get_routes(iface):
'''
Return the routes for the interface
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0
'''
filename = os.path.join(_DEB_NETWORK_UP_DIR, 'route-{0}'.format(iface))
results = _read_file(filename)
filename = os.path.join(_DEB_NETWORK_DOWN_DIR, 'route-{0}'.format(iface))
results += _read_file(filename)
return results
def apply_network_settings(**settings):
'''
Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings
'''
if 'require_reboot' not in settings:
settings['require_reboot'] = False
if 'apply_hostname' not in settings:
settings['apply_hostname'] = False
hostname_res = True
if settings['apply_hostname'] in _CONFIG_TRUE:
if 'hostname' in settings:
hostname_res = __salt__['network.mod_hostname'](settings['hostname'])
else:
log.warning(
'The network state sls is trying to apply hostname '
'changes but no hostname is defined.'
)
hostname_res = False
res = True
if settings['require_reboot'] in _CONFIG_TRUE:
log.warning(
'The network state sls is requiring a reboot of the system to '
'properly apply network configuration.'
)
res = True
else:
stop = __salt__['service.stop']('networking')
time.sleep(2)
res = stop and __salt__['service.start']('networking')
return hostname_res and res
def build_network_settings(**settings):
'''
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
'''
changes = []
# Read current configuration and store default values
current_network_settings = _parse_current_network_settings()
# Build settings
opts = _parse_network_settings(settings, current_network_settings)
# Ubuntu has moved away from /etc/default/networking
# beginning with the 12.04 release so we disable or enable
# the networking related services on boot
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
if opts['networking'] == 'yes':
service_cmd = 'service.enable'
else:
service_cmd = 'service.disable'
if __salt__['service.available']('NetworkManager'):
__salt__[service_cmd]('NetworkManager')
if __salt__['service.available']('networking'):
__salt__[service_cmd]('networking')
else:
try:
template = JINJA.get_template('network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template network.jinja')
return ''
network = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(network)
# Write settings
_write_file_network(network, _DEB_NETWORKING_FILE, True)
# Get hostname and domain from opts
sline = opts['hostname'].split('.', 1)
opts['hostname'] = sline[0]
current_domainname = current_network_settings['domainname']
current_searchdomain = current_network_settings['searchdomain']
new_domain = False
if len(sline) > 1:
new_domainname = sline[1]
if new_domainname != current_domainname:
domainname = new_domainname
opts['domainname'] = new_domainname
new_domain = True
else:
domainname = current_domainname
opts['domainname'] = domainname
else:
domainname = current_domainname
opts['domainname'] = domainname
new_search = False
if 'search' in opts:
new_searchdomain = opts['search']
if new_searchdomain != current_searchdomain:
searchdomain = new_searchdomain
opts['searchdomain'] = new_searchdomain
new_search = True
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
# If the domain changes, then we should write the resolv.conf file.
if new_domain or new_search:
# Look for existing domain line and update if necessary
resolve = _parse_resolve()
domain_prog = re.compile(r'domain\s+')
search_prog = re.compile(r'search\s+')
new_contents = []
for item in _read_file(_DEB_RESOLV_FILE):
if domain_prog.match(item):
item = 'domain {0}'.format(domainname)
elif search_prog.match(item):
item = 'search {0}'.format(searchdomain)
new_contents.append(item)
# A domain line didn't exist so we'll add one in
# with the new domainname
if 'domain' not in resolve:
new_contents.insert(0, 'domain {0}' . format(domainname))
# A search line didn't exist so we'll add one in
# with the new search domain
if 'search' not in resolve:
new_contents.insert('domain' in resolve, 'search {0}'.format(searchdomain))
new_resolv = '\n'.join(new_contents)
# Write /etc/resolv.conf
if not ('test' in settings and settings['test']):
_write_file_network(new_resolv, _DEB_RESOLV_FILE)
# used for returning the results back
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(opts)
changes.extend(_read_temp(network))
return changes
|
saltstack/salt
|
salt/modules/debian_ip.py
|
get_routes
|
python
|
def get_routes(iface):
'''
Return the routes for the interface
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0
'''
filename = os.path.join(_DEB_NETWORK_UP_DIR, 'route-{0}'.format(iface))
results = _read_file(filename)
filename = os.path.join(_DEB_NETWORK_DOWN_DIR, 'route-{0}'.format(iface))
results += _read_file(filename)
return results
|
Return the routes for the interface
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_ip.py#L1840-L1857
|
[
"def _read_file(path):\n '''\n Reads and returns the contents of a text file\n '''\n try:\n with salt.utils.files.flopen(path, 'rb') as contents:\n return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]\n except (OSError, IOError):\n return ''\n"
] |
# -*- coding: utf-8 -*-
'''
The networking module for Debian-based distros
References:
* http://www.debian.org/doc/manuals/debian-reference/ch05.en.html
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import functools
import logging
import os.path
import os
import re
import time
# Import third party libs
import jinja2
import jinja2.exceptions
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error,no-name-in-module
# Import salt libs
import salt.utils.dns
import salt.utils.files
import salt.utils.odict
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.validate.net
# Set up logging
log = logging.getLogger(__name__)
# Set up template environment
JINJA = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'debian_ip')
)
)
# Define the module's virtual name
__virtualname__ = 'ip'
def __virtual__():
'''
Confine this module to Debian-based distros
'''
if __grains__['os_family'] == 'Debian':
return __virtualname__
return (False, 'The debian_ip module could not be loaded: '
'unsupported OS family')
_ETHTOOL_CONFIG_OPTS = {
'speed': 'link-speed',
'duplex': 'link-duplex',
'autoneg': 'ethernet-autoneg',
'ethernet-port': 'ethernet-port',
'wol': 'ethernet-wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'rx': 'offload-rx',
'tx': 'offload-tx',
'sg': 'offload-sg',
'tso': 'offload-tso',
'ufo': 'offload-ufo',
'gso': 'offload-gso',
'gro': 'offload-gro',
'lro': 'offload-lro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_REV_ETHTOOL_CONFIG_OPTS = {
'link-speed': 'speed',
'link-duplex': 'duplex',
'ethernet-autoneg': 'autoneg',
'ethernet-port': 'ethernet-port',
'ethernet-wol': 'wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'offload-rx': 'rx',
'offload-tx': 'tx',
'offload-sg': 'sg',
'offload-tso': 'tso',
'offload-ufo': 'ufo',
'offload-gso': 'gso',
'offload-lro': 'lro',
'offload-gro': 'gro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_DEB_CONFIG_PPPOE_OPTS = {
'user': 'user',
'password': 'password',
'provider': 'provider',
'pppoe_iface': 'pppoe_iface',
'noipdefault': 'noipdefault',
'usepeerdns': 'usepeerdns',
'defaultroute': 'defaultroute',
'holdoff': 'holdoff',
'maxfail': 'maxfail',
'hide-password': 'hide-password',
'lcp-echo-interval': 'lcp-echo-interval',
'lcp-echo-failure': 'lcp-echo-failure',
'connect': 'connect',
'noauth': 'noauth',
'persist': 'persist',
'mtu': 'mtu',
'noaccomp': 'noaccomp',
'linkname': 'linkname',
}
_DEB_ROUTES_FILE = '/etc/network/routes'
_DEB_NETWORK_FILE = '/etc/network/interfaces'
_DEB_NETWORK_DIR = '/etc/network/interfaces.d/'
_DEB_NETWORK_UP_DIR = '/etc/network/if-up.d/'
_DEB_NETWORK_DOWN_DIR = '/etc/network/if-down.d/'
_DEB_NETWORK_CONF_FILES = '/etc/modprobe.d/'
_DEB_NETWORKING_FILE = '/etc/default/networking'
_DEB_HOSTNAME_FILE = '/etc/hostname'
_DEB_RESOLV_FILE = '/etc/resolv.conf'
_DEB_PPP_DIR = '/etc/ppp/peers/'
_CONFIG_TRUE = ['yes', 'on', 'true', '1', True]
_CONFIG_FALSE = ['no', 'off', 'false', '0', False]
_IFACE_TYPES = [
'eth', 'bond', 'alias', 'clone',
'ipsec', 'dialup', 'bridge', 'slave',
'vlan', 'pppoe', 'source',
]
def _error_msg_iface(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, '|'.join(str(e) for e in expected))
def _error_msg_routes(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, expected)
def _log_default_iface(iface, opt, value):
log.info(
'Using default option -- Interface: %s Option: %s Value: %s',
iface, opt, value
)
def _error_msg_network(option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]'
return msg.format(option, '|'.join(str(e) for e in expected))
def _log_default_network(opt, value):
log.info('Using existing setting -- Setting: %s Value: %s', opt, value)
def _raise_error_iface(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_iface(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_network(option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_network(option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_routes(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_routes(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _read_file(path):
'''
Reads and returns the contents of a text file
'''
try:
with salt.utils.files.flopen(path, 'rb') as contents:
return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]
except (OSError, IOError):
return ''
def _parse_resolve():
'''
Parse /etc/resolv.conf
'''
return salt.utils.dns.parse_resolv(_DEB_RESOLV_FILE)
def _parse_domainname():
'''
Parse /etc/resolv.conf and return domainname
'''
return _parse_resolve().get('domain', '')
def _parse_searchdomain():
'''
Parse /etc/resolv.conf and return searchdomain
'''
return _parse_resolve().get('search', '')
def _parse_hostname():
'''
Parse /etc/hostname and return hostname
'''
contents = _read_file(_DEB_HOSTNAME_FILE)
if contents:
return contents[0].split('\n')[0]
else:
return ''
def _parse_current_network_settings():
'''
Parse /etc/default/networking and return current configuration
'''
opts = salt.utils.odict.OrderedDict()
opts['networking'] = ''
if os.path.isfile(_DEB_NETWORKING_FILE):
with salt.utils.files.fopen(_DEB_NETWORKING_FILE) as contents:
for line in contents:
salt.utils.stringutils.to_unicode(line)
if line.startswith('#'):
continue
elif line.startswith('CONFIGURE_INTERFACES'):
opts['networking'] = line.split('=', 1)[1].strip()
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
opts['hostname'] = hostname
opts['domainname'] = domainname
opts['searchdomain'] = searchdomain
return opts
# def __validator_func(value):
# return (valid: True/False, (transformed) value, error message)
def __ipv4_quad(value):
'''validate an IPv4 address'''
return (salt.utils.validate.net.ipv4_addr(value), value,
'dotted IPv4 address')
def __ipv6(value):
'''validate an IPv6 address'''
return (salt.utils.validate.net.ipv6_addr(value), value,
'IPv6 address')
def __mac(value):
'''validate a mac address'''
return (salt.utils.validate.net.mac(value), value,
'MAC address')
def __anything(value):
return (True, value, None)
def __int(value):
'''validate an integer'''
valid, _value = False, value
try:
_value = int(value)
valid = True
except ValueError:
pass
return (valid, _value, 'integer')
def __float(value):
'''validate a float'''
valid, _value = False, value
try:
_value = float(value)
valid = True
except ValueError:
pass
return (valid, _value, 'float')
def __ipv4_netmask(value):
'''validate an IPv4 dotted quad or integer CIDR netmask'''
valid, errmsg = False, 'dotted quad or integer CIDR (0->32)'
valid, value, _ = __int(value)
if not (valid and 0 <= value <= 32):
valid = salt.utils.validate.net.netmask(value)
return (valid, value, errmsg)
def __ipv6_netmask(value):
'''validate an IPv6 integer netmask'''
valid, errmsg = False, 'IPv6 netmask (0->128)'
valid, value, _ = __int(value)
valid = (valid and 0 <= value <= 128)
return (valid, value, errmsg)
def __within2(value, within=None, errmsg=None, dtype=None):
'''validate that a value is in ``within`` and optionally a ``dtype``'''
valid, _value = False, value
if dtype:
try:
_value = dtype(value) # TODO: this is a bit loose when dtype is a class
valid = _value in within
except ValueError:
pass
else:
valid = _value in within
if errmsg is None:
if dtype:
typename = getattr(dtype, '__name__',
hasattr(dtype, '__class__')
and getattr(dtype.__class__, 'name', dtype))
errmsg = '{0} within \'{1}\''.format(typename, within)
else:
errmsg = 'within \'{0}\''.format(within)
return (valid, _value, errmsg)
def __within(within=None, errmsg=None, dtype=None):
return functools.partial(__within2, within=within,
errmsg=errmsg, dtype=dtype)
def __space_delimited_list(value):
'''validate that a value contains one or more space-delimited values'''
if isinstance(value, six.string_types):
value = value.strip().split()
if hasattr(value, '__iter__') and value != []:
return (True, value, 'space-delimited string')
else:
return (False, value, '{0} is not a valid space-delimited value.\n'.format(value))
SALT_ATTR_TO_DEBIAN_ATTR_MAP = {
'dns': 'dns-nameservers',
'search': 'dns-search',
'hwaddr': 'hwaddress', # TODO: this limits bootp functionality
'ipaddr': 'address',
'ipaddrs': 'addresses',
}
DEBIAN_ATTR_TO_SALT_ATTR_MAP = dict(
(v, k) for (k, v) in six.iteritems(SALT_ATTR_TO_DEBIAN_ATTR_MAP))
# TODO
DEBIAN_ATTR_TO_SALT_ATTR_MAP['address'] = 'address'
DEBIAN_ATTR_TO_SALT_ATTR_MAP['hwaddress'] = 'hwaddress'
IPV4_VALID_PROTO = ['bootp', 'dhcp', 'static', 'manual', 'loopback', 'ppp']
IPV4_ATTR_MAP = {
'proto': __within(IPV4_VALID_PROTO, dtype=six.text_type),
# ipv4 static & manual
'address': __ipv4_quad,
'addresses': __anything,
'netmask': __ipv4_netmask,
'broadcast': __ipv4_quad,
'metric': __int,
'gateway': __ipv4_quad, # supports a colon-delimited list
'pointopoint': __ipv4_quad,
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'link', 'host'], dtype=six.text_type),
# dhcp
'hostname': __anything,
'leasehours': __int,
'leasetime': __int,
'vendor': __anything,
'client': __anything,
# bootp
'bootfile': __anything,
'server': __ipv4_quad,
'hwaddr': __mac,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'dstaddr': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# bond
'slaves': __anything,
# ppp
'provider': __anything,
'unit': __int,
'options': __anything,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
#
'network': __anything, # i don't know what this is
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
IPV6_VALID_PROTO = ['auto', 'loopback', 'static', 'manual',
'dhcp', 'v4tunnel', '6to4']
IPV6_ATTR_MAP = {
'proto': __within(IPV6_VALID_PROTO),
# ipv6 static & manual
'address': __ipv6,
'addresses': __anything,
'netmask': __ipv6_netmask,
'broadcast': __ipv6,
'gateway': __ipv6, # supports a colon-delimited list
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'site', 'link', 'host'], dtype=six.text_type),
# inet6 auto
'privext': __within([0, 1, 2], dtype=int),
'dhcp': __within([0, 1], dtype=int),
# inet6 static & manual & dhcp
'media': __anything,
'accept_ra': __within([0, 1], dtype=int),
'autoconf': __within([0, 1], dtype=int),
'preferred-lifetime': __int,
'dad-attempts': __int, # 0 to disable
'dad-interval': __float,
# bond
'slaves': __anything,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
WIRELESS_ATTR_MAP = {
'wireless-essid': __anything,
'wireless-mode': __anything, # TODO
'wpa-ap-scan': __within([0, 1, 2], dtype=int), # TODO
'wpa-conf': __anything,
'wpa-driver': __anything,
'wpa-group': __anything,
'wpa-key-mgmt': __anything,
'wpa-pairwise': __anything,
'wpa-psk': __anything,
'wpa-proto': __anything, # partial(__within,
'wpa-roam': __anything,
'wpa-ssid': __anything, # TODO
}
ATTRMAPS = {
'inet': [IPV4_ATTR_MAP, WIRELESS_ATTR_MAP],
'inet6': [IPV6_ATTR_MAP, WIRELESS_ATTR_MAP]
}
def _validate_interface_option(attr, value, addrfam='inet'):
'''lookup the validation function for a [addrfam][attr] and
return the results
:param attr: attribute name
:param value: raw setting value
:param addrfam: address family (inet, inet6,
'''
valid, _value, errmsg = False, value, 'Unknown validator'
attrmaps = ATTRMAPS.get(addrfam, [])
for attrmap in attrmaps:
if attr in attrmap:
validate_func = attrmap[attr]
(valid, _value, errmsg) = validate_func(value)
break
return (valid, _value, errmsg)
def _attrmaps_contain_attr(attr):
return (
attr in WIRELESS_ATTR_MAP or
attr in IPV4_ATTR_MAP or
attr in IPV6_ATTR_MAP)
def _parse_interfaces(interface_files=None):
'''
Parse /etc/network/interfaces and return current configured interfaces
'''
if interface_files is None:
interface_files = []
# Add this later.
if os.path.exists(_DEB_NETWORK_DIR):
interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]
if os.path.isfile(_DEB_NETWORK_FILE):
interface_files.insert(0, _DEB_NETWORK_FILE)
adapters = salt.utils.odict.OrderedDict()
method = -1
for interface_file in interface_files:
with salt.utils.files.fopen(interface_file) as interfaces:
# This ensures iface_dict exists, but does not ensure we're not reading a new interface.
iface_dict = {}
for line in interfaces:
line = salt.utils.stringutils.to_unicode(line)
# Identify the clauses by the first word of each line.
# Go to the next line if the current line is a comment
# or all spaces.
if line.lstrip().startswith('#') or line.isspace():
continue
# Parse the iface clause
if line.startswith('iface'):
sline = line.split()
if len(sline) != 4:
msg = 'Interface file malformed: {0}.'
msg = msg.format(sline)
log.error(msg)
raise AttributeError(msg)
iface_name = sline[1]
addrfam = sline[2]
method = sline[3]
# Create item in dict, if not already there
if iface_name not in adapters:
adapters[iface_name] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters[iface_name]:
adapters[iface_name]['data'] = salt.utils.odict.OrderedDict()
if addrfam not in adapters[iface_name]['data']:
adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict()
iface_dict = adapters[iface_name]['data'][addrfam]
iface_dict['addrfam'] = addrfam
iface_dict['proto'] = method
iface_dict['filename'] = interface_file
# Parse the detail clauses.
elif line[0].isspace():
sline = line.split()
# conf file attr: dns-nameservers
# salt states.network attr: dns
attr, valuestr = line.rstrip().split(None, 1)
if _attrmaps_contain_attr(attr):
if '-' in attr:
attrname = attr.replace('-', '_')
else:
attrname = attr
(valid, value, errmsg) = _validate_interface_option(
attr, valuestr, addrfam)
if attrname == 'address' and 'address' in iface_dict:
if 'addresses' not in iface_dict:
iface_dict['addresses'] = []
iface_dict['addresses'].append(value)
else:
iface_dict[attrname] = value
elif attr in _REV_ETHTOOL_CONFIG_OPTS:
if 'ethtool' not in iface_dict:
iface_dict['ethtool'] = salt.utils.odict.OrderedDict()
iface_dict['ethtool'][attr] = valuestr
elif attr.startswith('bond'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bonding' not in iface_dict:
iface_dict['bonding'] = salt.utils.odict.OrderedDict()
iface_dict['bonding'][opt] = valuestr
elif attr.startswith('bridge'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bridging' not in iface_dict:
iface_dict['bridging'] = salt.utils.odict.OrderedDict()
iface_dict['bridging'][opt] = valuestr
elif attr in ['up', 'pre-up', 'post-up',
'down', 'pre-down', 'post-down']:
cmd = valuestr
cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr))
if cmd_key not in iface_dict:
iface_dict[cmd_key] = []
iface_dict[cmd_key].append(cmd)
elif line.startswith('auto'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['enabled'] = True
elif line.startswith('allow-hotplug'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['hotplug'] = True
elif line.startswith('source'):
if 'source' not in adapters:
adapters['source'] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters['source']:
adapters['source']['data'] = salt.utils.odict.OrderedDict()
adapters['source']['data']['sources'] = []
adapters['source']['data']['sources'].append(line.split()[1])
# Return a sorted list of the keys for bond, bridge and ethtool options to
# ensure a consistent order
for iface_name in adapters:
if iface_name == 'source':
continue
if 'data' not in adapters[iface_name]:
msg = 'Interface file malformed for interface: {0}.'.format(iface_name)
log.error(msg)
adapters.pop(iface_name)
continue
for opt in ['ethtool', 'bonding', 'bridging']:
for inet in ['inet', 'inet6']:
if inet in adapters[iface_name]['data']:
if opt in adapters[iface_name]['data'][inet]:
opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys())
adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys
return adapters
def _parse_ethtool_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
if 'autoneg' in opts:
if opts['autoneg'] in _CONFIG_TRUE:
config.update({'autoneg': 'on'})
elif opts['autoneg'] in _CONFIG_FALSE:
config.update({'autoneg': 'off'})
else:
_raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE)
if 'duplex' in opts:
valid = ['full', 'half']
if opts['duplex'] in valid:
config.update({'duplex': opts['duplex']})
else:
_raise_error_iface(iface, 'duplex', valid)
if 'speed' in opts:
valid = ['10', '100', '1000', '10000']
if six.text_type(opts['speed']) in valid:
config.update({'speed': opts['speed']})
else:
_raise_error_iface(iface, opts['speed'], valid)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'on'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'off'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_ethtool_pppoe_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
for opt in _DEB_CONFIG_PPPOE_OPTS:
if opt in opts:
config[opt] = opts[opt]
if 'provider' in opts and not opts['provider']:
_raise_error_iface(iface, 'provider', _CONFIG_TRUE + _CONFIG_FALSE)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('noipdefault', 'usepeerdns', 'defaultroute', 'hide-password', 'noauth', 'persist', 'noaccomp'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'True'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'False'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_settings_bond(opts, iface):
'''
Filters given options and outputs valid settings for requested
operation. If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond_def = {
# 803.ad aggregation selection logic
# 0 for stable (default)
# 1 for bandwidth
# 2 for count
'ad_select': '0',
# Max number of transmit queues (default = 16)
'tx_queues': '16',
# Link monitoring in milliseconds. Most NICs support this
'miimon': '100',
# ARP interval in milliseconds
'arp_interval': '250',
# Delay before considering link down in milliseconds (miimon * 2)
'downdelay': '200',
# lacp_rate 0: Slow - every 30 seconds
# lacp_rate 1: Fast - every 1 second
'lacp_rate': '0',
# Max bonds for this driver
'max_bonds': '1',
# Specifies the time, in milliseconds, to wait before
# enabling a slave after a link recovery has been
# detected. Only used with miimon.
'updelay': '0',
# Used with miimon.
# On: driver sends mii
# Off: ethtool sends mii
'use_carrier': 'on',
# Default. Don't change unless you know what you are doing.
'xmit_hash_policy': 'layer2',
}
if opts['mode'] in ['balance-rr', '0']:
log.info('Device: %s Bonding Mode: load balancing (round-robin)', iface)
return _parse_settings_bond_0(opts, iface, bond_def)
elif opts['mode'] in ['active-backup', '1']:
log.info('Device: %s Bonding Mode: fault-tolerance (active-backup)', iface)
return _parse_settings_bond_1(opts, iface, bond_def)
elif opts['mode'] in ['balance-xor', '2']:
log.info('Device: %s Bonding Mode: load balancing (xor)', iface)
return _parse_settings_bond_2(opts, iface, bond_def)
elif opts['mode'] in ['broadcast', '3']:
log.info('Device: %s Bonding Mode: fault-tolerance (broadcast)', iface)
return _parse_settings_bond_3(opts, iface, bond_def)
elif opts['mode'] in ['802.3ad', '4']:
log.info('Device: %s Bonding Mode: IEEE 802.3ad Dynamic link '
'aggregation', iface)
return _parse_settings_bond_4(opts, iface, bond_def)
elif opts['mode'] in ['balance-tlb', '5']:
log.info('Device: %s Bonding Mode: transmit load balancing', iface)
return _parse_settings_bond_5(opts, iface, bond_def)
elif opts['mode'] in ['balance-alb', '6']:
log.info('Device: %s Bonding Mode: adaptive load balancing', iface)
return _parse_settings_bond_6(opts, iface, bond_def)
else:
valid = [
'0', '1', '2', '3', '4', '5', '6',
'balance-rr', 'active-backup', 'balance-xor',
'broadcast', '802.3ad', 'balance-tlb', 'balance-alb'
]
_raise_error_iface(iface, 'mode', valid)
def _parse_settings_bond_0(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond0.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '0'}
# ARP targets in n.n.n.n form
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
return bond
def _parse_settings_bond_1(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '1'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
if not (__grains__['os'] == "Ubuntu" and __grains__['osrelease_info'][0] >= 16):
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_2(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond2.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '2'}
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_3(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond3.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '3'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_4(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond4.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '4'}
for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']:
if binding in opts:
if binding == 'lacp_rate':
if opts[binding] == 'fast':
opts.update({binding: '1'})
if opts[binding] == 'slow':
opts.update({binding: '0'})
valid = ['fast', '1', 'slow', '0']
else:
valid = ['integer']
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, valid)
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_5(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond5.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '5'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_settings_bond_6(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond6.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '6'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_bridge_opts(opts, iface):
'''
Filters given options and outputs valid settings for BRIDGING_OPTS
If an option has a value that is not expected, this
function will log the Interface, Setting and what was expected.
'''
config = {}
if 'ports' in opts:
if isinstance(opts['ports'], list):
opts['ports'] = ' '.join(opts['ports'])
config.update({'ports': opts['ports']})
for opt in ['ageing', 'fd', 'gcint', 'hello', 'maxage']:
if opt in opts:
try:
float(opts[opt])
config.update({opt: opts[opt]})
except ValueError:
_raise_error_iface(iface, opt, ['float'])
for opt in ['bridgeprio', 'maxwait']:
if opt in opts:
if isinstance(opts[opt], int):
config.update({opt: opts[opt]})
else:
_raise_error_iface(iface, opt, ['integer'])
if 'hw' in opts:
# match 12 hex digits with either : or - as separators between pairs
if re.match('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$',
opts['hw'].lower()):
config.update({'hw': opts['hw']})
else:
_raise_error_iface(iface, 'hw', ['valid MAC address'])
for opt in ['pathcost', 'portprio']:
if opt in opts:
try:
port, cost_or_prio = opts[opt].split()
int(cost_or_prio)
config.update({opt: '{0} {1}'.format(port, cost_or_prio)})
except ValueError:
_raise_error_iface(iface, opt, ['interface integer'])
if 'stp' in opts:
if opts['stp'] in _CONFIG_TRUE:
config.update({'stp': 'on'})
elif opts['stp'] in _CONFIG_FALSE:
config.update({'stp': 'off'})
else:
_raise_error_iface(iface, 'stp', _CONFIG_TRUE + _CONFIG_FALSE)
if 'waitport' in opts:
if isinstance(opts['waitport'], int):
config.update({'waitport': opts['waitport']})
else:
values = opts['waitport'].split()
waitport_time = values.pop(0)
if waitport_time.isdigit() and values:
config.update({
'waitport': '{0} {1}'.format(
waitport_time, ' '.join(values)
)
})
else:
_raise_error_iface(iface, opt, ['integer [interfaces]'])
return config
def _parse_settings_eth(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['inet'] = salt.utils.odict.OrderedDict()
iface_data['inet6'] = salt.utils.odict.OrderedDict()
if enabled:
adapters[iface]['enabled'] = True
if opts.get('hotplug', False):
adapters[iface]['hotplug'] = True
if opts.get('enable_ipv6', None) and opts.get('iface_type', '') == 'vlan':
iface_data['inet6']['vlan_raw_device'] = (
re.sub(r'\.\d*', '', iface))
for addrfam in ['inet', 'inet6']:
if iface_type not in ['bridge']:
tmp_ethtool = _parse_ethtool_opts(opts, iface)
if tmp_ethtool:
ethtool = {}
for item in tmp_ethtool:
ethtool[_ETHTOOL_CONFIG_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['ethtool'] = ethtool
# return a list of sorted keys to ensure consistent order
iface_data[addrfam]['ethtool_keys'] = sorted(ethtool)
if iface_type == 'bridge':
bridging = _parse_bridge_opts(opts, iface)
if bridging:
iface_data[addrfam]['bridging'] = bridging
iface_data[addrfam]['bridging_keys'] = sorted(bridging)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'bond':
bonding = _parse_settings_bond(opts, iface)
if bonding:
iface_data[addrfam]['bonding'] = bonding
iface_data[addrfam]['bonding']['slaves'] = opts['slaves']
iface_data[addrfam]['bonding_keys'] = sorted(bonding)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'slave':
adapters[iface]['master'] = opts['master']
opts['proto'] = 'manual'
iface_data[addrfam]['master'] = adapters[iface]['master']
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'vlan':
iface_data[addrfam]['vlan_raw_device'] = re.sub(r'\.\d*', '', iface)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'pppoe':
tmp_ethtool = _parse_ethtool_pppoe_opts(opts, iface)
if tmp_ethtool:
for item in tmp_ethtool:
adapters[iface]['data'][addrfam][_DEB_CONFIG_PPPOE_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['addrfam'] = addrfam
opts.pop('mode', None)
for opt, val in opts.items():
inet = None
if opt.startswith('ipv4'):
opt = opt[4:]
inet = 'inet'
iface_data['inet']['addrfam'] = 'inet'
elif opt.startswith('ipv6'):
iface_data['inet6']['addrfam'] = 'inet6'
opt = opt[4:]
inet = 'inet6'
elif opt in ['ipaddr', 'address', 'ipaddresses', 'addresses', 'gateway', 'proto']:
iface_data['inet']['addrfam'] = 'inet'
inet = 'inet'
_opt = SALT_ATTR_TO_DEBIAN_ATTR_MAP.get(opt, opt)
_debopt = _opt.replace('-', '_')
for addrfam in ['inet', 'inet6']:
(valid, value, errmsg) = _validate_interface_option(_opt, val, addrfam=addrfam)
if not valid:
continue
if inet is None and _debopt not in iface_data[addrfam]:
iface_data[addrfam][_debopt] = value
elif inet == addrfam:
iface_data[addrfam][_debopt] = value
for opt in ['up_cmds', 'pre_up_cmds', 'post_up_cmds',
'down_cmds', 'pre_down_cmds', 'post_down_cmds']:
if opt in opts:
iface_data['inet'][opt] = opts[opt]
iface_data['inet6'][opt] = opts[opt]
# Remove incomplete/disabled inet blocks
for (addrfam, opt) in [('inet', 'enable_ipv4'), ('inet6', 'enable_ipv6')]:
if opts.get(opt, None) is False:
iface_data.pop(addrfam)
elif iface_data[addrfam].get('addrfam', '') != addrfam:
iface_data.pop(addrfam)
return adapters
def _parse_settings_source(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['sources'] = [opts['source']]
return adapters
def _parse_network_settings(opts, current):
'''
Filters given options and outputs valid settings for
the global network settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
current = dict((k.lower(), v) for (k, v) in six.iteritems(current))
result = {}
valid = _CONFIG_TRUE + _CONFIG_FALSE
if 'enabled' not in opts:
try:
opts['networking'] = current['networking']
_log_default_network('networking', current['networking'])
except ValueError:
_raise_error_network('networking', valid)
else:
opts['networking'] = opts['enabled']
if opts['networking'] in valid:
if opts['networking'] in _CONFIG_TRUE:
result['networking'] = 'yes'
elif opts['networking'] in _CONFIG_FALSE:
result['networking'] = 'no'
else:
_raise_error_network('networking', valid)
if 'hostname' not in opts:
try:
opts['hostname'] = current['hostname']
_log_default_network('hostname', current['hostname'])
except ValueError:
_raise_error_network('hostname', ['server1.example.com'])
if opts['hostname']:
result['hostname'] = opts['hostname']
else:
_raise_error_network('hostname', ['server1.example.com'])
if 'search' in opts:
result['search'] = opts['search']
return result
def _parse_routes(iface, opts):
'''
Filters given options and outputs valid settings for
the route settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
result = {}
if 'routes' not in opts:
_raise_error_routes(iface, 'routes', 'List of routes')
for opt in opts:
result[opt] = opts[opt]
return result
def _write_file(iface, data, folder, pattern):
'''
Writes a file to disk
'''
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
return filename
def _write_file_routes(iface, data, folder, pattern):
'''
Writes a file to disk
'''
# ifup / ifdown is executing given folder via run-parts.
# according to run-parts man-page, only filenames with this pattern are
# executed: (^[a-zA-Z0-9_-]+$)
# In order to make the routes file work for vlan interfaces
# (default would have been in example /etc/network/if-up.d/route-bond0.12)
# these dots in the iface name need to be replaced by underscores, so it
# can be executed by run-parts
iface = iface.replace('.', '_')
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
__salt__['file.set_mode'](filename, '0755')
return filename
def _write_file_network(data, filename, create=False):
'''
Writes a file to disk
If file does not exist, only create if create
argument is True
'''
if not os.path.exists(filename) and not create:
msg = '{0} cannot be written. {0} does not exist\
and create is set to False'
msg = msg.format(filename)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
def _read_temp(data):
'''
Return what would be written to disk
'''
tout = StringIO()
tout.write(data)
tout.seek(0)
output = tout.readlines()
tout.close()
return output
def _read_temp_ifaces(iface, data):
'''
Return what would be written to disk for interfaces
'''
try:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': data})
# Return as an array so the difflib works
return [item + '\n' for item in ifcfg.split('\n')]
def _write_file_ifaces(iface, data, **settings):
'''
Writes a file to disk
'''
try:
eth_template = JINJA.get_template('debian_eth.jinja')
source_template = JINJA.get_template('debian_source.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
# Read /etc/network/interfaces into a dict
adapters = _parse_interfaces()
# Apply supplied settings over on-disk settings
adapters[iface] = data
ifcfg = ''
for adapter in adapters:
if 'type' in adapters[adapter] and adapters[adapter]['type'] == 'source':
tmp = source_template.render({'name': adapter, 'data': adapters[adapter]})
else:
tmp = eth_template.render({'name': adapter, 'data': adapters[adapter]})
ifcfg = ifcfg + tmp
if adapter == iface:
saved_ifcfg = tmp
_SEPARATE_FILE = False
if 'filename' in settings:
if not settings['filename'].startswith('/'):
filename = '{0}/{1}'.format(_DEB_NETWORK_DIR, settings['filename'])
else:
filename = settings['filename']
_SEPARATE_FILE = True
else:
if 'filename' in adapters[adapter]['data']:
filename = adapters[adapter]['data']
else:
filename = _DEB_NETWORK_FILE
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
if _SEPARATE_FILE:
fout.write(salt.utils.stringutils.to_str(saved_ifcfg))
else:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return saved_ifcfg.split('\n')
def _write_file_ppp_ifaces(iface, data):
'''
Writes a file to disk
'''
try:
template = JINJA.get_template('debian_ppp_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_ppp_eth.jinja')
return ''
adapters = _parse_interfaces()
adapters[iface] = data
ifcfg = ''
tmp = template.render({'data': adapters[iface]})
ifcfg = tmp + ifcfg
filename = _DEB_PPP_DIR + '/' + adapters[iface]['data']['inet']['provider']
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.fopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return filename
def build_bond(iface, **settings):
'''
Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb
'''
deb_major = __grains__['osrelease'][:1]
opts = _parse_settings_bond(settings, iface)
try:
template = JINJA.get_template('conf.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template conf.jinja')
return ''
data = template.render({'name': iface, 'bonding': opts})
if 'test' in settings and settings['test']:
return _read_temp(data)
_write_file(iface, data, _DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
if deb_major == '5':
for line_type in ('alias', 'options'):
cmd = ['sed', '-i', '-e', r'/^{0}\s{1}.*/d'.format(line_type, iface),
'/etc/modprobe.conf']
__salt__['cmd.run'](cmd, python_shell=False)
__salt__['file.append']('/etc/modprobe.conf', path)
# Load kernel module
__salt__['kmod.load']('bonding')
# install ifenslave-2.6
__salt__['pkg.install']('ifenslave-2.6')
return _read_file(path)
def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'vlan':
settings['vlan'] = 'yes'
__salt__['pkg.install']('vlan')
elif iface_type == 'pppoe':
settings['pppoe'] = 'yes'
if not __salt__['pkg.version']('ppp'):
inst = __salt__['pkg.install']('ppp')
elif iface_type == 'bond':
if 'slaves' not in settings:
msg = 'slaves is a required setting for bond interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'bridge':
if 'ports' not in settings:
msg = (
'ports is a required setting for bridge interfaces on Debian '
'or Ubuntu based systems'
)
log.error(msg)
raise AttributeError(msg)
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'pppoe']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
if iface_type in ['source']:
opts = _parse_settings_source(settings, iface_type, enabled, iface)
if 'test' in settings and settings['test']:
return _read_temp_ifaces(iface, opts[iface])
ifcfg = _write_file_ifaces(iface, opts[iface], **settings)
if iface_type == 'pppoe':
_write_file_ppp_ifaces(iface, opts[iface])
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg]
def build_routes(iface, **settings):
'''
Add route scripts for a network interface using up commands.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
'''
opts = _parse_routes(iface, settings)
try:
template = JINJA.get_template('route_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template route_eth.jinja')
return ''
add_routecfg = template.render(route_type='add',
routes=opts['routes'],
iface=iface)
del_routecfg = template.render(route_type='del',
routes=opts['routes'],
iface=iface)
if 'test' in settings and settings['test']:
return _read_temp(add_routecfg + del_routecfg)
filename = _write_file_routes(iface,
add_routecfg,
_DEB_NETWORK_UP_DIR,
'route-{0}')
results = _read_file(filename)
filename = _write_file_routes(iface,
del_routecfg,
_DEB_NETWORK_DOWN_DIR,
'route-{0}')
results += _read_file(filename)
return results
def down(iface, iface_type):
'''
Shutdown a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.down eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought down.
if iface_type not in ['slave', 'source']:
return __salt__['cmd.run'](['ifdown', iface])
return None
def get_bond(iface):
'''
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
'''
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
return _read_file(path)
def get_interface(iface):
'''
Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
adapters = _parse_interfaces()
if iface in adapters:
try:
if iface == 'source':
template = JINJA.get_template('debian_source.jinja')
else:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': adapters[iface]})
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg.split('\n')]
else:
return []
def up(iface, iface_type): # pylint: disable=C0103
'''
Start up a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.up eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought up.
if iface_type not in ('slave', 'source'):
return __salt__['cmd.run'](['ifup', iface])
return None
def get_network_settings():
'''
Return the contents of the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_network_settings
'''
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
settings = {}
if __salt__['service.available']('networking'):
if __salt__['service.status']('networking'):
settings['networking'] = "yes"
else:
settings['networking'] = "no"
else:
settings['networking'] = "no"
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
settings['hostname'] = hostname
settings['domainname'] = domainname
settings['searchdomain'] = searchdomain
else:
settings = _parse_current_network_settings()
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(settings)
return _read_temp(network)
def apply_network_settings(**settings):
'''
Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings
'''
if 'require_reboot' not in settings:
settings['require_reboot'] = False
if 'apply_hostname' not in settings:
settings['apply_hostname'] = False
hostname_res = True
if settings['apply_hostname'] in _CONFIG_TRUE:
if 'hostname' in settings:
hostname_res = __salt__['network.mod_hostname'](settings['hostname'])
else:
log.warning(
'The network state sls is trying to apply hostname '
'changes but no hostname is defined.'
)
hostname_res = False
res = True
if settings['require_reboot'] in _CONFIG_TRUE:
log.warning(
'The network state sls is requiring a reboot of the system to '
'properly apply network configuration.'
)
res = True
else:
stop = __salt__['service.stop']('networking')
time.sleep(2)
res = stop and __salt__['service.start']('networking')
return hostname_res and res
def build_network_settings(**settings):
'''
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
'''
changes = []
# Read current configuration and store default values
current_network_settings = _parse_current_network_settings()
# Build settings
opts = _parse_network_settings(settings, current_network_settings)
# Ubuntu has moved away from /etc/default/networking
# beginning with the 12.04 release so we disable or enable
# the networking related services on boot
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
if opts['networking'] == 'yes':
service_cmd = 'service.enable'
else:
service_cmd = 'service.disable'
if __salt__['service.available']('NetworkManager'):
__salt__[service_cmd]('NetworkManager')
if __salt__['service.available']('networking'):
__salt__[service_cmd]('networking')
else:
try:
template = JINJA.get_template('network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template network.jinja')
return ''
network = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(network)
# Write settings
_write_file_network(network, _DEB_NETWORKING_FILE, True)
# Get hostname and domain from opts
sline = opts['hostname'].split('.', 1)
opts['hostname'] = sline[0]
current_domainname = current_network_settings['domainname']
current_searchdomain = current_network_settings['searchdomain']
new_domain = False
if len(sline) > 1:
new_domainname = sline[1]
if new_domainname != current_domainname:
domainname = new_domainname
opts['domainname'] = new_domainname
new_domain = True
else:
domainname = current_domainname
opts['domainname'] = domainname
else:
domainname = current_domainname
opts['domainname'] = domainname
new_search = False
if 'search' in opts:
new_searchdomain = opts['search']
if new_searchdomain != current_searchdomain:
searchdomain = new_searchdomain
opts['searchdomain'] = new_searchdomain
new_search = True
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
# If the domain changes, then we should write the resolv.conf file.
if new_domain or new_search:
# Look for existing domain line and update if necessary
resolve = _parse_resolve()
domain_prog = re.compile(r'domain\s+')
search_prog = re.compile(r'search\s+')
new_contents = []
for item in _read_file(_DEB_RESOLV_FILE):
if domain_prog.match(item):
item = 'domain {0}'.format(domainname)
elif search_prog.match(item):
item = 'search {0}'.format(searchdomain)
new_contents.append(item)
# A domain line didn't exist so we'll add one in
# with the new domainname
if 'domain' not in resolve:
new_contents.insert(0, 'domain {0}' . format(domainname))
# A search line didn't exist so we'll add one in
# with the new search domain
if 'search' not in resolve:
new_contents.insert('domain' in resolve, 'search {0}'.format(searchdomain))
new_resolv = '\n'.join(new_contents)
# Write /etc/resolv.conf
if not ('test' in settings and settings['test']):
_write_file_network(new_resolv, _DEB_RESOLV_FILE)
# used for returning the results back
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(opts)
changes.extend(_read_temp(network))
return changes
|
saltstack/salt
|
salt/modules/debian_ip.py
|
apply_network_settings
|
python
|
def apply_network_settings(**settings):
'''
Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings
'''
if 'require_reboot' not in settings:
settings['require_reboot'] = False
if 'apply_hostname' not in settings:
settings['apply_hostname'] = False
hostname_res = True
if settings['apply_hostname'] in _CONFIG_TRUE:
if 'hostname' in settings:
hostname_res = __salt__['network.mod_hostname'](settings['hostname'])
else:
log.warning(
'The network state sls is trying to apply hostname '
'changes but no hostname is defined.'
)
hostname_res = False
res = True
if settings['require_reboot'] in _CONFIG_TRUE:
log.warning(
'The network state sls is requiring a reboot of the system to '
'properly apply network configuration.'
)
res = True
else:
stop = __salt__['service.stop']('networking')
time.sleep(2)
res = stop and __salt__['service.start']('networking')
return hostname_res and res
|
Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_ip.py#L1860-L1899
| null |
# -*- coding: utf-8 -*-
'''
The networking module for Debian-based distros
References:
* http://www.debian.org/doc/manuals/debian-reference/ch05.en.html
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import functools
import logging
import os.path
import os
import re
import time
# Import third party libs
import jinja2
import jinja2.exceptions
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error,no-name-in-module
# Import salt libs
import salt.utils.dns
import salt.utils.files
import salt.utils.odict
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.validate.net
# Set up logging
log = logging.getLogger(__name__)
# Set up template environment
JINJA = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'debian_ip')
)
)
# Define the module's virtual name
__virtualname__ = 'ip'
def __virtual__():
'''
Confine this module to Debian-based distros
'''
if __grains__['os_family'] == 'Debian':
return __virtualname__
return (False, 'The debian_ip module could not be loaded: '
'unsupported OS family')
_ETHTOOL_CONFIG_OPTS = {
'speed': 'link-speed',
'duplex': 'link-duplex',
'autoneg': 'ethernet-autoneg',
'ethernet-port': 'ethernet-port',
'wol': 'ethernet-wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'rx': 'offload-rx',
'tx': 'offload-tx',
'sg': 'offload-sg',
'tso': 'offload-tso',
'ufo': 'offload-ufo',
'gso': 'offload-gso',
'gro': 'offload-gro',
'lro': 'offload-lro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_REV_ETHTOOL_CONFIG_OPTS = {
'link-speed': 'speed',
'link-duplex': 'duplex',
'ethernet-autoneg': 'autoneg',
'ethernet-port': 'ethernet-port',
'ethernet-wol': 'wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'offload-rx': 'rx',
'offload-tx': 'tx',
'offload-sg': 'sg',
'offload-tso': 'tso',
'offload-ufo': 'ufo',
'offload-gso': 'gso',
'offload-lro': 'lro',
'offload-gro': 'gro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_DEB_CONFIG_PPPOE_OPTS = {
'user': 'user',
'password': 'password',
'provider': 'provider',
'pppoe_iface': 'pppoe_iface',
'noipdefault': 'noipdefault',
'usepeerdns': 'usepeerdns',
'defaultroute': 'defaultroute',
'holdoff': 'holdoff',
'maxfail': 'maxfail',
'hide-password': 'hide-password',
'lcp-echo-interval': 'lcp-echo-interval',
'lcp-echo-failure': 'lcp-echo-failure',
'connect': 'connect',
'noauth': 'noauth',
'persist': 'persist',
'mtu': 'mtu',
'noaccomp': 'noaccomp',
'linkname': 'linkname',
}
_DEB_ROUTES_FILE = '/etc/network/routes'
_DEB_NETWORK_FILE = '/etc/network/interfaces'
_DEB_NETWORK_DIR = '/etc/network/interfaces.d/'
_DEB_NETWORK_UP_DIR = '/etc/network/if-up.d/'
_DEB_NETWORK_DOWN_DIR = '/etc/network/if-down.d/'
_DEB_NETWORK_CONF_FILES = '/etc/modprobe.d/'
_DEB_NETWORKING_FILE = '/etc/default/networking'
_DEB_HOSTNAME_FILE = '/etc/hostname'
_DEB_RESOLV_FILE = '/etc/resolv.conf'
_DEB_PPP_DIR = '/etc/ppp/peers/'
_CONFIG_TRUE = ['yes', 'on', 'true', '1', True]
_CONFIG_FALSE = ['no', 'off', 'false', '0', False]
_IFACE_TYPES = [
'eth', 'bond', 'alias', 'clone',
'ipsec', 'dialup', 'bridge', 'slave',
'vlan', 'pppoe', 'source',
]
def _error_msg_iface(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, '|'.join(str(e) for e in expected))
def _error_msg_routes(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, expected)
def _log_default_iface(iface, opt, value):
log.info(
'Using default option -- Interface: %s Option: %s Value: %s',
iface, opt, value
)
def _error_msg_network(option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]'
return msg.format(option, '|'.join(str(e) for e in expected))
def _log_default_network(opt, value):
log.info('Using existing setting -- Setting: %s Value: %s', opt, value)
def _raise_error_iface(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_iface(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_network(option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_network(option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_routes(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_routes(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _read_file(path):
'''
Reads and returns the contents of a text file
'''
try:
with salt.utils.files.flopen(path, 'rb') as contents:
return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]
except (OSError, IOError):
return ''
def _parse_resolve():
'''
Parse /etc/resolv.conf
'''
return salt.utils.dns.parse_resolv(_DEB_RESOLV_FILE)
def _parse_domainname():
'''
Parse /etc/resolv.conf and return domainname
'''
return _parse_resolve().get('domain', '')
def _parse_searchdomain():
'''
Parse /etc/resolv.conf and return searchdomain
'''
return _parse_resolve().get('search', '')
def _parse_hostname():
'''
Parse /etc/hostname and return hostname
'''
contents = _read_file(_DEB_HOSTNAME_FILE)
if contents:
return contents[0].split('\n')[0]
else:
return ''
def _parse_current_network_settings():
'''
Parse /etc/default/networking and return current configuration
'''
opts = salt.utils.odict.OrderedDict()
opts['networking'] = ''
if os.path.isfile(_DEB_NETWORKING_FILE):
with salt.utils.files.fopen(_DEB_NETWORKING_FILE) as contents:
for line in contents:
salt.utils.stringutils.to_unicode(line)
if line.startswith('#'):
continue
elif line.startswith('CONFIGURE_INTERFACES'):
opts['networking'] = line.split('=', 1)[1].strip()
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
opts['hostname'] = hostname
opts['domainname'] = domainname
opts['searchdomain'] = searchdomain
return opts
# def __validator_func(value):
# return (valid: True/False, (transformed) value, error message)
def __ipv4_quad(value):
'''validate an IPv4 address'''
return (salt.utils.validate.net.ipv4_addr(value), value,
'dotted IPv4 address')
def __ipv6(value):
'''validate an IPv6 address'''
return (salt.utils.validate.net.ipv6_addr(value), value,
'IPv6 address')
def __mac(value):
'''validate a mac address'''
return (salt.utils.validate.net.mac(value), value,
'MAC address')
def __anything(value):
return (True, value, None)
def __int(value):
'''validate an integer'''
valid, _value = False, value
try:
_value = int(value)
valid = True
except ValueError:
pass
return (valid, _value, 'integer')
def __float(value):
'''validate a float'''
valid, _value = False, value
try:
_value = float(value)
valid = True
except ValueError:
pass
return (valid, _value, 'float')
def __ipv4_netmask(value):
'''validate an IPv4 dotted quad or integer CIDR netmask'''
valid, errmsg = False, 'dotted quad or integer CIDR (0->32)'
valid, value, _ = __int(value)
if not (valid and 0 <= value <= 32):
valid = salt.utils.validate.net.netmask(value)
return (valid, value, errmsg)
def __ipv6_netmask(value):
'''validate an IPv6 integer netmask'''
valid, errmsg = False, 'IPv6 netmask (0->128)'
valid, value, _ = __int(value)
valid = (valid and 0 <= value <= 128)
return (valid, value, errmsg)
def __within2(value, within=None, errmsg=None, dtype=None):
'''validate that a value is in ``within`` and optionally a ``dtype``'''
valid, _value = False, value
if dtype:
try:
_value = dtype(value) # TODO: this is a bit loose when dtype is a class
valid = _value in within
except ValueError:
pass
else:
valid = _value in within
if errmsg is None:
if dtype:
typename = getattr(dtype, '__name__',
hasattr(dtype, '__class__')
and getattr(dtype.__class__, 'name', dtype))
errmsg = '{0} within \'{1}\''.format(typename, within)
else:
errmsg = 'within \'{0}\''.format(within)
return (valid, _value, errmsg)
def __within(within=None, errmsg=None, dtype=None):
return functools.partial(__within2, within=within,
errmsg=errmsg, dtype=dtype)
def __space_delimited_list(value):
'''validate that a value contains one or more space-delimited values'''
if isinstance(value, six.string_types):
value = value.strip().split()
if hasattr(value, '__iter__') and value != []:
return (True, value, 'space-delimited string')
else:
return (False, value, '{0} is not a valid space-delimited value.\n'.format(value))
SALT_ATTR_TO_DEBIAN_ATTR_MAP = {
'dns': 'dns-nameservers',
'search': 'dns-search',
'hwaddr': 'hwaddress', # TODO: this limits bootp functionality
'ipaddr': 'address',
'ipaddrs': 'addresses',
}
DEBIAN_ATTR_TO_SALT_ATTR_MAP = dict(
(v, k) for (k, v) in six.iteritems(SALT_ATTR_TO_DEBIAN_ATTR_MAP))
# TODO
DEBIAN_ATTR_TO_SALT_ATTR_MAP['address'] = 'address'
DEBIAN_ATTR_TO_SALT_ATTR_MAP['hwaddress'] = 'hwaddress'
IPV4_VALID_PROTO = ['bootp', 'dhcp', 'static', 'manual', 'loopback', 'ppp']
IPV4_ATTR_MAP = {
'proto': __within(IPV4_VALID_PROTO, dtype=six.text_type),
# ipv4 static & manual
'address': __ipv4_quad,
'addresses': __anything,
'netmask': __ipv4_netmask,
'broadcast': __ipv4_quad,
'metric': __int,
'gateway': __ipv4_quad, # supports a colon-delimited list
'pointopoint': __ipv4_quad,
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'link', 'host'], dtype=six.text_type),
# dhcp
'hostname': __anything,
'leasehours': __int,
'leasetime': __int,
'vendor': __anything,
'client': __anything,
# bootp
'bootfile': __anything,
'server': __ipv4_quad,
'hwaddr': __mac,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'dstaddr': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# bond
'slaves': __anything,
# ppp
'provider': __anything,
'unit': __int,
'options': __anything,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
#
'network': __anything, # i don't know what this is
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
IPV6_VALID_PROTO = ['auto', 'loopback', 'static', 'manual',
'dhcp', 'v4tunnel', '6to4']
IPV6_ATTR_MAP = {
'proto': __within(IPV6_VALID_PROTO),
# ipv6 static & manual
'address': __ipv6,
'addresses': __anything,
'netmask': __ipv6_netmask,
'broadcast': __ipv6,
'gateway': __ipv6, # supports a colon-delimited list
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'site', 'link', 'host'], dtype=six.text_type),
# inet6 auto
'privext': __within([0, 1, 2], dtype=int),
'dhcp': __within([0, 1], dtype=int),
# inet6 static & manual & dhcp
'media': __anything,
'accept_ra': __within([0, 1], dtype=int),
'autoconf': __within([0, 1], dtype=int),
'preferred-lifetime': __int,
'dad-attempts': __int, # 0 to disable
'dad-interval': __float,
# bond
'slaves': __anything,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
WIRELESS_ATTR_MAP = {
'wireless-essid': __anything,
'wireless-mode': __anything, # TODO
'wpa-ap-scan': __within([0, 1, 2], dtype=int), # TODO
'wpa-conf': __anything,
'wpa-driver': __anything,
'wpa-group': __anything,
'wpa-key-mgmt': __anything,
'wpa-pairwise': __anything,
'wpa-psk': __anything,
'wpa-proto': __anything, # partial(__within,
'wpa-roam': __anything,
'wpa-ssid': __anything, # TODO
}
ATTRMAPS = {
'inet': [IPV4_ATTR_MAP, WIRELESS_ATTR_MAP],
'inet6': [IPV6_ATTR_MAP, WIRELESS_ATTR_MAP]
}
def _validate_interface_option(attr, value, addrfam='inet'):
'''lookup the validation function for a [addrfam][attr] and
return the results
:param attr: attribute name
:param value: raw setting value
:param addrfam: address family (inet, inet6,
'''
valid, _value, errmsg = False, value, 'Unknown validator'
attrmaps = ATTRMAPS.get(addrfam, [])
for attrmap in attrmaps:
if attr in attrmap:
validate_func = attrmap[attr]
(valid, _value, errmsg) = validate_func(value)
break
return (valid, _value, errmsg)
def _attrmaps_contain_attr(attr):
return (
attr in WIRELESS_ATTR_MAP or
attr in IPV4_ATTR_MAP or
attr in IPV6_ATTR_MAP)
def _parse_interfaces(interface_files=None):
'''
Parse /etc/network/interfaces and return current configured interfaces
'''
if interface_files is None:
interface_files = []
# Add this later.
if os.path.exists(_DEB_NETWORK_DIR):
interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]
if os.path.isfile(_DEB_NETWORK_FILE):
interface_files.insert(0, _DEB_NETWORK_FILE)
adapters = salt.utils.odict.OrderedDict()
method = -1
for interface_file in interface_files:
with salt.utils.files.fopen(interface_file) as interfaces:
# This ensures iface_dict exists, but does not ensure we're not reading a new interface.
iface_dict = {}
for line in interfaces:
line = salt.utils.stringutils.to_unicode(line)
# Identify the clauses by the first word of each line.
# Go to the next line if the current line is a comment
# or all spaces.
if line.lstrip().startswith('#') or line.isspace():
continue
# Parse the iface clause
if line.startswith('iface'):
sline = line.split()
if len(sline) != 4:
msg = 'Interface file malformed: {0}.'
msg = msg.format(sline)
log.error(msg)
raise AttributeError(msg)
iface_name = sline[1]
addrfam = sline[2]
method = sline[3]
# Create item in dict, if not already there
if iface_name not in adapters:
adapters[iface_name] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters[iface_name]:
adapters[iface_name]['data'] = salt.utils.odict.OrderedDict()
if addrfam not in adapters[iface_name]['data']:
adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict()
iface_dict = adapters[iface_name]['data'][addrfam]
iface_dict['addrfam'] = addrfam
iface_dict['proto'] = method
iface_dict['filename'] = interface_file
# Parse the detail clauses.
elif line[0].isspace():
sline = line.split()
# conf file attr: dns-nameservers
# salt states.network attr: dns
attr, valuestr = line.rstrip().split(None, 1)
if _attrmaps_contain_attr(attr):
if '-' in attr:
attrname = attr.replace('-', '_')
else:
attrname = attr
(valid, value, errmsg) = _validate_interface_option(
attr, valuestr, addrfam)
if attrname == 'address' and 'address' in iface_dict:
if 'addresses' not in iface_dict:
iface_dict['addresses'] = []
iface_dict['addresses'].append(value)
else:
iface_dict[attrname] = value
elif attr in _REV_ETHTOOL_CONFIG_OPTS:
if 'ethtool' not in iface_dict:
iface_dict['ethtool'] = salt.utils.odict.OrderedDict()
iface_dict['ethtool'][attr] = valuestr
elif attr.startswith('bond'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bonding' not in iface_dict:
iface_dict['bonding'] = salt.utils.odict.OrderedDict()
iface_dict['bonding'][opt] = valuestr
elif attr.startswith('bridge'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bridging' not in iface_dict:
iface_dict['bridging'] = salt.utils.odict.OrderedDict()
iface_dict['bridging'][opt] = valuestr
elif attr in ['up', 'pre-up', 'post-up',
'down', 'pre-down', 'post-down']:
cmd = valuestr
cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr))
if cmd_key not in iface_dict:
iface_dict[cmd_key] = []
iface_dict[cmd_key].append(cmd)
elif line.startswith('auto'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['enabled'] = True
elif line.startswith('allow-hotplug'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['hotplug'] = True
elif line.startswith('source'):
if 'source' not in adapters:
adapters['source'] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters['source']:
adapters['source']['data'] = salt.utils.odict.OrderedDict()
adapters['source']['data']['sources'] = []
adapters['source']['data']['sources'].append(line.split()[1])
# Return a sorted list of the keys for bond, bridge and ethtool options to
# ensure a consistent order
for iface_name in adapters:
if iface_name == 'source':
continue
if 'data' not in adapters[iface_name]:
msg = 'Interface file malformed for interface: {0}.'.format(iface_name)
log.error(msg)
adapters.pop(iface_name)
continue
for opt in ['ethtool', 'bonding', 'bridging']:
for inet in ['inet', 'inet6']:
if inet in adapters[iface_name]['data']:
if opt in adapters[iface_name]['data'][inet]:
opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys())
adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys
return adapters
def _parse_ethtool_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
if 'autoneg' in opts:
if opts['autoneg'] in _CONFIG_TRUE:
config.update({'autoneg': 'on'})
elif opts['autoneg'] in _CONFIG_FALSE:
config.update({'autoneg': 'off'})
else:
_raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE)
if 'duplex' in opts:
valid = ['full', 'half']
if opts['duplex'] in valid:
config.update({'duplex': opts['duplex']})
else:
_raise_error_iface(iface, 'duplex', valid)
if 'speed' in opts:
valid = ['10', '100', '1000', '10000']
if six.text_type(opts['speed']) in valid:
config.update({'speed': opts['speed']})
else:
_raise_error_iface(iface, opts['speed'], valid)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'on'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'off'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_ethtool_pppoe_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
for opt in _DEB_CONFIG_PPPOE_OPTS:
if opt in opts:
config[opt] = opts[opt]
if 'provider' in opts and not opts['provider']:
_raise_error_iface(iface, 'provider', _CONFIG_TRUE + _CONFIG_FALSE)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('noipdefault', 'usepeerdns', 'defaultroute', 'hide-password', 'noauth', 'persist', 'noaccomp'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'True'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'False'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_settings_bond(opts, iface):
'''
Filters given options and outputs valid settings for requested
operation. If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond_def = {
# 803.ad aggregation selection logic
# 0 for stable (default)
# 1 for bandwidth
# 2 for count
'ad_select': '0',
# Max number of transmit queues (default = 16)
'tx_queues': '16',
# Link monitoring in milliseconds. Most NICs support this
'miimon': '100',
# ARP interval in milliseconds
'arp_interval': '250',
# Delay before considering link down in milliseconds (miimon * 2)
'downdelay': '200',
# lacp_rate 0: Slow - every 30 seconds
# lacp_rate 1: Fast - every 1 second
'lacp_rate': '0',
# Max bonds for this driver
'max_bonds': '1',
# Specifies the time, in milliseconds, to wait before
# enabling a slave after a link recovery has been
# detected. Only used with miimon.
'updelay': '0',
# Used with miimon.
# On: driver sends mii
# Off: ethtool sends mii
'use_carrier': 'on',
# Default. Don't change unless you know what you are doing.
'xmit_hash_policy': 'layer2',
}
if opts['mode'] in ['balance-rr', '0']:
log.info('Device: %s Bonding Mode: load balancing (round-robin)', iface)
return _parse_settings_bond_0(opts, iface, bond_def)
elif opts['mode'] in ['active-backup', '1']:
log.info('Device: %s Bonding Mode: fault-tolerance (active-backup)', iface)
return _parse_settings_bond_1(opts, iface, bond_def)
elif opts['mode'] in ['balance-xor', '2']:
log.info('Device: %s Bonding Mode: load balancing (xor)', iface)
return _parse_settings_bond_2(opts, iface, bond_def)
elif opts['mode'] in ['broadcast', '3']:
log.info('Device: %s Bonding Mode: fault-tolerance (broadcast)', iface)
return _parse_settings_bond_3(opts, iface, bond_def)
elif opts['mode'] in ['802.3ad', '4']:
log.info('Device: %s Bonding Mode: IEEE 802.3ad Dynamic link '
'aggregation', iface)
return _parse_settings_bond_4(opts, iface, bond_def)
elif opts['mode'] in ['balance-tlb', '5']:
log.info('Device: %s Bonding Mode: transmit load balancing', iface)
return _parse_settings_bond_5(opts, iface, bond_def)
elif opts['mode'] in ['balance-alb', '6']:
log.info('Device: %s Bonding Mode: adaptive load balancing', iface)
return _parse_settings_bond_6(opts, iface, bond_def)
else:
valid = [
'0', '1', '2', '3', '4', '5', '6',
'balance-rr', 'active-backup', 'balance-xor',
'broadcast', '802.3ad', 'balance-tlb', 'balance-alb'
]
_raise_error_iface(iface, 'mode', valid)
def _parse_settings_bond_0(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond0.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '0'}
# ARP targets in n.n.n.n form
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
return bond
def _parse_settings_bond_1(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '1'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
if not (__grains__['os'] == "Ubuntu" and __grains__['osrelease_info'][0] >= 16):
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_2(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond2.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '2'}
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_3(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond3.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '3'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_4(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond4.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '4'}
for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']:
if binding in opts:
if binding == 'lacp_rate':
if opts[binding] == 'fast':
opts.update({binding: '1'})
if opts[binding] == 'slow':
opts.update({binding: '0'})
valid = ['fast', '1', 'slow', '0']
else:
valid = ['integer']
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, valid)
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_5(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond5.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '5'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_settings_bond_6(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond6.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '6'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_bridge_opts(opts, iface):
'''
Filters given options and outputs valid settings for BRIDGING_OPTS
If an option has a value that is not expected, this
function will log the Interface, Setting and what was expected.
'''
config = {}
if 'ports' in opts:
if isinstance(opts['ports'], list):
opts['ports'] = ' '.join(opts['ports'])
config.update({'ports': opts['ports']})
for opt in ['ageing', 'fd', 'gcint', 'hello', 'maxage']:
if opt in opts:
try:
float(opts[opt])
config.update({opt: opts[opt]})
except ValueError:
_raise_error_iface(iface, opt, ['float'])
for opt in ['bridgeprio', 'maxwait']:
if opt in opts:
if isinstance(opts[opt], int):
config.update({opt: opts[opt]})
else:
_raise_error_iface(iface, opt, ['integer'])
if 'hw' in opts:
# match 12 hex digits with either : or - as separators between pairs
if re.match('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$',
opts['hw'].lower()):
config.update({'hw': opts['hw']})
else:
_raise_error_iface(iface, 'hw', ['valid MAC address'])
for opt in ['pathcost', 'portprio']:
if opt in opts:
try:
port, cost_or_prio = opts[opt].split()
int(cost_or_prio)
config.update({opt: '{0} {1}'.format(port, cost_or_prio)})
except ValueError:
_raise_error_iface(iface, opt, ['interface integer'])
if 'stp' in opts:
if opts['stp'] in _CONFIG_TRUE:
config.update({'stp': 'on'})
elif opts['stp'] in _CONFIG_FALSE:
config.update({'stp': 'off'})
else:
_raise_error_iface(iface, 'stp', _CONFIG_TRUE + _CONFIG_FALSE)
if 'waitport' in opts:
if isinstance(opts['waitport'], int):
config.update({'waitport': opts['waitport']})
else:
values = opts['waitport'].split()
waitport_time = values.pop(0)
if waitport_time.isdigit() and values:
config.update({
'waitport': '{0} {1}'.format(
waitport_time, ' '.join(values)
)
})
else:
_raise_error_iface(iface, opt, ['integer [interfaces]'])
return config
def _parse_settings_eth(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['inet'] = salt.utils.odict.OrderedDict()
iface_data['inet6'] = salt.utils.odict.OrderedDict()
if enabled:
adapters[iface]['enabled'] = True
if opts.get('hotplug', False):
adapters[iface]['hotplug'] = True
if opts.get('enable_ipv6', None) and opts.get('iface_type', '') == 'vlan':
iface_data['inet6']['vlan_raw_device'] = (
re.sub(r'\.\d*', '', iface))
for addrfam in ['inet', 'inet6']:
if iface_type not in ['bridge']:
tmp_ethtool = _parse_ethtool_opts(opts, iface)
if tmp_ethtool:
ethtool = {}
for item in tmp_ethtool:
ethtool[_ETHTOOL_CONFIG_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['ethtool'] = ethtool
# return a list of sorted keys to ensure consistent order
iface_data[addrfam]['ethtool_keys'] = sorted(ethtool)
if iface_type == 'bridge':
bridging = _parse_bridge_opts(opts, iface)
if bridging:
iface_data[addrfam]['bridging'] = bridging
iface_data[addrfam]['bridging_keys'] = sorted(bridging)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'bond':
bonding = _parse_settings_bond(opts, iface)
if bonding:
iface_data[addrfam]['bonding'] = bonding
iface_data[addrfam]['bonding']['slaves'] = opts['slaves']
iface_data[addrfam]['bonding_keys'] = sorted(bonding)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'slave':
adapters[iface]['master'] = opts['master']
opts['proto'] = 'manual'
iface_data[addrfam]['master'] = adapters[iface]['master']
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'vlan':
iface_data[addrfam]['vlan_raw_device'] = re.sub(r'\.\d*', '', iface)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'pppoe':
tmp_ethtool = _parse_ethtool_pppoe_opts(opts, iface)
if tmp_ethtool:
for item in tmp_ethtool:
adapters[iface]['data'][addrfam][_DEB_CONFIG_PPPOE_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['addrfam'] = addrfam
opts.pop('mode', None)
for opt, val in opts.items():
inet = None
if opt.startswith('ipv4'):
opt = opt[4:]
inet = 'inet'
iface_data['inet']['addrfam'] = 'inet'
elif opt.startswith('ipv6'):
iface_data['inet6']['addrfam'] = 'inet6'
opt = opt[4:]
inet = 'inet6'
elif opt in ['ipaddr', 'address', 'ipaddresses', 'addresses', 'gateway', 'proto']:
iface_data['inet']['addrfam'] = 'inet'
inet = 'inet'
_opt = SALT_ATTR_TO_DEBIAN_ATTR_MAP.get(opt, opt)
_debopt = _opt.replace('-', '_')
for addrfam in ['inet', 'inet6']:
(valid, value, errmsg) = _validate_interface_option(_opt, val, addrfam=addrfam)
if not valid:
continue
if inet is None and _debopt not in iface_data[addrfam]:
iface_data[addrfam][_debopt] = value
elif inet == addrfam:
iface_data[addrfam][_debopt] = value
for opt in ['up_cmds', 'pre_up_cmds', 'post_up_cmds',
'down_cmds', 'pre_down_cmds', 'post_down_cmds']:
if opt in opts:
iface_data['inet'][opt] = opts[opt]
iface_data['inet6'][opt] = opts[opt]
# Remove incomplete/disabled inet blocks
for (addrfam, opt) in [('inet', 'enable_ipv4'), ('inet6', 'enable_ipv6')]:
if opts.get(opt, None) is False:
iface_data.pop(addrfam)
elif iface_data[addrfam].get('addrfam', '') != addrfam:
iface_data.pop(addrfam)
return adapters
def _parse_settings_source(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['sources'] = [opts['source']]
return adapters
def _parse_network_settings(opts, current):
'''
Filters given options and outputs valid settings for
the global network settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
current = dict((k.lower(), v) for (k, v) in six.iteritems(current))
result = {}
valid = _CONFIG_TRUE + _CONFIG_FALSE
if 'enabled' not in opts:
try:
opts['networking'] = current['networking']
_log_default_network('networking', current['networking'])
except ValueError:
_raise_error_network('networking', valid)
else:
opts['networking'] = opts['enabled']
if opts['networking'] in valid:
if opts['networking'] in _CONFIG_TRUE:
result['networking'] = 'yes'
elif opts['networking'] in _CONFIG_FALSE:
result['networking'] = 'no'
else:
_raise_error_network('networking', valid)
if 'hostname' not in opts:
try:
opts['hostname'] = current['hostname']
_log_default_network('hostname', current['hostname'])
except ValueError:
_raise_error_network('hostname', ['server1.example.com'])
if opts['hostname']:
result['hostname'] = opts['hostname']
else:
_raise_error_network('hostname', ['server1.example.com'])
if 'search' in opts:
result['search'] = opts['search']
return result
def _parse_routes(iface, opts):
'''
Filters given options and outputs valid settings for
the route settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
result = {}
if 'routes' not in opts:
_raise_error_routes(iface, 'routes', 'List of routes')
for opt in opts:
result[opt] = opts[opt]
return result
def _write_file(iface, data, folder, pattern):
'''
Writes a file to disk
'''
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
return filename
def _write_file_routes(iface, data, folder, pattern):
'''
Writes a file to disk
'''
# ifup / ifdown is executing given folder via run-parts.
# according to run-parts man-page, only filenames with this pattern are
# executed: (^[a-zA-Z0-9_-]+$)
# In order to make the routes file work for vlan interfaces
# (default would have been in example /etc/network/if-up.d/route-bond0.12)
# these dots in the iface name need to be replaced by underscores, so it
# can be executed by run-parts
iface = iface.replace('.', '_')
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
__salt__['file.set_mode'](filename, '0755')
return filename
def _write_file_network(data, filename, create=False):
'''
Writes a file to disk
If file does not exist, only create if create
argument is True
'''
if not os.path.exists(filename) and not create:
msg = '{0} cannot be written. {0} does not exist\
and create is set to False'
msg = msg.format(filename)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
def _read_temp(data):
'''
Return what would be written to disk
'''
tout = StringIO()
tout.write(data)
tout.seek(0)
output = tout.readlines()
tout.close()
return output
def _read_temp_ifaces(iface, data):
'''
Return what would be written to disk for interfaces
'''
try:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': data})
# Return as an array so the difflib works
return [item + '\n' for item in ifcfg.split('\n')]
def _write_file_ifaces(iface, data, **settings):
'''
Writes a file to disk
'''
try:
eth_template = JINJA.get_template('debian_eth.jinja')
source_template = JINJA.get_template('debian_source.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
# Read /etc/network/interfaces into a dict
adapters = _parse_interfaces()
# Apply supplied settings over on-disk settings
adapters[iface] = data
ifcfg = ''
for adapter in adapters:
if 'type' in adapters[adapter] and adapters[adapter]['type'] == 'source':
tmp = source_template.render({'name': adapter, 'data': adapters[adapter]})
else:
tmp = eth_template.render({'name': adapter, 'data': adapters[adapter]})
ifcfg = ifcfg + tmp
if adapter == iface:
saved_ifcfg = tmp
_SEPARATE_FILE = False
if 'filename' in settings:
if not settings['filename'].startswith('/'):
filename = '{0}/{1}'.format(_DEB_NETWORK_DIR, settings['filename'])
else:
filename = settings['filename']
_SEPARATE_FILE = True
else:
if 'filename' in adapters[adapter]['data']:
filename = adapters[adapter]['data']
else:
filename = _DEB_NETWORK_FILE
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
if _SEPARATE_FILE:
fout.write(salt.utils.stringutils.to_str(saved_ifcfg))
else:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return saved_ifcfg.split('\n')
def _write_file_ppp_ifaces(iface, data):
'''
Writes a file to disk
'''
try:
template = JINJA.get_template('debian_ppp_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_ppp_eth.jinja')
return ''
adapters = _parse_interfaces()
adapters[iface] = data
ifcfg = ''
tmp = template.render({'data': adapters[iface]})
ifcfg = tmp + ifcfg
filename = _DEB_PPP_DIR + '/' + adapters[iface]['data']['inet']['provider']
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.fopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return filename
def build_bond(iface, **settings):
'''
Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb
'''
deb_major = __grains__['osrelease'][:1]
opts = _parse_settings_bond(settings, iface)
try:
template = JINJA.get_template('conf.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template conf.jinja')
return ''
data = template.render({'name': iface, 'bonding': opts})
if 'test' in settings and settings['test']:
return _read_temp(data)
_write_file(iface, data, _DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
if deb_major == '5':
for line_type in ('alias', 'options'):
cmd = ['sed', '-i', '-e', r'/^{0}\s{1}.*/d'.format(line_type, iface),
'/etc/modprobe.conf']
__salt__['cmd.run'](cmd, python_shell=False)
__salt__['file.append']('/etc/modprobe.conf', path)
# Load kernel module
__salt__['kmod.load']('bonding')
# install ifenslave-2.6
__salt__['pkg.install']('ifenslave-2.6')
return _read_file(path)
def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'vlan':
settings['vlan'] = 'yes'
__salt__['pkg.install']('vlan')
elif iface_type == 'pppoe':
settings['pppoe'] = 'yes'
if not __salt__['pkg.version']('ppp'):
inst = __salt__['pkg.install']('ppp')
elif iface_type == 'bond':
if 'slaves' not in settings:
msg = 'slaves is a required setting for bond interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'bridge':
if 'ports' not in settings:
msg = (
'ports is a required setting for bridge interfaces on Debian '
'or Ubuntu based systems'
)
log.error(msg)
raise AttributeError(msg)
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'pppoe']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
if iface_type in ['source']:
opts = _parse_settings_source(settings, iface_type, enabled, iface)
if 'test' in settings and settings['test']:
return _read_temp_ifaces(iface, opts[iface])
ifcfg = _write_file_ifaces(iface, opts[iface], **settings)
if iface_type == 'pppoe':
_write_file_ppp_ifaces(iface, opts[iface])
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg]
def build_routes(iface, **settings):
'''
Add route scripts for a network interface using up commands.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
'''
opts = _parse_routes(iface, settings)
try:
template = JINJA.get_template('route_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template route_eth.jinja')
return ''
add_routecfg = template.render(route_type='add',
routes=opts['routes'],
iface=iface)
del_routecfg = template.render(route_type='del',
routes=opts['routes'],
iface=iface)
if 'test' in settings and settings['test']:
return _read_temp(add_routecfg + del_routecfg)
filename = _write_file_routes(iface,
add_routecfg,
_DEB_NETWORK_UP_DIR,
'route-{0}')
results = _read_file(filename)
filename = _write_file_routes(iface,
del_routecfg,
_DEB_NETWORK_DOWN_DIR,
'route-{0}')
results += _read_file(filename)
return results
def down(iface, iface_type):
'''
Shutdown a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.down eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought down.
if iface_type not in ['slave', 'source']:
return __salt__['cmd.run'](['ifdown', iface])
return None
def get_bond(iface):
'''
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
'''
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
return _read_file(path)
def get_interface(iface):
'''
Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
adapters = _parse_interfaces()
if iface in adapters:
try:
if iface == 'source':
template = JINJA.get_template('debian_source.jinja')
else:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': adapters[iface]})
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg.split('\n')]
else:
return []
def up(iface, iface_type): # pylint: disable=C0103
'''
Start up a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.up eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought up.
if iface_type not in ('slave', 'source'):
return __salt__['cmd.run'](['ifup', iface])
return None
def get_network_settings():
'''
Return the contents of the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_network_settings
'''
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
settings = {}
if __salt__['service.available']('networking'):
if __salt__['service.status']('networking'):
settings['networking'] = "yes"
else:
settings['networking'] = "no"
else:
settings['networking'] = "no"
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
settings['hostname'] = hostname
settings['domainname'] = domainname
settings['searchdomain'] = searchdomain
else:
settings = _parse_current_network_settings()
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(settings)
return _read_temp(network)
def get_routes(iface):
'''
Return the routes for the interface
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0
'''
filename = os.path.join(_DEB_NETWORK_UP_DIR, 'route-{0}'.format(iface))
results = _read_file(filename)
filename = os.path.join(_DEB_NETWORK_DOWN_DIR, 'route-{0}'.format(iface))
results += _read_file(filename)
return results
def build_network_settings(**settings):
'''
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
'''
changes = []
# Read current configuration and store default values
current_network_settings = _parse_current_network_settings()
# Build settings
opts = _parse_network_settings(settings, current_network_settings)
# Ubuntu has moved away from /etc/default/networking
# beginning with the 12.04 release so we disable or enable
# the networking related services on boot
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
if opts['networking'] == 'yes':
service_cmd = 'service.enable'
else:
service_cmd = 'service.disable'
if __salt__['service.available']('NetworkManager'):
__salt__[service_cmd]('NetworkManager')
if __salt__['service.available']('networking'):
__salt__[service_cmd]('networking')
else:
try:
template = JINJA.get_template('network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template network.jinja')
return ''
network = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(network)
# Write settings
_write_file_network(network, _DEB_NETWORKING_FILE, True)
# Get hostname and domain from opts
sline = opts['hostname'].split('.', 1)
opts['hostname'] = sline[0]
current_domainname = current_network_settings['domainname']
current_searchdomain = current_network_settings['searchdomain']
new_domain = False
if len(sline) > 1:
new_domainname = sline[1]
if new_domainname != current_domainname:
domainname = new_domainname
opts['domainname'] = new_domainname
new_domain = True
else:
domainname = current_domainname
opts['domainname'] = domainname
else:
domainname = current_domainname
opts['domainname'] = domainname
new_search = False
if 'search' in opts:
new_searchdomain = opts['search']
if new_searchdomain != current_searchdomain:
searchdomain = new_searchdomain
opts['searchdomain'] = new_searchdomain
new_search = True
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
# If the domain changes, then we should write the resolv.conf file.
if new_domain or new_search:
# Look for existing domain line and update if necessary
resolve = _parse_resolve()
domain_prog = re.compile(r'domain\s+')
search_prog = re.compile(r'search\s+')
new_contents = []
for item in _read_file(_DEB_RESOLV_FILE):
if domain_prog.match(item):
item = 'domain {0}'.format(domainname)
elif search_prog.match(item):
item = 'search {0}'.format(searchdomain)
new_contents.append(item)
# A domain line didn't exist so we'll add one in
# with the new domainname
if 'domain' not in resolve:
new_contents.insert(0, 'domain {0}' . format(domainname))
# A search line didn't exist so we'll add one in
# with the new search domain
if 'search' not in resolve:
new_contents.insert('domain' in resolve, 'search {0}'.format(searchdomain))
new_resolv = '\n'.join(new_contents)
# Write /etc/resolv.conf
if not ('test' in settings and settings['test']):
_write_file_network(new_resolv, _DEB_RESOLV_FILE)
# used for returning the results back
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(opts)
changes.extend(_read_temp(network))
return changes
|
saltstack/salt
|
salt/modules/debian_ip.py
|
build_network_settings
|
python
|
def build_network_settings(**settings):
'''
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
'''
changes = []
# Read current configuration and store default values
current_network_settings = _parse_current_network_settings()
# Build settings
opts = _parse_network_settings(settings, current_network_settings)
# Ubuntu has moved away from /etc/default/networking
# beginning with the 12.04 release so we disable or enable
# the networking related services on boot
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
if opts['networking'] == 'yes':
service_cmd = 'service.enable'
else:
service_cmd = 'service.disable'
if __salt__['service.available']('NetworkManager'):
__salt__[service_cmd]('NetworkManager')
if __salt__['service.available']('networking'):
__salt__[service_cmd]('networking')
else:
try:
template = JINJA.get_template('network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template network.jinja')
return ''
network = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(network)
# Write settings
_write_file_network(network, _DEB_NETWORKING_FILE, True)
# Get hostname and domain from opts
sline = opts['hostname'].split('.', 1)
opts['hostname'] = sline[0]
current_domainname = current_network_settings['domainname']
current_searchdomain = current_network_settings['searchdomain']
new_domain = False
if len(sline) > 1:
new_domainname = sline[1]
if new_domainname != current_domainname:
domainname = new_domainname
opts['domainname'] = new_domainname
new_domain = True
else:
domainname = current_domainname
opts['domainname'] = domainname
else:
domainname = current_domainname
opts['domainname'] = domainname
new_search = False
if 'search' in opts:
new_searchdomain = opts['search']
if new_searchdomain != current_searchdomain:
searchdomain = new_searchdomain
opts['searchdomain'] = new_searchdomain
new_search = True
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
else:
searchdomain = current_searchdomain
opts['searchdomain'] = searchdomain
# If the domain changes, then we should write the resolv.conf file.
if new_domain or new_search:
# Look for existing domain line and update if necessary
resolve = _parse_resolve()
domain_prog = re.compile(r'domain\s+')
search_prog = re.compile(r'search\s+')
new_contents = []
for item in _read_file(_DEB_RESOLV_FILE):
if domain_prog.match(item):
item = 'domain {0}'.format(domainname)
elif search_prog.match(item):
item = 'search {0}'.format(searchdomain)
new_contents.append(item)
# A domain line didn't exist so we'll add one in
# with the new domainname
if 'domain' not in resolve:
new_contents.insert(0, 'domain {0}' . format(domainname))
# A search line didn't exist so we'll add one in
# with the new search domain
if 'search' not in resolve:
new_contents.insert('domain' in resolve, 'search {0}'.format(searchdomain))
new_resolv = '\n'.join(new_contents)
# Write /etc/resolv.conf
if not ('test' in settings and settings['test']):
_write_file_network(new_resolv, _DEB_RESOLV_FILE)
# used for returning the results back
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(opts)
changes.extend(_read_temp(network))
return changes
|
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debian_ip.py#L1902-L2024
|
[
"def _parse_current_network_settings():\n '''\n Parse /etc/default/networking and return current configuration\n '''\n opts = salt.utils.odict.OrderedDict()\n opts['networking'] = ''\n\n if os.path.isfile(_DEB_NETWORKING_FILE):\n with salt.utils.files.fopen(_DEB_NETWORKING_FILE) as contents:\n for line in contents:\n salt.utils.stringutils.to_unicode(line)\n if line.startswith('#'):\n continue\n elif line.startswith('CONFIGURE_INTERFACES'):\n opts['networking'] = line.split('=', 1)[1].strip()\n\n hostname = _parse_hostname()\n domainname = _parse_domainname()\n searchdomain = _parse_searchdomain()\n\n opts['hostname'] = hostname\n opts['domainname'] = domainname\n opts['searchdomain'] = searchdomain\n return opts\n",
"def _parse_network_settings(opts, current):\n '''\n Filters given options and outputs valid settings for\n the global network settings file.\n '''\n # Normalize keys\n opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))\n current = dict((k.lower(), v) for (k, v) in six.iteritems(current))\n result = {}\n\n valid = _CONFIG_TRUE + _CONFIG_FALSE\n if 'enabled' not in opts:\n try:\n opts['networking'] = current['networking']\n _log_default_network('networking', current['networking'])\n except ValueError:\n _raise_error_network('networking', valid)\n else:\n opts['networking'] = opts['enabled']\n\n if opts['networking'] in valid:\n if opts['networking'] in _CONFIG_TRUE:\n result['networking'] = 'yes'\n elif opts['networking'] in _CONFIG_FALSE:\n result['networking'] = 'no'\n else:\n _raise_error_network('networking', valid)\n\n if 'hostname' not in opts:\n try:\n opts['hostname'] = current['hostname']\n _log_default_network('hostname', current['hostname'])\n except ValueError:\n _raise_error_network('hostname', ['server1.example.com'])\n\n if opts['hostname']:\n result['hostname'] = opts['hostname']\n else:\n _raise_error_network('hostname', ['server1.example.com'])\n\n if 'search' in opts:\n result['search'] = opts['search']\n\n return result\n"
] |
# -*- coding: utf-8 -*-
'''
The networking module for Debian-based distros
References:
* http://www.debian.org/doc/manuals/debian-reference/ch05.en.html
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import functools
import logging
import os.path
import os
import re
import time
# Import third party libs
import jinja2
import jinja2.exceptions
from salt.ext import six
from salt.ext.six.moves import StringIO # pylint: disable=import-error,no-name-in-module
# Import salt libs
import salt.utils.dns
import salt.utils.files
import salt.utils.odict
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.validate.net
# Set up logging
log = logging.getLogger(__name__)
# Set up template environment
JINJA = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'debian_ip')
)
)
# Define the module's virtual name
__virtualname__ = 'ip'
def __virtual__():
'''
Confine this module to Debian-based distros
'''
if __grains__['os_family'] == 'Debian':
return __virtualname__
return (False, 'The debian_ip module could not be loaded: '
'unsupported OS family')
_ETHTOOL_CONFIG_OPTS = {
'speed': 'link-speed',
'duplex': 'link-duplex',
'autoneg': 'ethernet-autoneg',
'ethernet-port': 'ethernet-port',
'wol': 'ethernet-wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'rx': 'offload-rx',
'tx': 'offload-tx',
'sg': 'offload-sg',
'tso': 'offload-tso',
'ufo': 'offload-ufo',
'gso': 'offload-gso',
'gro': 'offload-gro',
'lro': 'offload-lro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_REV_ETHTOOL_CONFIG_OPTS = {
'link-speed': 'speed',
'link-duplex': 'duplex',
'ethernet-autoneg': 'autoneg',
'ethernet-port': 'ethernet-port',
'ethernet-wol': 'wol',
'driver-message-level': 'driver-message-level',
'ethernet-pause-rx': 'ethernet-pause-rx',
'ethernet-pause-tx': 'ethernet-pause-tx',
'ethernet-pause-autoneg': 'ethernet-pause-autoneg',
'offload-rx': 'rx',
'offload-tx': 'tx',
'offload-sg': 'sg',
'offload-tso': 'tso',
'offload-ufo': 'ufo',
'offload-gso': 'gso',
'offload-lro': 'lro',
'offload-gro': 'gro',
'hardware-irq-coalesce-adaptive-rx': 'hardware-irq-coalesce-adaptive-rx',
'hardware-irq-coalesce-adaptive-tx': 'hardware-irq-coalesce-adaptive-tx',
'hardware-irq-coalesce-rx-usecs': 'hardware-irq-coalesce-rx-usecs',
'hardware-irq-coalesce-rx-frames': 'hardware-irq-coalesce-rx-frames',
'hardware-dma-ring-rx': 'hardware-dma-ring-rx',
'hardware-dma-ring-rx-mini': 'hardware-dma-ring-rx-mini',
'hardware-dma-ring-rx-jumbo': 'hardware-dma-ring-rx-jumbo',
'hardware-dma-ring-tx': 'hardware-dma-ring-tx',
}
_DEB_CONFIG_PPPOE_OPTS = {
'user': 'user',
'password': 'password',
'provider': 'provider',
'pppoe_iface': 'pppoe_iface',
'noipdefault': 'noipdefault',
'usepeerdns': 'usepeerdns',
'defaultroute': 'defaultroute',
'holdoff': 'holdoff',
'maxfail': 'maxfail',
'hide-password': 'hide-password',
'lcp-echo-interval': 'lcp-echo-interval',
'lcp-echo-failure': 'lcp-echo-failure',
'connect': 'connect',
'noauth': 'noauth',
'persist': 'persist',
'mtu': 'mtu',
'noaccomp': 'noaccomp',
'linkname': 'linkname',
}
_DEB_ROUTES_FILE = '/etc/network/routes'
_DEB_NETWORK_FILE = '/etc/network/interfaces'
_DEB_NETWORK_DIR = '/etc/network/interfaces.d/'
_DEB_NETWORK_UP_DIR = '/etc/network/if-up.d/'
_DEB_NETWORK_DOWN_DIR = '/etc/network/if-down.d/'
_DEB_NETWORK_CONF_FILES = '/etc/modprobe.d/'
_DEB_NETWORKING_FILE = '/etc/default/networking'
_DEB_HOSTNAME_FILE = '/etc/hostname'
_DEB_RESOLV_FILE = '/etc/resolv.conf'
_DEB_PPP_DIR = '/etc/ppp/peers/'
_CONFIG_TRUE = ['yes', 'on', 'true', '1', True]
_CONFIG_FALSE = ['no', 'off', 'false', '0', False]
_IFACE_TYPES = [
'eth', 'bond', 'alias', 'clone',
'ipsec', 'dialup', 'bridge', 'slave',
'vlan', 'pppoe', 'source',
]
def _error_msg_iface(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, '|'.join(str(e) for e in expected))
def _error_msg_routes(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, expected)
def _log_default_iface(iface, opt, value):
log.info(
'Using default option -- Interface: %s Option: %s Value: %s',
iface, opt, value
)
def _error_msg_network(option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]'
return msg.format(option, '|'.join(str(e) for e in expected))
def _log_default_network(opt, value):
log.info('Using existing setting -- Setting: %s Value: %s', opt, value)
def _raise_error_iface(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_iface(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_network(option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_network(option, expected)
log.error(msg)
raise AttributeError(msg)
def _raise_error_routes(iface, option, expected):
'''
Log and raise an error with a logical formatted message.
'''
msg = _error_msg_routes(iface, option, expected)
log.error(msg)
raise AttributeError(msg)
def _read_file(path):
'''
Reads and returns the contents of a text file
'''
try:
with salt.utils.files.flopen(path, 'rb') as contents:
return [salt.utils.stringutils.to_str(line) for line in contents.readlines()]
except (OSError, IOError):
return ''
def _parse_resolve():
'''
Parse /etc/resolv.conf
'''
return salt.utils.dns.parse_resolv(_DEB_RESOLV_FILE)
def _parse_domainname():
'''
Parse /etc/resolv.conf and return domainname
'''
return _parse_resolve().get('domain', '')
def _parse_searchdomain():
'''
Parse /etc/resolv.conf and return searchdomain
'''
return _parse_resolve().get('search', '')
def _parse_hostname():
'''
Parse /etc/hostname and return hostname
'''
contents = _read_file(_DEB_HOSTNAME_FILE)
if contents:
return contents[0].split('\n')[0]
else:
return ''
def _parse_current_network_settings():
'''
Parse /etc/default/networking and return current configuration
'''
opts = salt.utils.odict.OrderedDict()
opts['networking'] = ''
if os.path.isfile(_DEB_NETWORKING_FILE):
with salt.utils.files.fopen(_DEB_NETWORKING_FILE) as contents:
for line in contents:
salt.utils.stringutils.to_unicode(line)
if line.startswith('#'):
continue
elif line.startswith('CONFIGURE_INTERFACES'):
opts['networking'] = line.split('=', 1)[1].strip()
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
opts['hostname'] = hostname
opts['domainname'] = domainname
opts['searchdomain'] = searchdomain
return opts
# def __validator_func(value):
# return (valid: True/False, (transformed) value, error message)
def __ipv4_quad(value):
'''validate an IPv4 address'''
return (salt.utils.validate.net.ipv4_addr(value), value,
'dotted IPv4 address')
def __ipv6(value):
'''validate an IPv6 address'''
return (salt.utils.validate.net.ipv6_addr(value), value,
'IPv6 address')
def __mac(value):
'''validate a mac address'''
return (salt.utils.validate.net.mac(value), value,
'MAC address')
def __anything(value):
return (True, value, None)
def __int(value):
'''validate an integer'''
valid, _value = False, value
try:
_value = int(value)
valid = True
except ValueError:
pass
return (valid, _value, 'integer')
def __float(value):
'''validate a float'''
valid, _value = False, value
try:
_value = float(value)
valid = True
except ValueError:
pass
return (valid, _value, 'float')
def __ipv4_netmask(value):
'''validate an IPv4 dotted quad or integer CIDR netmask'''
valid, errmsg = False, 'dotted quad or integer CIDR (0->32)'
valid, value, _ = __int(value)
if not (valid and 0 <= value <= 32):
valid = salt.utils.validate.net.netmask(value)
return (valid, value, errmsg)
def __ipv6_netmask(value):
'''validate an IPv6 integer netmask'''
valid, errmsg = False, 'IPv6 netmask (0->128)'
valid, value, _ = __int(value)
valid = (valid and 0 <= value <= 128)
return (valid, value, errmsg)
def __within2(value, within=None, errmsg=None, dtype=None):
'''validate that a value is in ``within`` and optionally a ``dtype``'''
valid, _value = False, value
if dtype:
try:
_value = dtype(value) # TODO: this is a bit loose when dtype is a class
valid = _value in within
except ValueError:
pass
else:
valid = _value in within
if errmsg is None:
if dtype:
typename = getattr(dtype, '__name__',
hasattr(dtype, '__class__')
and getattr(dtype.__class__, 'name', dtype))
errmsg = '{0} within \'{1}\''.format(typename, within)
else:
errmsg = 'within \'{0}\''.format(within)
return (valid, _value, errmsg)
def __within(within=None, errmsg=None, dtype=None):
return functools.partial(__within2, within=within,
errmsg=errmsg, dtype=dtype)
def __space_delimited_list(value):
'''validate that a value contains one or more space-delimited values'''
if isinstance(value, six.string_types):
value = value.strip().split()
if hasattr(value, '__iter__') and value != []:
return (True, value, 'space-delimited string')
else:
return (False, value, '{0} is not a valid space-delimited value.\n'.format(value))
SALT_ATTR_TO_DEBIAN_ATTR_MAP = {
'dns': 'dns-nameservers',
'search': 'dns-search',
'hwaddr': 'hwaddress', # TODO: this limits bootp functionality
'ipaddr': 'address',
'ipaddrs': 'addresses',
}
DEBIAN_ATTR_TO_SALT_ATTR_MAP = dict(
(v, k) for (k, v) in six.iteritems(SALT_ATTR_TO_DEBIAN_ATTR_MAP))
# TODO
DEBIAN_ATTR_TO_SALT_ATTR_MAP['address'] = 'address'
DEBIAN_ATTR_TO_SALT_ATTR_MAP['hwaddress'] = 'hwaddress'
IPV4_VALID_PROTO = ['bootp', 'dhcp', 'static', 'manual', 'loopback', 'ppp']
IPV4_ATTR_MAP = {
'proto': __within(IPV4_VALID_PROTO, dtype=six.text_type),
# ipv4 static & manual
'address': __ipv4_quad,
'addresses': __anything,
'netmask': __ipv4_netmask,
'broadcast': __ipv4_quad,
'metric': __int,
'gateway': __ipv4_quad, # supports a colon-delimited list
'pointopoint': __ipv4_quad,
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'link', 'host'], dtype=six.text_type),
# dhcp
'hostname': __anything,
'leasehours': __int,
'leasetime': __int,
'vendor': __anything,
'client': __anything,
# bootp
'bootfile': __anything,
'server': __ipv4_quad,
'hwaddr': __mac,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'dstaddr': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# bond
'slaves': __anything,
# ppp
'provider': __anything,
'unit': __int,
'options': __anything,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
#
'network': __anything, # i don't know what this is
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
IPV6_VALID_PROTO = ['auto', 'loopback', 'static', 'manual',
'dhcp', 'v4tunnel', '6to4']
IPV6_ATTR_MAP = {
'proto': __within(IPV6_VALID_PROTO),
# ipv6 static & manual
'address': __ipv6,
'addresses': __anything,
'netmask': __ipv6_netmask,
'broadcast': __ipv6,
'gateway': __ipv6, # supports a colon-delimited list
'hwaddress': __mac,
'mtu': __int,
'scope': __within(['global', 'site', 'link', 'host'], dtype=six.text_type),
# inet6 auto
'privext': __within([0, 1, 2], dtype=int),
'dhcp': __within([0, 1], dtype=int),
# inet6 static & manual & dhcp
'media': __anything,
'accept_ra': __within([0, 1], dtype=int),
'autoconf': __within([0, 1], dtype=int),
'preferred-lifetime': __int,
'dad-attempts': __int, # 0 to disable
'dad-interval': __float,
# bond
'slaves': __anything,
# tunnel
'mode': __within(['gre', 'GRE', 'ipip', 'IPIP', '802.3ad'], dtype=six.text_type),
'endpoint': __ipv4_quad,
'local': __ipv4_quad,
'ttl': __int,
# resolvconf
'dns-nameservers': __space_delimited_list,
'dns-search': __space_delimited_list,
#
'vlan-raw-device': __anything,
'test': __anything, # TODO
'enable_ipv4': __anything, # TODO
'enable_ipv6': __anything, # TODO
}
WIRELESS_ATTR_MAP = {
'wireless-essid': __anything,
'wireless-mode': __anything, # TODO
'wpa-ap-scan': __within([0, 1, 2], dtype=int), # TODO
'wpa-conf': __anything,
'wpa-driver': __anything,
'wpa-group': __anything,
'wpa-key-mgmt': __anything,
'wpa-pairwise': __anything,
'wpa-psk': __anything,
'wpa-proto': __anything, # partial(__within,
'wpa-roam': __anything,
'wpa-ssid': __anything, # TODO
}
ATTRMAPS = {
'inet': [IPV4_ATTR_MAP, WIRELESS_ATTR_MAP],
'inet6': [IPV6_ATTR_MAP, WIRELESS_ATTR_MAP]
}
def _validate_interface_option(attr, value, addrfam='inet'):
'''lookup the validation function for a [addrfam][attr] and
return the results
:param attr: attribute name
:param value: raw setting value
:param addrfam: address family (inet, inet6,
'''
valid, _value, errmsg = False, value, 'Unknown validator'
attrmaps = ATTRMAPS.get(addrfam, [])
for attrmap in attrmaps:
if attr in attrmap:
validate_func = attrmap[attr]
(valid, _value, errmsg) = validate_func(value)
break
return (valid, _value, errmsg)
def _attrmaps_contain_attr(attr):
return (
attr in WIRELESS_ATTR_MAP or
attr in IPV4_ATTR_MAP or
attr in IPV6_ATTR_MAP)
def _parse_interfaces(interface_files=None):
'''
Parse /etc/network/interfaces and return current configured interfaces
'''
if interface_files is None:
interface_files = []
# Add this later.
if os.path.exists(_DEB_NETWORK_DIR):
interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]
if os.path.isfile(_DEB_NETWORK_FILE):
interface_files.insert(0, _DEB_NETWORK_FILE)
adapters = salt.utils.odict.OrderedDict()
method = -1
for interface_file in interface_files:
with salt.utils.files.fopen(interface_file) as interfaces:
# This ensures iface_dict exists, but does not ensure we're not reading a new interface.
iface_dict = {}
for line in interfaces:
line = salt.utils.stringutils.to_unicode(line)
# Identify the clauses by the first word of each line.
# Go to the next line if the current line is a comment
# or all spaces.
if line.lstrip().startswith('#') or line.isspace():
continue
# Parse the iface clause
if line.startswith('iface'):
sline = line.split()
if len(sline) != 4:
msg = 'Interface file malformed: {0}.'
msg = msg.format(sline)
log.error(msg)
raise AttributeError(msg)
iface_name = sline[1]
addrfam = sline[2]
method = sline[3]
# Create item in dict, if not already there
if iface_name not in adapters:
adapters[iface_name] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters[iface_name]:
adapters[iface_name]['data'] = salt.utils.odict.OrderedDict()
if addrfam not in adapters[iface_name]['data']:
adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict()
iface_dict = adapters[iface_name]['data'][addrfam]
iface_dict['addrfam'] = addrfam
iface_dict['proto'] = method
iface_dict['filename'] = interface_file
# Parse the detail clauses.
elif line[0].isspace():
sline = line.split()
# conf file attr: dns-nameservers
# salt states.network attr: dns
attr, valuestr = line.rstrip().split(None, 1)
if _attrmaps_contain_attr(attr):
if '-' in attr:
attrname = attr.replace('-', '_')
else:
attrname = attr
(valid, value, errmsg) = _validate_interface_option(
attr, valuestr, addrfam)
if attrname == 'address' and 'address' in iface_dict:
if 'addresses' not in iface_dict:
iface_dict['addresses'] = []
iface_dict['addresses'].append(value)
else:
iface_dict[attrname] = value
elif attr in _REV_ETHTOOL_CONFIG_OPTS:
if 'ethtool' not in iface_dict:
iface_dict['ethtool'] = salt.utils.odict.OrderedDict()
iface_dict['ethtool'][attr] = valuestr
elif attr.startswith('bond'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bonding' not in iface_dict:
iface_dict['bonding'] = salt.utils.odict.OrderedDict()
iface_dict['bonding'][opt] = valuestr
elif attr.startswith('bridge'):
opt = re.split(r'[_-]', attr, maxsplit=1)[1]
if 'bridging' not in iface_dict:
iface_dict['bridging'] = salt.utils.odict.OrderedDict()
iface_dict['bridging'][opt] = valuestr
elif attr in ['up', 'pre-up', 'post-up',
'down', 'pre-down', 'post-down']:
cmd = valuestr
cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr))
if cmd_key not in iface_dict:
iface_dict[cmd_key] = []
iface_dict[cmd_key].append(cmd)
elif line.startswith('auto'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['enabled'] = True
elif line.startswith('allow-hotplug'):
for word in line.split()[1:]:
if word not in adapters:
adapters[word] = salt.utils.odict.OrderedDict()
adapters[word]['hotplug'] = True
elif line.startswith('source'):
if 'source' not in adapters:
adapters['source'] = salt.utils.odict.OrderedDict()
# Create item in dict, if not already there
if 'data' not in adapters['source']:
adapters['source']['data'] = salt.utils.odict.OrderedDict()
adapters['source']['data']['sources'] = []
adapters['source']['data']['sources'].append(line.split()[1])
# Return a sorted list of the keys for bond, bridge and ethtool options to
# ensure a consistent order
for iface_name in adapters:
if iface_name == 'source':
continue
if 'data' not in adapters[iface_name]:
msg = 'Interface file malformed for interface: {0}.'.format(iface_name)
log.error(msg)
adapters.pop(iface_name)
continue
for opt in ['ethtool', 'bonding', 'bridging']:
for inet in ['inet', 'inet6']:
if inet in adapters[iface_name]['data']:
if opt in adapters[iface_name]['data'][inet]:
opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys())
adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys
return adapters
def _parse_ethtool_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
if 'autoneg' in opts:
if opts['autoneg'] in _CONFIG_TRUE:
config.update({'autoneg': 'on'})
elif opts['autoneg'] in _CONFIG_FALSE:
config.update({'autoneg': 'off'})
else:
_raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE)
if 'duplex' in opts:
valid = ['full', 'half']
if opts['duplex'] in valid:
config.update({'duplex': opts['duplex']})
else:
_raise_error_iface(iface, 'duplex', valid)
if 'speed' in opts:
valid = ['10', '100', '1000', '10000']
if six.text_type(opts['speed']) in valid:
config.update({'speed': opts['speed']})
else:
_raise_error_iface(iface, opts['speed'], valid)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'on'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'off'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_ethtool_pppoe_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
for opt in _DEB_CONFIG_PPPOE_OPTS:
if opt in opts:
config[opt] = opts[opt]
if 'provider' in opts and not opts['provider']:
_raise_error_iface(iface, 'provider', _CONFIG_TRUE + _CONFIG_FALSE)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option in ('noipdefault', 'usepeerdns', 'defaultroute', 'hide-password', 'noauth', 'persist', 'noaccomp'):
if option in opts:
if opts[option] in _CONFIG_TRUE:
config.update({option: 'True'})
elif opts[option] in _CONFIG_FALSE:
config.update({option: 'False'})
else:
_raise_error_iface(iface, option, valid)
return config
def _parse_settings_bond(opts, iface):
'''
Filters given options and outputs valid settings for requested
operation. If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond_def = {
# 803.ad aggregation selection logic
# 0 for stable (default)
# 1 for bandwidth
# 2 for count
'ad_select': '0',
# Max number of transmit queues (default = 16)
'tx_queues': '16',
# Link monitoring in milliseconds. Most NICs support this
'miimon': '100',
# ARP interval in milliseconds
'arp_interval': '250',
# Delay before considering link down in milliseconds (miimon * 2)
'downdelay': '200',
# lacp_rate 0: Slow - every 30 seconds
# lacp_rate 1: Fast - every 1 second
'lacp_rate': '0',
# Max bonds for this driver
'max_bonds': '1',
# Specifies the time, in milliseconds, to wait before
# enabling a slave after a link recovery has been
# detected. Only used with miimon.
'updelay': '0',
# Used with miimon.
# On: driver sends mii
# Off: ethtool sends mii
'use_carrier': 'on',
# Default. Don't change unless you know what you are doing.
'xmit_hash_policy': 'layer2',
}
if opts['mode'] in ['balance-rr', '0']:
log.info('Device: %s Bonding Mode: load balancing (round-robin)', iface)
return _parse_settings_bond_0(opts, iface, bond_def)
elif opts['mode'] in ['active-backup', '1']:
log.info('Device: %s Bonding Mode: fault-tolerance (active-backup)', iface)
return _parse_settings_bond_1(opts, iface, bond_def)
elif opts['mode'] in ['balance-xor', '2']:
log.info('Device: %s Bonding Mode: load balancing (xor)', iface)
return _parse_settings_bond_2(opts, iface, bond_def)
elif opts['mode'] in ['broadcast', '3']:
log.info('Device: %s Bonding Mode: fault-tolerance (broadcast)', iface)
return _parse_settings_bond_3(opts, iface, bond_def)
elif opts['mode'] in ['802.3ad', '4']:
log.info('Device: %s Bonding Mode: IEEE 802.3ad Dynamic link '
'aggregation', iface)
return _parse_settings_bond_4(opts, iface, bond_def)
elif opts['mode'] in ['balance-tlb', '5']:
log.info('Device: %s Bonding Mode: transmit load balancing', iface)
return _parse_settings_bond_5(opts, iface, bond_def)
elif opts['mode'] in ['balance-alb', '6']:
log.info('Device: %s Bonding Mode: adaptive load balancing', iface)
return _parse_settings_bond_6(opts, iface, bond_def)
else:
valid = [
'0', '1', '2', '3', '4', '5', '6',
'balance-rr', 'active-backup', 'balance-xor',
'broadcast', '802.3ad', 'balance-tlb', 'balance-alb'
]
_raise_error_iface(iface, 'mode', valid)
def _parse_settings_bond_0(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond0.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '0'}
# ARP targets in n.n.n.n form
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
return bond
def _parse_settings_bond_1(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '1'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
if not (__grains__['os'] == "Ubuntu" and __grains__['osrelease_info'][0] >= 16):
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_2(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond2.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '2'}
valid = ['list of ips (up to 16)']
if 'arp_ip_target' in opts:
if isinstance(opts['arp_ip_target'], list):
if 1 <= len(opts['arp_ip_target']) <= 16:
bond.update({'arp_ip_target': ''})
for ip in opts['arp_ip_target']: # pylint: disable=C0103
if bond['arp_ip_target']:
bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip
else:
bond['arp_ip_target'] = ip
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
else:
_raise_error_iface(iface, 'arp_ip_target', valid)
if 'arp_interval' in opts:
try:
int(opts['arp_interval'])
bond.update({'arp_interval': opts['arp_interval']})
except ValueError:
_raise_error_iface(iface, 'arp_interval', ['integer'])
else:
_log_default_iface(iface, 'arp_interval', bond_def['arp_interval'])
bond.update({'arp_interval': bond_def['arp_interval']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_3(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond3.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '3'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
return bond
def _parse_settings_bond_4(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond4.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '4'}
for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']:
if binding in opts:
if binding == 'lacp_rate':
if opts[binding] == 'fast':
opts.update({binding: '1'})
if opts[binding] == 'slow':
opts.update({binding: '0'})
valid = ['fast', '1', 'slow', '0']
else:
valid = ['integer']
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, valid)
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'hashing-algorithm' in opts:
valid = ['layer2', 'layer2+3', 'layer3+4']
if opts['hashing-algorithm'] in valid:
bond.update({'xmit_hash_policy': opts['hashing-algorithm']})
else:
_raise_error_iface(iface, 'hashing-algorithm', valid)
return bond
def _parse_settings_bond_5(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond5.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '5'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_settings_bond_6(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond6.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '6'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except ValueError:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond
def _parse_bridge_opts(opts, iface):
'''
Filters given options and outputs valid settings for BRIDGING_OPTS
If an option has a value that is not expected, this
function will log the Interface, Setting and what was expected.
'''
config = {}
if 'ports' in opts:
if isinstance(opts['ports'], list):
opts['ports'] = ' '.join(opts['ports'])
config.update({'ports': opts['ports']})
for opt in ['ageing', 'fd', 'gcint', 'hello', 'maxage']:
if opt in opts:
try:
float(opts[opt])
config.update({opt: opts[opt]})
except ValueError:
_raise_error_iface(iface, opt, ['float'])
for opt in ['bridgeprio', 'maxwait']:
if opt in opts:
if isinstance(opts[opt], int):
config.update({opt: opts[opt]})
else:
_raise_error_iface(iface, opt, ['integer'])
if 'hw' in opts:
# match 12 hex digits with either : or - as separators between pairs
if re.match('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$',
opts['hw'].lower()):
config.update({'hw': opts['hw']})
else:
_raise_error_iface(iface, 'hw', ['valid MAC address'])
for opt in ['pathcost', 'portprio']:
if opt in opts:
try:
port, cost_or_prio = opts[opt].split()
int(cost_or_prio)
config.update({opt: '{0} {1}'.format(port, cost_or_prio)})
except ValueError:
_raise_error_iface(iface, opt, ['interface integer'])
if 'stp' in opts:
if opts['stp'] in _CONFIG_TRUE:
config.update({'stp': 'on'})
elif opts['stp'] in _CONFIG_FALSE:
config.update({'stp': 'off'})
else:
_raise_error_iface(iface, 'stp', _CONFIG_TRUE + _CONFIG_FALSE)
if 'waitport' in opts:
if isinstance(opts['waitport'], int):
config.update({'waitport': opts['waitport']})
else:
values = opts['waitport'].split()
waitport_time = values.pop(0)
if waitport_time.isdigit() and values:
config.update({
'waitport': '{0} {1}'.format(
waitport_time, ' '.join(values)
)
})
else:
_raise_error_iface(iface, opt, ['integer [interfaces]'])
return config
def _parse_settings_eth(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['inet'] = salt.utils.odict.OrderedDict()
iface_data['inet6'] = salt.utils.odict.OrderedDict()
if enabled:
adapters[iface]['enabled'] = True
if opts.get('hotplug', False):
adapters[iface]['hotplug'] = True
if opts.get('enable_ipv6', None) and opts.get('iface_type', '') == 'vlan':
iface_data['inet6']['vlan_raw_device'] = (
re.sub(r'\.\d*', '', iface))
for addrfam in ['inet', 'inet6']:
if iface_type not in ['bridge']:
tmp_ethtool = _parse_ethtool_opts(opts, iface)
if tmp_ethtool:
ethtool = {}
for item in tmp_ethtool:
ethtool[_ETHTOOL_CONFIG_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['ethtool'] = ethtool
# return a list of sorted keys to ensure consistent order
iface_data[addrfam]['ethtool_keys'] = sorted(ethtool)
if iface_type == 'bridge':
bridging = _parse_bridge_opts(opts, iface)
if bridging:
iface_data[addrfam]['bridging'] = bridging
iface_data[addrfam]['bridging_keys'] = sorted(bridging)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'bond':
bonding = _parse_settings_bond(opts, iface)
if bonding:
iface_data[addrfam]['bonding'] = bonding
iface_data[addrfam]['bonding']['slaves'] = opts['slaves']
iface_data[addrfam]['bonding_keys'] = sorted(bonding)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'slave':
adapters[iface]['master'] = opts['master']
opts['proto'] = 'manual'
iface_data[addrfam]['master'] = adapters[iface]['master']
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'vlan':
iface_data[addrfam]['vlan_raw_device'] = re.sub(r'\.\d*', '', iface)
iface_data[addrfam]['addrfam'] = addrfam
elif iface_type == 'pppoe':
tmp_ethtool = _parse_ethtool_pppoe_opts(opts, iface)
if tmp_ethtool:
for item in tmp_ethtool:
adapters[iface]['data'][addrfam][_DEB_CONFIG_PPPOE_OPTS[item]] = tmp_ethtool[item]
iface_data[addrfam]['addrfam'] = addrfam
opts.pop('mode', None)
for opt, val in opts.items():
inet = None
if opt.startswith('ipv4'):
opt = opt[4:]
inet = 'inet'
iface_data['inet']['addrfam'] = 'inet'
elif opt.startswith('ipv6'):
iface_data['inet6']['addrfam'] = 'inet6'
opt = opt[4:]
inet = 'inet6'
elif opt in ['ipaddr', 'address', 'ipaddresses', 'addresses', 'gateway', 'proto']:
iface_data['inet']['addrfam'] = 'inet'
inet = 'inet'
_opt = SALT_ATTR_TO_DEBIAN_ATTR_MAP.get(opt, opt)
_debopt = _opt.replace('-', '_')
for addrfam in ['inet', 'inet6']:
(valid, value, errmsg) = _validate_interface_option(_opt, val, addrfam=addrfam)
if not valid:
continue
if inet is None and _debopt not in iface_data[addrfam]:
iface_data[addrfam][_debopt] = value
elif inet == addrfam:
iface_data[addrfam][_debopt] = value
for opt in ['up_cmds', 'pre_up_cmds', 'post_up_cmds',
'down_cmds', 'pre_down_cmds', 'post_down_cmds']:
if opt in opts:
iface_data['inet'][opt] = opts[opt]
iface_data['inet6'][opt] = opts[opt]
# Remove incomplete/disabled inet blocks
for (addrfam, opt) in [('inet', 'enable_ipv4'), ('inet6', 'enable_ipv6')]:
if opts.get(opt, None) is False:
iface_data.pop(addrfam)
elif iface_data[addrfam].get('addrfam', '') != addrfam:
iface_data.pop(addrfam)
return adapters
def _parse_settings_source(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
adapters = salt.utils.odict.OrderedDict()
adapters[iface] = salt.utils.odict.OrderedDict()
adapters[iface]['type'] = iface_type
adapters[iface]['data'] = salt.utils.odict.OrderedDict()
iface_data = adapters[iface]['data']
iface_data['sources'] = [opts['source']]
return adapters
def _parse_network_settings(opts, current):
'''
Filters given options and outputs valid settings for
the global network settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
current = dict((k.lower(), v) for (k, v) in six.iteritems(current))
result = {}
valid = _CONFIG_TRUE + _CONFIG_FALSE
if 'enabled' not in opts:
try:
opts['networking'] = current['networking']
_log_default_network('networking', current['networking'])
except ValueError:
_raise_error_network('networking', valid)
else:
opts['networking'] = opts['enabled']
if opts['networking'] in valid:
if opts['networking'] in _CONFIG_TRUE:
result['networking'] = 'yes'
elif opts['networking'] in _CONFIG_FALSE:
result['networking'] = 'no'
else:
_raise_error_network('networking', valid)
if 'hostname' not in opts:
try:
opts['hostname'] = current['hostname']
_log_default_network('hostname', current['hostname'])
except ValueError:
_raise_error_network('hostname', ['server1.example.com'])
if opts['hostname']:
result['hostname'] = opts['hostname']
else:
_raise_error_network('hostname', ['server1.example.com'])
if 'search' in opts:
result['search'] = opts['search']
return result
def _parse_routes(iface, opts):
'''
Filters given options and outputs valid settings for
the route settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
result = {}
if 'routes' not in opts:
_raise_error_routes(iface, 'routes', 'List of routes')
for opt in opts:
result[opt] = opts[opt]
return result
def _write_file(iface, data, folder, pattern):
'''
Writes a file to disk
'''
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
return filename
def _write_file_routes(iface, data, folder, pattern):
'''
Writes a file to disk
'''
# ifup / ifdown is executing given folder via run-parts.
# according to run-parts man-page, only filenames with this pattern are
# executed: (^[a-zA-Z0-9_-]+$)
# In order to make the routes file work for vlan interfaces
# (default would have been in example /etc/network/if-up.d/route-bond0.12)
# these dots in the iface name need to be replaced by underscores, so it
# can be executed by run-parts
iface = iface.replace('.', '_')
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
__salt__['file.set_mode'](filename, '0755')
return filename
def _write_file_network(data, filename, create=False):
'''
Writes a file to disk
If file does not exist, only create if create
argument is True
'''
if not os.path.exists(filename) and not create:
msg = '{0} cannot be written. {0} does not exist\
and create is set to False'
msg = msg.format(filename)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(data))
def _read_temp(data):
'''
Return what would be written to disk
'''
tout = StringIO()
tout.write(data)
tout.seek(0)
output = tout.readlines()
tout.close()
return output
def _read_temp_ifaces(iface, data):
'''
Return what would be written to disk for interfaces
'''
try:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': data})
# Return as an array so the difflib works
return [item + '\n' for item in ifcfg.split('\n')]
def _write_file_ifaces(iface, data, **settings):
'''
Writes a file to disk
'''
try:
eth_template = JINJA.get_template('debian_eth.jinja')
source_template = JINJA.get_template('debian_source.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
# Read /etc/network/interfaces into a dict
adapters = _parse_interfaces()
# Apply supplied settings over on-disk settings
adapters[iface] = data
ifcfg = ''
for adapter in adapters:
if 'type' in adapters[adapter] and adapters[adapter]['type'] == 'source':
tmp = source_template.render({'name': adapter, 'data': adapters[adapter]})
else:
tmp = eth_template.render({'name': adapter, 'data': adapters[adapter]})
ifcfg = ifcfg + tmp
if adapter == iface:
saved_ifcfg = tmp
_SEPARATE_FILE = False
if 'filename' in settings:
if not settings['filename'].startswith('/'):
filename = '{0}/{1}'.format(_DEB_NETWORK_DIR, settings['filename'])
else:
filename = settings['filename']
_SEPARATE_FILE = True
else:
if 'filename' in adapters[adapter]['data']:
filename = adapters[adapter]['data']
else:
filename = _DEB_NETWORK_FILE
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.flopen(filename, 'w') as fout:
if _SEPARATE_FILE:
fout.write(salt.utils.stringutils.to_str(saved_ifcfg))
else:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return saved_ifcfg.split('\n')
def _write_file_ppp_ifaces(iface, data):
'''
Writes a file to disk
'''
try:
template = JINJA.get_template('debian_ppp_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_ppp_eth.jinja')
return ''
adapters = _parse_interfaces()
adapters[iface] = data
ifcfg = ''
tmp = template.render({'data': adapters[iface]})
ifcfg = tmp + ifcfg
filename = _DEB_PPP_DIR + '/' + adapters[iface]['data']['inet']['provider']
if not os.path.exists(os.path.dirname(filename)):
msg = '{0} cannot be written.'
msg = msg.format(os.path.dirname(filename))
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.fopen(filename, 'w') as fout:
fout.write(salt.utils.stringutils.to_str(ifcfg))
# Return as an array so the difflib works
return filename
def build_bond(iface, **settings):
'''
Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb
'''
deb_major = __grains__['osrelease'][:1]
opts = _parse_settings_bond(settings, iface)
try:
template = JINJA.get_template('conf.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template conf.jinja')
return ''
data = template.render({'name': iface, 'bonding': opts})
if 'test' in settings and settings['test']:
return _read_temp(data)
_write_file(iface, data, _DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
if deb_major == '5':
for line_type in ('alias', 'options'):
cmd = ['sed', '-i', '-e', r'/^{0}\s{1}.*/d'.format(line_type, iface),
'/etc/modprobe.conf']
__salt__['cmd.run'](cmd, python_shell=False)
__salt__['file.append']('/etc/modprobe.conf', path)
# Load kernel module
__salt__['kmod.load']('bonding')
# install ifenslave-2.6
__salt__['pkg.install']('ifenslave-2.6')
return _read_file(path)
def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'vlan':
settings['vlan'] = 'yes'
__salt__['pkg.install']('vlan')
elif iface_type == 'pppoe':
settings['pppoe'] = 'yes'
if not __salt__['pkg.version']('ppp'):
inst = __salt__['pkg.install']('ppp')
elif iface_type == 'bond':
if 'slaves' not in settings:
msg = 'slaves is a required setting for bond interfaces'
log.error(msg)
raise AttributeError(msg)
elif iface_type == 'bridge':
if 'ports' not in settings:
msg = (
'ports is a required setting for bridge interfaces on Debian '
'or Ubuntu based systems'
)
log.error(msg)
raise AttributeError(msg)
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'pppoe']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
if iface_type in ['source']:
opts = _parse_settings_source(settings, iface_type, enabled, iface)
if 'test' in settings and settings['test']:
return _read_temp_ifaces(iface, opts[iface])
ifcfg = _write_file_ifaces(iface, opts[iface], **settings)
if iface_type == 'pppoe':
_write_file_ppp_ifaces(iface, opts[iface])
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg]
def build_routes(iface, **settings):
'''
Add route scripts for a network interface using up commands.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
'''
opts = _parse_routes(iface, settings)
try:
template = JINJA.get_template('route_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template route_eth.jinja')
return ''
add_routecfg = template.render(route_type='add',
routes=opts['routes'],
iface=iface)
del_routecfg = template.render(route_type='del',
routes=opts['routes'],
iface=iface)
if 'test' in settings and settings['test']:
return _read_temp(add_routecfg + del_routecfg)
filename = _write_file_routes(iface,
add_routecfg,
_DEB_NETWORK_UP_DIR,
'route-{0}')
results = _read_file(filename)
filename = _write_file_routes(iface,
del_routecfg,
_DEB_NETWORK_DOWN_DIR,
'route-{0}')
results += _read_file(filename)
return results
def down(iface, iface_type):
'''
Shutdown a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.down eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought down.
if iface_type not in ['slave', 'source']:
return __salt__['cmd.run'](['ifdown', iface])
return None
def get_bond(iface):
'''
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
'''
path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
return _read_file(path)
def get_interface(iface):
'''
Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
adapters = _parse_interfaces()
if iface in adapters:
try:
if iface == 'source':
template = JINJA.get_template('debian_source.jinja')
else:
template = JINJA.get_template('debian_eth.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template debian_eth.jinja')
return ''
ifcfg = template.render({'name': iface, 'data': adapters[iface]})
# ensure lines in list end with newline, so difflib works
return [item + '\n' for item in ifcfg.split('\n')]
else:
return []
def up(iface, iface_type): # pylint: disable=C0103
'''
Start up a network interface
CLI Example:
.. code-block:: bash
salt '*' ip.up eth0 eth
'''
# Slave devices are controlled by the master.
# Source 'interfaces' aren't brought up.
if iface_type not in ('slave', 'source'):
return __salt__['cmd.run'](['ifup', iface])
return None
def get_network_settings():
'''
Return the contents of the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_network_settings
'''
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) >= 12)
if skip_etc_default_networking:
settings = {}
if __salt__['service.available']('networking'):
if __salt__['service.status']('networking'):
settings['networking'] = "yes"
else:
settings['networking'] = "no"
else:
settings['networking'] = "no"
hostname = _parse_hostname()
domainname = _parse_domainname()
searchdomain = _parse_searchdomain()
settings['hostname'] = hostname
settings['domainname'] = domainname
settings['searchdomain'] = searchdomain
else:
settings = _parse_current_network_settings()
try:
template = JINJA.get_template('display-network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template display-network.jinja')
return ''
network = template.render(settings)
return _read_temp(network)
def get_routes(iface):
'''
Return the routes for the interface
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0
'''
filename = os.path.join(_DEB_NETWORK_UP_DIR, 'route-{0}'.format(iface))
results = _read_file(filename)
filename = os.path.join(_DEB_NETWORK_DOWN_DIR, 'route-{0}'.format(iface))
results += _read_file(filename)
return results
def apply_network_settings(**settings):
'''
Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings
'''
if 'require_reboot' not in settings:
settings['require_reboot'] = False
if 'apply_hostname' not in settings:
settings['apply_hostname'] = False
hostname_res = True
if settings['apply_hostname'] in _CONFIG_TRUE:
if 'hostname' in settings:
hostname_res = __salt__['network.mod_hostname'](settings['hostname'])
else:
log.warning(
'The network state sls is trying to apply hostname '
'changes but no hostname is defined.'
)
hostname_res = False
res = True
if settings['require_reboot'] in _CONFIG_TRUE:
log.warning(
'The network state sls is requiring a reboot of the system to '
'properly apply network configuration.'
)
res = True
else:
stop = __salt__['service.stop']('networking')
time.sleep(2)
res = stop and __salt__['service.start']('networking')
return hostname_res and res
|
saltstack/salt
|
salt/modules/environ.py
|
setval
|
python
|
def setval(key, val, false_unsets=False, permanent=False):
'''
Set a single salt process environment variable. Returns True
on success.
key
The environment key to set. Must be a string.
val
The value to set. Must be a string or False. Refer to the
'false_unsets' parameter for behavior when set to False.
false_unsets
If val is False and false_unsets is True, then the key will be
removed from the salt processes environment dict entirely.
If val is False and false_unsets is not True, then the key's
value will be set to an empty string.
Default: False.
permanent
On Windows minions this will set the environment variable in the
registry so that it is always added as an environment variable when
applications open. If you want to set the variable to HKLM instead of
HKCU just pass in "HKLM" for this parameter. On all other minion types
this will be ignored. Note: This will only take affect on applications
opened after this has been set.
CLI Example:
.. code-block:: bash
salt '*' environ.setval foo bar
salt '*' environ.setval baz val=False false_unsets=True
salt '*' environ.setval baz bar permanent=True
salt '*' environ.setval baz bar permanent=HKLM
'''
is_windows = salt.utils.platform.is_windows()
if is_windows:
permanent_hive = 'HKCU'
permanent_key = 'Environment'
if permanent == 'HKLM':
permanent_hive = 'HKLM'
permanent_key = r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment'
if not isinstance(key, six.string_types):
log.debug('%s: \'key\' argument is not a string type: \'%s\'', __name__, key)
if val is False:
if false_unsets is True:
try:
os.environ.pop(key, None)
if permanent and is_windows:
__utils__['reg.delete_value'](permanent_hive, permanent_key, key)
return None
except Exception as exc:
log.error(
'%s: Exception occurred when unsetting '
'environ key \'%s\': \'%s\'', __name__, key, exc
)
return False
else:
val = ''
if isinstance(val, six.string_types):
try:
os.environ[key] = val
if permanent and is_windows:
__utils__['reg.set_value'](permanent_hive, permanent_key, key, val)
return os.environ[key]
except Exception as exc:
log.error(
'%s: Exception occurred when setting'
'environ key \'%s\': \'%s\'', __name__, key, exc
)
return False
else:
log.debug(
'%s: \'val\' argument for key \'%s\' is not a string '
'or False: \'%s\'', __name__, key, val
)
return False
|
Set a single salt process environment variable. Returns True
on success.
key
The environment key to set. Must be a string.
val
The value to set. Must be a string or False. Refer to the
'false_unsets' parameter for behavior when set to False.
false_unsets
If val is False and false_unsets is True, then the key will be
removed from the salt processes environment dict entirely.
If val is False and false_unsets is not True, then the key's
value will be set to an empty string.
Default: False.
permanent
On Windows minions this will set the environment variable in the
registry so that it is always added as an environment variable when
applications open. If you want to set the variable to HKLM instead of
HKCU just pass in "HKLM" for this parameter. On all other minion types
this will be ignored. Note: This will only take affect on applications
opened after this has been set.
CLI Example:
.. code-block:: bash
salt '*' environ.setval foo bar
salt '*' environ.setval baz val=False false_unsets=True
salt '*' environ.setval baz bar permanent=True
salt '*' environ.setval baz bar permanent=HKLM
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/environ.py#L27-L105
| null |
# -*- coding: utf-8 -*-
'''
Support for getting and setting the environment variables
of the current salt process.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import logging
# Import Salt libs
import salt.utils.platform
# Import 3rd-party libs
from salt.ext import six
log = logging.getLogger(__name__)
def __virtual__():
'''
No dependency checks, and not renaming, just return True
'''
return True
def setenv(environ, false_unsets=False, clear_all=False, update_minion=False, permanent=False):
'''
Set multiple salt process environment variables from a dict.
Returns a dict.
environ
Must be a dict. The top-level keys of the dict are the names
of the environment variables to set. Each key's value must be
a string or False. Refer to the 'false_unsets' parameter for
behavior when a value set to False.
false_unsets
If a key's value is False and false_unsets is True, then the
key will be removed from the salt processes environment dict
entirely. If a key's value is False and false_unsets is not
True, then the key's value will be set to an empty string.
Default: False
clear_all
USE WITH CAUTION! This option can unset environment variables
needed for salt to function properly.
If clear_all is True, then any environment variables not
defined in the environ dict will be deleted.
Default: False
update_minion
If True, apply these environ changes to the main salt-minion
process. If False, the environ changes will only affect the
current salt subprocess.
Default: False
permanent
On Windows minions this will set the environment variable in the
registry so that it is always added as an environment variable when
applications open. If you want to set the variable to HKLM instead of
HKCU just pass in "HKLM" for this parameter. On all other minion types
this will be ignored. Note: This will only take affect on applications
opened after this has been set.
CLI Example:
.. code-block:: bash
salt '*' environ.setenv '{"foo": "bar", "baz": "quux"}'
salt '*' environ.setenv '{"a": "b", "c": False}' false_unsets=True
'''
ret = {}
if not isinstance(environ, dict):
log.debug(
'%s: \'environ\' argument is not a dict: \'%s\'',
__name__, environ
)
return False
if clear_all is True:
# Unset any keys not defined in 'environ' dict supplied by user
to_unset = [key for key in os.environ if key not in environ]
for key in to_unset:
ret[key] = setval(key, False, false_unsets, permanent=permanent)
for key, val in six.iteritems(environ):
if isinstance(val, six.string_types):
ret[key] = setval(key, val, permanent=permanent)
elif val is False:
ret[key] = setval(key, val, false_unsets, permanent=permanent)
else:
log.debug(
'%s: \'val\' argument for key \'%s\' is not a string '
'or False: \'%s\'', __name__, key, val
)
return False
if update_minion is True:
__salt__['event.fire']({'environ': environ,
'false_unsets': false_unsets,
'clear_all': clear_all,
'permanent': permanent
},
'environ_setenv')
return ret
def get(key, default=''):
'''
Get a single salt process environment variable.
key
String used as the key for environment lookup.
default
If the key is not found in the environment, return this value.
Default: ''
CLI Example:
.. code-block:: bash
salt '*' environ.get foo
salt '*' environ.get baz default=False
'''
if not isinstance(key, six.string_types):
log.debug('%s: \'key\' argument is not a string type: \'%s\'', __name__, key)
return False
return os.environ.get(key, default)
def has_value(key, value=None):
'''
Determine whether the key exists in the current salt process
environment dictionary. Optionally compare the current value
of the environment against the supplied value string.
key
Must be a string. Used as key for environment lookup.
value:
Optional. If key exists in the environment, compare the
current value with this value. Return True if they are equal.
CLI Example:
.. code-block:: bash
salt '*' environ.has_value foo
'''
if not isinstance(key, six.string_types):
log.debug('%s: \'key\' argument is not a string type: \'%s\'', __name__, key)
return False
try:
cur_val = os.environ[key]
if value is not None:
if cur_val == value:
return True
else:
return False
except KeyError:
return False
return True
def item(keys, default=''):
'''
Get one or more salt process environment variables.
Returns a dict.
keys
Either a string or a list of strings that will be used as the
keys for environment lookup.
default
If the key is not found in the environment, return this value.
Default: ''
CLI Example:
.. code-block:: bash
salt '*' environ.item foo
salt '*' environ.item '[foo, baz]' default=None
'''
ret = {}
key_list = []
if isinstance(keys, six.string_types):
key_list.append(keys)
elif isinstance(keys, list):
key_list = keys
else:
log.debug(
'%s: \'keys\' argument is not a string or list type: \'%s\'',
__name__, keys
)
for key in key_list:
ret[key] = os.environ.get(key, default)
return ret
def items():
'''
Return a dict of the entire environment set for the salt process
CLI Example:
.. code-block:: bash
salt '*' environ.items
'''
return dict(os.environ)
|
saltstack/salt
|
salt/modules/environ.py
|
setenv
|
python
|
def setenv(environ, false_unsets=False, clear_all=False, update_minion=False, permanent=False):
'''
Set multiple salt process environment variables from a dict.
Returns a dict.
environ
Must be a dict. The top-level keys of the dict are the names
of the environment variables to set. Each key's value must be
a string or False. Refer to the 'false_unsets' parameter for
behavior when a value set to False.
false_unsets
If a key's value is False and false_unsets is True, then the
key will be removed from the salt processes environment dict
entirely. If a key's value is False and false_unsets is not
True, then the key's value will be set to an empty string.
Default: False
clear_all
USE WITH CAUTION! This option can unset environment variables
needed for salt to function properly.
If clear_all is True, then any environment variables not
defined in the environ dict will be deleted.
Default: False
update_minion
If True, apply these environ changes to the main salt-minion
process. If False, the environ changes will only affect the
current salt subprocess.
Default: False
permanent
On Windows minions this will set the environment variable in the
registry so that it is always added as an environment variable when
applications open. If you want to set the variable to HKLM instead of
HKCU just pass in "HKLM" for this parameter. On all other minion types
this will be ignored. Note: This will only take affect on applications
opened after this has been set.
CLI Example:
.. code-block:: bash
salt '*' environ.setenv '{"foo": "bar", "baz": "quux"}'
salt '*' environ.setenv '{"a": "b", "c": False}' false_unsets=True
'''
ret = {}
if not isinstance(environ, dict):
log.debug(
'%s: \'environ\' argument is not a dict: \'%s\'',
__name__, environ
)
return False
if clear_all is True:
# Unset any keys not defined in 'environ' dict supplied by user
to_unset = [key for key in os.environ if key not in environ]
for key in to_unset:
ret[key] = setval(key, False, false_unsets, permanent=permanent)
for key, val in six.iteritems(environ):
if isinstance(val, six.string_types):
ret[key] = setval(key, val, permanent=permanent)
elif val is False:
ret[key] = setval(key, val, false_unsets, permanent=permanent)
else:
log.debug(
'%s: \'val\' argument for key \'%s\' is not a string '
'or False: \'%s\'', __name__, key, val
)
return False
if update_minion is True:
__salt__['event.fire']({'environ': environ,
'false_unsets': false_unsets,
'clear_all': clear_all,
'permanent': permanent
},
'environ_setenv')
return ret
|
Set multiple salt process environment variables from a dict.
Returns a dict.
environ
Must be a dict. The top-level keys of the dict are the names
of the environment variables to set. Each key's value must be
a string or False. Refer to the 'false_unsets' parameter for
behavior when a value set to False.
false_unsets
If a key's value is False and false_unsets is True, then the
key will be removed from the salt processes environment dict
entirely. If a key's value is False and false_unsets is not
True, then the key's value will be set to an empty string.
Default: False
clear_all
USE WITH CAUTION! This option can unset environment variables
needed for salt to function properly.
If clear_all is True, then any environment variables not
defined in the environ dict will be deleted.
Default: False
update_minion
If True, apply these environ changes to the main salt-minion
process. If False, the environ changes will only affect the
current salt subprocess.
Default: False
permanent
On Windows minions this will set the environment variable in the
registry so that it is always added as an environment variable when
applications open. If you want to set the variable to HKLM instead of
HKCU just pass in "HKLM" for this parameter. On all other minion types
this will be ignored. Note: This will only take affect on applications
opened after this has been set.
CLI Example:
.. code-block:: bash
salt '*' environ.setenv '{"foo": "bar", "baz": "quux"}'
salt '*' environ.setenv '{"a": "b", "c": False}' false_unsets=True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/environ.py#L108-L186
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def setval(key, val, false_unsets=False, permanent=False):\n '''\n Set a single salt process environment variable. Returns True\n on success.\n\n key\n The environment key to set. Must be a string.\n\n val\n The value to set. Must be a string or False. Refer to the\n 'false_unsets' parameter for behavior when set to False.\n\n false_unsets\n If val is False and false_unsets is True, then the key will be\n removed from the salt processes environment dict entirely.\n If val is False and false_unsets is not True, then the key's\n value will be set to an empty string.\n Default: False.\n\n permanent\n On Windows minions this will set the environment variable in the\n registry so that it is always added as an environment variable when\n applications open. If you want to set the variable to HKLM instead of\n HKCU just pass in \"HKLM\" for this parameter. On all other minion types\n this will be ignored. Note: This will only take affect on applications\n opened after this has been set.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' environ.setval foo bar\n salt '*' environ.setval baz val=False false_unsets=True\n salt '*' environ.setval baz bar permanent=True\n salt '*' environ.setval baz bar permanent=HKLM\n '''\n is_windows = salt.utils.platform.is_windows()\n if is_windows:\n permanent_hive = 'HKCU'\n permanent_key = 'Environment'\n if permanent == 'HKLM':\n permanent_hive = 'HKLM'\n permanent_key = r'SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment'\n\n if not isinstance(key, six.string_types):\n log.debug('%s: \\'key\\' argument is not a string type: \\'%s\\'', __name__, key)\n if val is False:\n if false_unsets is True:\n try:\n os.environ.pop(key, None)\n if permanent and is_windows:\n __utils__['reg.delete_value'](permanent_hive, permanent_key, key)\n return None\n except Exception as exc:\n log.error(\n '%s: Exception occurred when unsetting '\n 'environ key \\'%s\\': \\'%s\\'', __name__, key, exc\n )\n return False\n else:\n val = ''\n if isinstance(val, six.string_types):\n try:\n os.environ[key] = val\n if permanent and is_windows:\n __utils__['reg.set_value'](permanent_hive, permanent_key, key, val)\n return os.environ[key]\n except Exception as exc:\n log.error(\n '%s: Exception occurred when setting'\n 'environ key \\'%s\\': \\'%s\\'', __name__, key, exc\n )\n return False\n else:\n log.debug(\n '%s: \\'val\\' argument for key \\'%s\\' is not a string '\n 'or False: \\'%s\\'', __name__, key, val\n )\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Support for getting and setting the environment variables
of the current salt process.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import logging
# Import Salt libs
import salt.utils.platform
# Import 3rd-party libs
from salt.ext import six
log = logging.getLogger(__name__)
def __virtual__():
'''
No dependency checks, and not renaming, just return True
'''
return True
def setval(key, val, false_unsets=False, permanent=False):
'''
Set a single salt process environment variable. Returns True
on success.
key
The environment key to set. Must be a string.
val
The value to set. Must be a string or False. Refer to the
'false_unsets' parameter for behavior when set to False.
false_unsets
If val is False and false_unsets is True, then the key will be
removed from the salt processes environment dict entirely.
If val is False and false_unsets is not True, then the key's
value will be set to an empty string.
Default: False.
permanent
On Windows minions this will set the environment variable in the
registry so that it is always added as an environment variable when
applications open. If you want to set the variable to HKLM instead of
HKCU just pass in "HKLM" for this parameter. On all other minion types
this will be ignored. Note: This will only take affect on applications
opened after this has been set.
CLI Example:
.. code-block:: bash
salt '*' environ.setval foo bar
salt '*' environ.setval baz val=False false_unsets=True
salt '*' environ.setval baz bar permanent=True
salt '*' environ.setval baz bar permanent=HKLM
'''
is_windows = salt.utils.platform.is_windows()
if is_windows:
permanent_hive = 'HKCU'
permanent_key = 'Environment'
if permanent == 'HKLM':
permanent_hive = 'HKLM'
permanent_key = r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment'
if not isinstance(key, six.string_types):
log.debug('%s: \'key\' argument is not a string type: \'%s\'', __name__, key)
if val is False:
if false_unsets is True:
try:
os.environ.pop(key, None)
if permanent and is_windows:
__utils__['reg.delete_value'](permanent_hive, permanent_key, key)
return None
except Exception as exc:
log.error(
'%s: Exception occurred when unsetting '
'environ key \'%s\': \'%s\'', __name__, key, exc
)
return False
else:
val = ''
if isinstance(val, six.string_types):
try:
os.environ[key] = val
if permanent and is_windows:
__utils__['reg.set_value'](permanent_hive, permanent_key, key, val)
return os.environ[key]
except Exception as exc:
log.error(
'%s: Exception occurred when setting'
'environ key \'%s\': \'%s\'', __name__, key, exc
)
return False
else:
log.debug(
'%s: \'val\' argument for key \'%s\' is not a string '
'or False: \'%s\'', __name__, key, val
)
return False
def get(key, default=''):
'''
Get a single salt process environment variable.
key
String used as the key for environment lookup.
default
If the key is not found in the environment, return this value.
Default: ''
CLI Example:
.. code-block:: bash
salt '*' environ.get foo
salt '*' environ.get baz default=False
'''
if not isinstance(key, six.string_types):
log.debug('%s: \'key\' argument is not a string type: \'%s\'', __name__, key)
return False
return os.environ.get(key, default)
def has_value(key, value=None):
'''
Determine whether the key exists in the current salt process
environment dictionary. Optionally compare the current value
of the environment against the supplied value string.
key
Must be a string. Used as key for environment lookup.
value:
Optional. If key exists in the environment, compare the
current value with this value. Return True if they are equal.
CLI Example:
.. code-block:: bash
salt '*' environ.has_value foo
'''
if not isinstance(key, six.string_types):
log.debug('%s: \'key\' argument is not a string type: \'%s\'', __name__, key)
return False
try:
cur_val = os.environ[key]
if value is not None:
if cur_val == value:
return True
else:
return False
except KeyError:
return False
return True
def item(keys, default=''):
'''
Get one or more salt process environment variables.
Returns a dict.
keys
Either a string or a list of strings that will be used as the
keys for environment lookup.
default
If the key is not found in the environment, return this value.
Default: ''
CLI Example:
.. code-block:: bash
salt '*' environ.item foo
salt '*' environ.item '[foo, baz]' default=None
'''
ret = {}
key_list = []
if isinstance(keys, six.string_types):
key_list.append(keys)
elif isinstance(keys, list):
key_list = keys
else:
log.debug(
'%s: \'keys\' argument is not a string or list type: \'%s\'',
__name__, keys
)
for key in key_list:
ret[key] = os.environ.get(key, default)
return ret
def items():
'''
Return a dict of the entire environment set for the salt process
CLI Example:
.. code-block:: bash
salt '*' environ.items
'''
return dict(os.environ)
|
saltstack/salt
|
salt/modules/environ.py
|
get
|
python
|
def get(key, default=''):
'''
Get a single salt process environment variable.
key
String used as the key for environment lookup.
default
If the key is not found in the environment, return this value.
Default: ''
CLI Example:
.. code-block:: bash
salt '*' environ.get foo
salt '*' environ.get baz default=False
'''
if not isinstance(key, six.string_types):
log.debug('%s: \'key\' argument is not a string type: \'%s\'', __name__, key)
return False
return os.environ.get(key, default)
|
Get a single salt process environment variable.
key
String used as the key for environment lookup.
default
If the key is not found in the environment, return this value.
Default: ''
CLI Example:
.. code-block:: bash
salt '*' environ.get foo
salt '*' environ.get baz default=False
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/environ.py#L189-L211
| null |
# -*- coding: utf-8 -*-
'''
Support for getting and setting the environment variables
of the current salt process.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import logging
# Import Salt libs
import salt.utils.platform
# Import 3rd-party libs
from salt.ext import six
log = logging.getLogger(__name__)
def __virtual__():
'''
No dependency checks, and not renaming, just return True
'''
return True
def setval(key, val, false_unsets=False, permanent=False):
'''
Set a single salt process environment variable. Returns True
on success.
key
The environment key to set. Must be a string.
val
The value to set. Must be a string or False. Refer to the
'false_unsets' parameter for behavior when set to False.
false_unsets
If val is False and false_unsets is True, then the key will be
removed from the salt processes environment dict entirely.
If val is False and false_unsets is not True, then the key's
value will be set to an empty string.
Default: False.
permanent
On Windows minions this will set the environment variable in the
registry so that it is always added as an environment variable when
applications open. If you want to set the variable to HKLM instead of
HKCU just pass in "HKLM" for this parameter. On all other minion types
this will be ignored. Note: This will only take affect on applications
opened after this has been set.
CLI Example:
.. code-block:: bash
salt '*' environ.setval foo bar
salt '*' environ.setval baz val=False false_unsets=True
salt '*' environ.setval baz bar permanent=True
salt '*' environ.setval baz bar permanent=HKLM
'''
is_windows = salt.utils.platform.is_windows()
if is_windows:
permanent_hive = 'HKCU'
permanent_key = 'Environment'
if permanent == 'HKLM':
permanent_hive = 'HKLM'
permanent_key = r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment'
if not isinstance(key, six.string_types):
log.debug('%s: \'key\' argument is not a string type: \'%s\'', __name__, key)
if val is False:
if false_unsets is True:
try:
os.environ.pop(key, None)
if permanent and is_windows:
__utils__['reg.delete_value'](permanent_hive, permanent_key, key)
return None
except Exception as exc:
log.error(
'%s: Exception occurred when unsetting '
'environ key \'%s\': \'%s\'', __name__, key, exc
)
return False
else:
val = ''
if isinstance(val, six.string_types):
try:
os.environ[key] = val
if permanent and is_windows:
__utils__['reg.set_value'](permanent_hive, permanent_key, key, val)
return os.environ[key]
except Exception as exc:
log.error(
'%s: Exception occurred when setting'
'environ key \'%s\': \'%s\'', __name__, key, exc
)
return False
else:
log.debug(
'%s: \'val\' argument for key \'%s\' is not a string '
'or False: \'%s\'', __name__, key, val
)
return False
def setenv(environ, false_unsets=False, clear_all=False, update_minion=False, permanent=False):
'''
Set multiple salt process environment variables from a dict.
Returns a dict.
environ
Must be a dict. The top-level keys of the dict are the names
of the environment variables to set. Each key's value must be
a string or False. Refer to the 'false_unsets' parameter for
behavior when a value set to False.
false_unsets
If a key's value is False and false_unsets is True, then the
key will be removed from the salt processes environment dict
entirely. If a key's value is False and false_unsets is not
True, then the key's value will be set to an empty string.
Default: False
clear_all
USE WITH CAUTION! This option can unset environment variables
needed for salt to function properly.
If clear_all is True, then any environment variables not
defined in the environ dict will be deleted.
Default: False
update_minion
If True, apply these environ changes to the main salt-minion
process. If False, the environ changes will only affect the
current salt subprocess.
Default: False
permanent
On Windows minions this will set the environment variable in the
registry so that it is always added as an environment variable when
applications open. If you want to set the variable to HKLM instead of
HKCU just pass in "HKLM" for this parameter. On all other minion types
this will be ignored. Note: This will only take affect on applications
opened after this has been set.
CLI Example:
.. code-block:: bash
salt '*' environ.setenv '{"foo": "bar", "baz": "quux"}'
salt '*' environ.setenv '{"a": "b", "c": False}' false_unsets=True
'''
ret = {}
if not isinstance(environ, dict):
log.debug(
'%s: \'environ\' argument is not a dict: \'%s\'',
__name__, environ
)
return False
if clear_all is True:
# Unset any keys not defined in 'environ' dict supplied by user
to_unset = [key for key in os.environ if key not in environ]
for key in to_unset:
ret[key] = setval(key, False, false_unsets, permanent=permanent)
for key, val in six.iteritems(environ):
if isinstance(val, six.string_types):
ret[key] = setval(key, val, permanent=permanent)
elif val is False:
ret[key] = setval(key, val, false_unsets, permanent=permanent)
else:
log.debug(
'%s: \'val\' argument for key \'%s\' is not a string '
'or False: \'%s\'', __name__, key, val
)
return False
if update_minion is True:
__salt__['event.fire']({'environ': environ,
'false_unsets': false_unsets,
'clear_all': clear_all,
'permanent': permanent
},
'environ_setenv')
return ret
def has_value(key, value=None):
'''
Determine whether the key exists in the current salt process
environment dictionary. Optionally compare the current value
of the environment against the supplied value string.
key
Must be a string. Used as key for environment lookup.
value:
Optional. If key exists in the environment, compare the
current value with this value. Return True if they are equal.
CLI Example:
.. code-block:: bash
salt '*' environ.has_value foo
'''
if not isinstance(key, six.string_types):
log.debug('%s: \'key\' argument is not a string type: \'%s\'', __name__, key)
return False
try:
cur_val = os.environ[key]
if value is not None:
if cur_val == value:
return True
else:
return False
except KeyError:
return False
return True
def item(keys, default=''):
'''
Get one or more salt process environment variables.
Returns a dict.
keys
Either a string or a list of strings that will be used as the
keys for environment lookup.
default
If the key is not found in the environment, return this value.
Default: ''
CLI Example:
.. code-block:: bash
salt '*' environ.item foo
salt '*' environ.item '[foo, baz]' default=None
'''
ret = {}
key_list = []
if isinstance(keys, six.string_types):
key_list.append(keys)
elif isinstance(keys, list):
key_list = keys
else:
log.debug(
'%s: \'keys\' argument is not a string or list type: \'%s\'',
__name__, keys
)
for key in key_list:
ret[key] = os.environ.get(key, default)
return ret
def items():
'''
Return a dict of the entire environment set for the salt process
CLI Example:
.. code-block:: bash
salt '*' environ.items
'''
return dict(os.environ)
|
saltstack/salt
|
salt/modules/environ.py
|
has_value
|
python
|
def has_value(key, value=None):
'''
Determine whether the key exists in the current salt process
environment dictionary. Optionally compare the current value
of the environment against the supplied value string.
key
Must be a string. Used as key for environment lookup.
value:
Optional. If key exists in the environment, compare the
current value with this value. Return True if they are equal.
CLI Example:
.. code-block:: bash
salt '*' environ.has_value foo
'''
if not isinstance(key, six.string_types):
log.debug('%s: \'key\' argument is not a string type: \'%s\'', __name__, key)
return False
try:
cur_val = os.environ[key]
if value is not None:
if cur_val == value:
return True
else:
return False
except KeyError:
return False
return True
|
Determine whether the key exists in the current salt process
environment dictionary. Optionally compare the current value
of the environment against the supplied value string.
key
Must be a string. Used as key for environment lookup.
value:
Optional. If key exists in the environment, compare the
current value with this value. Return True if they are equal.
CLI Example:
.. code-block:: bash
salt '*' environ.has_value foo
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/environ.py#L214-L245
| null |
# -*- coding: utf-8 -*-
'''
Support for getting and setting the environment variables
of the current salt process.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import logging
# Import Salt libs
import salt.utils.platform
# Import 3rd-party libs
from salt.ext import six
log = logging.getLogger(__name__)
def __virtual__():
'''
No dependency checks, and not renaming, just return True
'''
return True
def setval(key, val, false_unsets=False, permanent=False):
'''
Set a single salt process environment variable. Returns True
on success.
key
The environment key to set. Must be a string.
val
The value to set. Must be a string or False. Refer to the
'false_unsets' parameter for behavior when set to False.
false_unsets
If val is False and false_unsets is True, then the key will be
removed from the salt processes environment dict entirely.
If val is False and false_unsets is not True, then the key's
value will be set to an empty string.
Default: False.
permanent
On Windows minions this will set the environment variable in the
registry so that it is always added as an environment variable when
applications open. If you want to set the variable to HKLM instead of
HKCU just pass in "HKLM" for this parameter. On all other minion types
this will be ignored. Note: This will only take affect on applications
opened after this has been set.
CLI Example:
.. code-block:: bash
salt '*' environ.setval foo bar
salt '*' environ.setval baz val=False false_unsets=True
salt '*' environ.setval baz bar permanent=True
salt '*' environ.setval baz bar permanent=HKLM
'''
is_windows = salt.utils.platform.is_windows()
if is_windows:
permanent_hive = 'HKCU'
permanent_key = 'Environment'
if permanent == 'HKLM':
permanent_hive = 'HKLM'
permanent_key = r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment'
if not isinstance(key, six.string_types):
log.debug('%s: \'key\' argument is not a string type: \'%s\'', __name__, key)
if val is False:
if false_unsets is True:
try:
os.environ.pop(key, None)
if permanent and is_windows:
__utils__['reg.delete_value'](permanent_hive, permanent_key, key)
return None
except Exception as exc:
log.error(
'%s: Exception occurred when unsetting '
'environ key \'%s\': \'%s\'', __name__, key, exc
)
return False
else:
val = ''
if isinstance(val, six.string_types):
try:
os.environ[key] = val
if permanent and is_windows:
__utils__['reg.set_value'](permanent_hive, permanent_key, key, val)
return os.environ[key]
except Exception as exc:
log.error(
'%s: Exception occurred when setting'
'environ key \'%s\': \'%s\'', __name__, key, exc
)
return False
else:
log.debug(
'%s: \'val\' argument for key \'%s\' is not a string '
'or False: \'%s\'', __name__, key, val
)
return False
def setenv(environ, false_unsets=False, clear_all=False, update_minion=False, permanent=False):
'''
Set multiple salt process environment variables from a dict.
Returns a dict.
environ
Must be a dict. The top-level keys of the dict are the names
of the environment variables to set. Each key's value must be
a string or False. Refer to the 'false_unsets' parameter for
behavior when a value set to False.
false_unsets
If a key's value is False and false_unsets is True, then the
key will be removed from the salt processes environment dict
entirely. If a key's value is False and false_unsets is not
True, then the key's value will be set to an empty string.
Default: False
clear_all
USE WITH CAUTION! This option can unset environment variables
needed for salt to function properly.
If clear_all is True, then any environment variables not
defined in the environ dict will be deleted.
Default: False
update_minion
If True, apply these environ changes to the main salt-minion
process. If False, the environ changes will only affect the
current salt subprocess.
Default: False
permanent
On Windows minions this will set the environment variable in the
registry so that it is always added as an environment variable when
applications open. If you want to set the variable to HKLM instead of
HKCU just pass in "HKLM" for this parameter. On all other minion types
this will be ignored. Note: This will only take affect on applications
opened after this has been set.
CLI Example:
.. code-block:: bash
salt '*' environ.setenv '{"foo": "bar", "baz": "quux"}'
salt '*' environ.setenv '{"a": "b", "c": False}' false_unsets=True
'''
ret = {}
if not isinstance(environ, dict):
log.debug(
'%s: \'environ\' argument is not a dict: \'%s\'',
__name__, environ
)
return False
if clear_all is True:
# Unset any keys not defined in 'environ' dict supplied by user
to_unset = [key for key in os.environ if key not in environ]
for key in to_unset:
ret[key] = setval(key, False, false_unsets, permanent=permanent)
for key, val in six.iteritems(environ):
if isinstance(val, six.string_types):
ret[key] = setval(key, val, permanent=permanent)
elif val is False:
ret[key] = setval(key, val, false_unsets, permanent=permanent)
else:
log.debug(
'%s: \'val\' argument for key \'%s\' is not a string '
'or False: \'%s\'', __name__, key, val
)
return False
if update_minion is True:
__salt__['event.fire']({'environ': environ,
'false_unsets': false_unsets,
'clear_all': clear_all,
'permanent': permanent
},
'environ_setenv')
return ret
def get(key, default=''):
'''
Get a single salt process environment variable.
key
String used as the key for environment lookup.
default
If the key is not found in the environment, return this value.
Default: ''
CLI Example:
.. code-block:: bash
salt '*' environ.get foo
salt '*' environ.get baz default=False
'''
if not isinstance(key, six.string_types):
log.debug('%s: \'key\' argument is not a string type: \'%s\'', __name__, key)
return False
return os.environ.get(key, default)
def item(keys, default=''):
'''
Get one or more salt process environment variables.
Returns a dict.
keys
Either a string or a list of strings that will be used as the
keys for environment lookup.
default
If the key is not found in the environment, return this value.
Default: ''
CLI Example:
.. code-block:: bash
salt '*' environ.item foo
salt '*' environ.item '[foo, baz]' default=None
'''
ret = {}
key_list = []
if isinstance(keys, six.string_types):
key_list.append(keys)
elif isinstance(keys, list):
key_list = keys
else:
log.debug(
'%s: \'keys\' argument is not a string or list type: \'%s\'',
__name__, keys
)
for key in key_list:
ret[key] = os.environ.get(key, default)
return ret
def items():
'''
Return a dict of the entire environment set for the salt process
CLI Example:
.. code-block:: bash
salt '*' environ.items
'''
return dict(os.environ)
|
saltstack/salt
|
salt/modules/environ.py
|
item
|
python
|
def item(keys, default=''):
'''
Get one or more salt process environment variables.
Returns a dict.
keys
Either a string or a list of strings that will be used as the
keys for environment lookup.
default
If the key is not found in the environment, return this value.
Default: ''
CLI Example:
.. code-block:: bash
salt '*' environ.item foo
salt '*' environ.item '[foo, baz]' default=None
'''
ret = {}
key_list = []
if isinstance(keys, six.string_types):
key_list.append(keys)
elif isinstance(keys, list):
key_list = keys
else:
log.debug(
'%s: \'keys\' argument is not a string or list type: \'%s\'',
__name__, keys
)
for key in key_list:
ret[key] = os.environ.get(key, default)
return ret
|
Get one or more salt process environment variables.
Returns a dict.
keys
Either a string or a list of strings that will be used as the
keys for environment lookup.
default
If the key is not found in the environment, return this value.
Default: ''
CLI Example:
.. code-block:: bash
salt '*' environ.item foo
salt '*' environ.item '[foo, baz]' default=None
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/environ.py#L248-L281
| null |
# -*- coding: utf-8 -*-
'''
Support for getting and setting the environment variables
of the current salt process.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import logging
# Import Salt libs
import salt.utils.platform
# Import 3rd-party libs
from salt.ext import six
log = logging.getLogger(__name__)
def __virtual__():
'''
No dependency checks, and not renaming, just return True
'''
return True
def setval(key, val, false_unsets=False, permanent=False):
'''
Set a single salt process environment variable. Returns True
on success.
key
The environment key to set. Must be a string.
val
The value to set. Must be a string or False. Refer to the
'false_unsets' parameter for behavior when set to False.
false_unsets
If val is False and false_unsets is True, then the key will be
removed from the salt processes environment dict entirely.
If val is False and false_unsets is not True, then the key's
value will be set to an empty string.
Default: False.
permanent
On Windows minions this will set the environment variable in the
registry so that it is always added as an environment variable when
applications open. If you want to set the variable to HKLM instead of
HKCU just pass in "HKLM" for this parameter. On all other minion types
this will be ignored. Note: This will only take affect on applications
opened after this has been set.
CLI Example:
.. code-block:: bash
salt '*' environ.setval foo bar
salt '*' environ.setval baz val=False false_unsets=True
salt '*' environ.setval baz bar permanent=True
salt '*' environ.setval baz bar permanent=HKLM
'''
is_windows = salt.utils.platform.is_windows()
if is_windows:
permanent_hive = 'HKCU'
permanent_key = 'Environment'
if permanent == 'HKLM':
permanent_hive = 'HKLM'
permanent_key = r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment'
if not isinstance(key, six.string_types):
log.debug('%s: \'key\' argument is not a string type: \'%s\'', __name__, key)
if val is False:
if false_unsets is True:
try:
os.environ.pop(key, None)
if permanent and is_windows:
__utils__['reg.delete_value'](permanent_hive, permanent_key, key)
return None
except Exception as exc:
log.error(
'%s: Exception occurred when unsetting '
'environ key \'%s\': \'%s\'', __name__, key, exc
)
return False
else:
val = ''
if isinstance(val, six.string_types):
try:
os.environ[key] = val
if permanent and is_windows:
__utils__['reg.set_value'](permanent_hive, permanent_key, key, val)
return os.environ[key]
except Exception as exc:
log.error(
'%s: Exception occurred when setting'
'environ key \'%s\': \'%s\'', __name__, key, exc
)
return False
else:
log.debug(
'%s: \'val\' argument for key \'%s\' is not a string '
'or False: \'%s\'', __name__, key, val
)
return False
def setenv(environ, false_unsets=False, clear_all=False, update_minion=False, permanent=False):
'''
Set multiple salt process environment variables from a dict.
Returns a dict.
environ
Must be a dict. The top-level keys of the dict are the names
of the environment variables to set. Each key's value must be
a string or False. Refer to the 'false_unsets' parameter for
behavior when a value set to False.
false_unsets
If a key's value is False and false_unsets is True, then the
key will be removed from the salt processes environment dict
entirely. If a key's value is False and false_unsets is not
True, then the key's value will be set to an empty string.
Default: False
clear_all
USE WITH CAUTION! This option can unset environment variables
needed for salt to function properly.
If clear_all is True, then any environment variables not
defined in the environ dict will be deleted.
Default: False
update_minion
If True, apply these environ changes to the main salt-minion
process. If False, the environ changes will only affect the
current salt subprocess.
Default: False
permanent
On Windows minions this will set the environment variable in the
registry so that it is always added as an environment variable when
applications open. If you want to set the variable to HKLM instead of
HKCU just pass in "HKLM" for this parameter. On all other minion types
this will be ignored. Note: This will only take affect on applications
opened after this has been set.
CLI Example:
.. code-block:: bash
salt '*' environ.setenv '{"foo": "bar", "baz": "quux"}'
salt '*' environ.setenv '{"a": "b", "c": False}' false_unsets=True
'''
ret = {}
if not isinstance(environ, dict):
log.debug(
'%s: \'environ\' argument is not a dict: \'%s\'',
__name__, environ
)
return False
if clear_all is True:
# Unset any keys not defined in 'environ' dict supplied by user
to_unset = [key for key in os.environ if key not in environ]
for key in to_unset:
ret[key] = setval(key, False, false_unsets, permanent=permanent)
for key, val in six.iteritems(environ):
if isinstance(val, six.string_types):
ret[key] = setval(key, val, permanent=permanent)
elif val is False:
ret[key] = setval(key, val, false_unsets, permanent=permanent)
else:
log.debug(
'%s: \'val\' argument for key \'%s\' is not a string '
'or False: \'%s\'', __name__, key, val
)
return False
if update_minion is True:
__salt__['event.fire']({'environ': environ,
'false_unsets': false_unsets,
'clear_all': clear_all,
'permanent': permanent
},
'environ_setenv')
return ret
def get(key, default=''):
'''
Get a single salt process environment variable.
key
String used as the key for environment lookup.
default
If the key is not found in the environment, return this value.
Default: ''
CLI Example:
.. code-block:: bash
salt '*' environ.get foo
salt '*' environ.get baz default=False
'''
if not isinstance(key, six.string_types):
log.debug('%s: \'key\' argument is not a string type: \'%s\'', __name__, key)
return False
return os.environ.get(key, default)
def has_value(key, value=None):
'''
Determine whether the key exists in the current salt process
environment dictionary. Optionally compare the current value
of the environment against the supplied value string.
key
Must be a string. Used as key for environment lookup.
value:
Optional. If key exists in the environment, compare the
current value with this value. Return True if they are equal.
CLI Example:
.. code-block:: bash
salt '*' environ.has_value foo
'''
if not isinstance(key, six.string_types):
log.debug('%s: \'key\' argument is not a string type: \'%s\'', __name__, key)
return False
try:
cur_val = os.environ[key]
if value is not None:
if cur_val == value:
return True
else:
return False
except KeyError:
return False
return True
def items():
'''
Return a dict of the entire environment set for the salt process
CLI Example:
.. code-block:: bash
salt '*' environ.items
'''
return dict(os.environ)
|
saltstack/salt
|
salt/pillar/svn_pillar.py
|
_extract_key_val
|
python
|
def _extract_key_val(kv, delimiter='='):
'''Extract key and value from key=val string.
Example:
>>> _extract_key_val('foo=bar')
('foo', 'bar')
'''
pieces = kv.split(delimiter)
key = pieces[0]
val = delimiter.join(pieces[1:])
return key, val
|
Extract key and value from key=val string.
Example:
>>> _extract_key_val('foo=bar')
('foo', 'bar')
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/svn_pillar.py#L148-L158
| null |
# -*- coding: utf-8 -*-
'''
Clone a remote SVN repository and use the filesystem as a Pillar source
This external Pillar source can be configured in the master config file like
so:
.. code-block:: yaml
ext_pillar:
- svn: trunk svn://svnserver/repo root=subdirectory
The `root=` parameter is optional and used to set the subdirectory from where
to look for Pillar files (such as ``top.sls``).
.. versionchanged:: 2014.7.0
The optional ``root`` parameter will be added.
Note that this is not the same thing as configuring pillar data using the
:conf_master:`pillar_roots` parameter. The branch referenced in the
:conf_master:`ext_pillar` entry above (``master``), would evaluate to the
``base`` environment, so this branch needs to contain a ``top.sls`` with a
``base`` section in it, like this:
.. code-block:: yaml
base:
'*':
- foo
To use other environments from the same SVN repo as svn_pillar sources, just
add additional lines, like so:
.. code-block:: yaml
ext_pillar:
- svn: trunk svn://svnserver/repo
- svn: dev svn://svnserver/repo
In this case, the ``dev`` branch would need its own ``top.sls`` with a ``dev``
section in it, like this:
.. code-block:: yaml
dev:
'*':
- bar
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
from copy import deepcopy
import logging
import os
import hashlib
# Import third party libs
HAS_SVN = False
try:
import pysvn
HAS_SVN = True
CLIENT = pysvn.Client()
except ImportError:
pass
# Import salt libs
from salt.pillar import Pillar
# Set up logging
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'svn'
def __virtual__():
ext_pillar_sources = [x for x in __opts__.get('ext_pillar', [])]
if not any(['svn' in x for x in ext_pillar_sources]):
return False
if not HAS_SVN:
log.error('SVN-based ext_pillar is enabled in configuration but '
'could not be loaded, is pysvn installed?')
return False
return __virtualname__
class SvnPillar(object):
'''
Deal with the remote SVN repository for Pillar
'''
def __init__(self, branch, repo_location, root, opts):
'''
Try to initialize the SVN repo object
'''
repo_hash = hashlib.md5(repo_location).hexdigest()
repo_dir = os.path.join(opts['cachedir'], 'pillar_svnfs', repo_hash)
self.branch = branch
self.root = root
self.repo_dir = repo_dir
self.repo_location = repo_location
if not os.path.isdir(repo_dir):
os.makedirs(repo_dir)
log.debug('Checking out fileserver for svn_pillar module')
try:
CLIENT.checkout(repo_location, repo_dir)
except pysvn.ClientError:
log.error(
'Failed to initialize svn_pillar %s %s',
repo_location, repo_dir
)
def update(self):
try:
log.debug('Updating fileserver for svn_pillar module')
CLIENT.update(self.repo_dir)
except pysvn.ClientError as exc:
log.error(
'Unable to fetch the latest changes from remote %s: %s',
self.repo_location, exc
)
def pillar_dir(self):
'''
Returns the directory of the pillars (repo cache + branch + root)
'''
repo_dir = self.repo_dir
root = self.root
branch = self.branch
if branch == 'trunk' or branch == 'base':
working_dir = os.path.join(repo_dir, 'trunk', root)
if not os.path.isdir(working_dir):
log.error('Could not find %s/trunk/%s', self.repo_location, root)
else:
return os.path.normpath(working_dir)
working_dir = os.path.join(repo_dir, 'branches', branch, root)
if os.path.isdir(working_dir):
return os.path.normpath(working_dir)
working_dir = os.path.join(working_dir, 'tags', branch, root)
if os.path.isdir(working_dir):
return os.path.normpath(working_dir)
log.error('Could not find %s/branches/%s/%s', self.repo_location, branch, root)
return repo_dir
def ext_pillar(minion_id,
pillar, # pylint: disable=W0613
repo_string):
'''
Execute a command and read the output as YAML
'''
# split the branch, repo name and optional extra (key=val) parameters.
options = repo_string.strip().split()
branch = options[0]
repo_location = options[1]
root = ''
for extraopt in options[2:]:
# Support multiple key=val attributes as custom parameters.
DELIM = '='
if DELIM not in extraopt:
log.error('Incorrectly formatted extra parameter. '
'Missing \'%s\': %s', DELIM, extraopt)
key, val = _extract_key_val(extraopt, DELIM)
if key == 'root':
root = val
else:
log.warning('Unrecognized extra parameter: %s', key)
svnpil = SvnPillar(branch, repo_location, root, __opts__)
# environment is "different" from the branch
branch = (branch == 'trunk' and 'base' or branch)
pillar_dir = svnpil.pillar_dir()
log.debug("[pillar_roots][%s] = %s", branch, pillar_dir)
# Don't recurse forever-- the Pillar object will re-call the ext_pillar
# function
if __opts__['pillar_roots'].get(branch, []) == [pillar_dir]:
return {}
svnpil.update()
opts = deepcopy(__opts__)
opts['pillar_roots'][branch] = [pillar_dir]
pil = Pillar(opts, __grains__, minion_id, branch)
return pil.compile_pillar(ext=False)
|
saltstack/salt
|
salt/pillar/svn_pillar.py
|
ext_pillar
|
python
|
def ext_pillar(minion_id,
pillar, # pylint: disable=W0613
repo_string):
'''
Execute a command and read the output as YAML
'''
# split the branch, repo name and optional extra (key=val) parameters.
options = repo_string.strip().split()
branch = options[0]
repo_location = options[1]
root = ''
for extraopt in options[2:]:
# Support multiple key=val attributes as custom parameters.
DELIM = '='
if DELIM not in extraopt:
log.error('Incorrectly formatted extra parameter. '
'Missing \'%s\': %s', DELIM, extraopt)
key, val = _extract_key_val(extraopt, DELIM)
if key == 'root':
root = val
else:
log.warning('Unrecognized extra parameter: %s', key)
svnpil = SvnPillar(branch, repo_location, root, __opts__)
# environment is "different" from the branch
branch = (branch == 'trunk' and 'base' or branch)
pillar_dir = svnpil.pillar_dir()
log.debug("[pillar_roots][%s] = %s", branch, pillar_dir)
# Don't recurse forever-- the Pillar object will re-call the ext_pillar
# function
if __opts__['pillar_roots'].get(branch, []) == [pillar_dir]:
return {}
svnpil.update()
opts = deepcopy(__opts__)
opts['pillar_roots'][branch] = [pillar_dir]
pil = Pillar(opts, __grains__, minion_id, branch)
return pil.compile_pillar(ext=False)
|
Execute a command and read the output as YAML
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/svn_pillar.py#L161-L201
|
[
"def _extract_key_val(kv, delimiter='='):\n '''Extract key and value from key=val string.\n\n Example:\n >>> _extract_key_val('foo=bar')\n ('foo', 'bar')\n '''\n pieces = kv.split(delimiter)\n key = pieces[0]\n val = delimiter.join(pieces[1:])\n return key, val\n",
"def compile_pillar(self, ext=True):\n '''\n Render the pillar data and return\n '''\n top, top_errors = self.get_top()\n if ext:\n if self.opts.get('ext_pillar_first', False):\n self.opts['pillar'], errors = self.ext_pillar(self.pillar_override)\n self.rend = salt.loader.render(self.opts, self.functions)\n matches = self.top_matches(top)\n pillar, errors = self.render_pillar(matches, errors=errors)\n pillar = merge(\n self.opts['pillar'],\n pillar,\n self.merge_strategy,\n self.opts.get('renderer', 'yaml'),\n self.opts.get('pillar_merge_lists', False))\n else:\n matches = self.top_matches(top)\n pillar, errors = self.render_pillar(matches)\n pillar, errors = self.ext_pillar(pillar, errors=errors)\n else:\n matches = self.top_matches(top)\n pillar, errors = self.render_pillar(matches)\n errors.extend(top_errors)\n if self.opts.get('pillar_opts', False):\n mopts = dict(self.opts)\n if 'grains' in mopts:\n mopts.pop('grains')\n mopts['saltversion'] = __version__\n pillar['master'] = mopts\n if 'pillar' in self.opts and self.opts.get('ssh_merge_pillar', False):\n pillar = merge(\n self.opts['pillar'],\n pillar,\n self.merge_strategy,\n self.opts.get('renderer', 'yaml'),\n self.opts.get('pillar_merge_lists', False))\n if errors:\n for error in errors:\n log.critical('Pillar render error: %s', error)\n pillar['_errors'] = errors\n\n if self.pillar_override:\n pillar = merge(\n pillar,\n self.pillar_override,\n self.merge_strategy,\n self.opts.get('renderer', 'yaml'),\n self.opts.get('pillar_merge_lists', False))\n\n decrypt_errors = self.decrypt_pillar(pillar)\n if decrypt_errors:\n pillar.setdefault('_errors', []).extend(decrypt_errors)\n\n return pillar\n",
"def update(self):\n try:\n log.debug('Updating fileserver for svn_pillar module')\n CLIENT.update(self.repo_dir)\n except pysvn.ClientError as exc:\n log.error(\n 'Unable to fetch the latest changes from remote %s: %s',\n self.repo_location, exc\n )\n",
"def pillar_dir(self):\n '''\n Returns the directory of the pillars (repo cache + branch + root)\n '''\n repo_dir = self.repo_dir\n root = self.root\n branch = self.branch\n if branch == 'trunk' or branch == 'base':\n working_dir = os.path.join(repo_dir, 'trunk', root)\n if not os.path.isdir(working_dir):\n log.error('Could not find %s/trunk/%s', self.repo_location, root)\n else:\n return os.path.normpath(working_dir)\n working_dir = os.path.join(repo_dir, 'branches', branch, root)\n if os.path.isdir(working_dir):\n return os.path.normpath(working_dir)\n working_dir = os.path.join(working_dir, 'tags', branch, root)\n if os.path.isdir(working_dir):\n return os.path.normpath(working_dir)\n log.error('Could not find %s/branches/%s/%s', self.repo_location, branch, root)\n return repo_dir\n"
] |
# -*- coding: utf-8 -*-
'''
Clone a remote SVN repository and use the filesystem as a Pillar source
This external Pillar source can be configured in the master config file like
so:
.. code-block:: yaml
ext_pillar:
- svn: trunk svn://svnserver/repo root=subdirectory
The `root=` parameter is optional and used to set the subdirectory from where
to look for Pillar files (such as ``top.sls``).
.. versionchanged:: 2014.7.0
The optional ``root`` parameter will be added.
Note that this is not the same thing as configuring pillar data using the
:conf_master:`pillar_roots` parameter. The branch referenced in the
:conf_master:`ext_pillar` entry above (``master``), would evaluate to the
``base`` environment, so this branch needs to contain a ``top.sls`` with a
``base`` section in it, like this:
.. code-block:: yaml
base:
'*':
- foo
To use other environments from the same SVN repo as svn_pillar sources, just
add additional lines, like so:
.. code-block:: yaml
ext_pillar:
- svn: trunk svn://svnserver/repo
- svn: dev svn://svnserver/repo
In this case, the ``dev`` branch would need its own ``top.sls`` with a ``dev``
section in it, like this:
.. code-block:: yaml
dev:
'*':
- bar
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
from copy import deepcopy
import logging
import os
import hashlib
# Import third party libs
HAS_SVN = False
try:
import pysvn
HAS_SVN = True
CLIENT = pysvn.Client()
except ImportError:
pass
# Import salt libs
from salt.pillar import Pillar
# Set up logging
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'svn'
def __virtual__():
ext_pillar_sources = [x for x in __opts__.get('ext_pillar', [])]
if not any(['svn' in x for x in ext_pillar_sources]):
return False
if not HAS_SVN:
log.error('SVN-based ext_pillar is enabled in configuration but '
'could not be loaded, is pysvn installed?')
return False
return __virtualname__
class SvnPillar(object):
'''
Deal with the remote SVN repository for Pillar
'''
def __init__(self, branch, repo_location, root, opts):
'''
Try to initialize the SVN repo object
'''
repo_hash = hashlib.md5(repo_location).hexdigest()
repo_dir = os.path.join(opts['cachedir'], 'pillar_svnfs', repo_hash)
self.branch = branch
self.root = root
self.repo_dir = repo_dir
self.repo_location = repo_location
if not os.path.isdir(repo_dir):
os.makedirs(repo_dir)
log.debug('Checking out fileserver for svn_pillar module')
try:
CLIENT.checkout(repo_location, repo_dir)
except pysvn.ClientError:
log.error(
'Failed to initialize svn_pillar %s %s',
repo_location, repo_dir
)
def update(self):
try:
log.debug('Updating fileserver for svn_pillar module')
CLIENT.update(self.repo_dir)
except pysvn.ClientError as exc:
log.error(
'Unable to fetch the latest changes from remote %s: %s',
self.repo_location, exc
)
def pillar_dir(self):
'''
Returns the directory of the pillars (repo cache + branch + root)
'''
repo_dir = self.repo_dir
root = self.root
branch = self.branch
if branch == 'trunk' or branch == 'base':
working_dir = os.path.join(repo_dir, 'trunk', root)
if not os.path.isdir(working_dir):
log.error('Could not find %s/trunk/%s', self.repo_location, root)
else:
return os.path.normpath(working_dir)
working_dir = os.path.join(repo_dir, 'branches', branch, root)
if os.path.isdir(working_dir):
return os.path.normpath(working_dir)
working_dir = os.path.join(working_dir, 'tags', branch, root)
if os.path.isdir(working_dir):
return os.path.normpath(working_dir)
log.error('Could not find %s/branches/%s/%s', self.repo_location, branch, root)
return repo_dir
def _extract_key_val(kv, delimiter='='):
'''Extract key and value from key=val string.
Example:
>>> _extract_key_val('foo=bar')
('foo', 'bar')
'''
pieces = kv.split(delimiter)
key = pieces[0]
val = delimiter.join(pieces[1:])
return key, val
|
saltstack/salt
|
salt/pillar/svn_pillar.py
|
SvnPillar.pillar_dir
|
python
|
def pillar_dir(self):
'''
Returns the directory of the pillars (repo cache + branch + root)
'''
repo_dir = self.repo_dir
root = self.root
branch = self.branch
if branch == 'trunk' or branch == 'base':
working_dir = os.path.join(repo_dir, 'trunk', root)
if not os.path.isdir(working_dir):
log.error('Could not find %s/trunk/%s', self.repo_location, root)
else:
return os.path.normpath(working_dir)
working_dir = os.path.join(repo_dir, 'branches', branch, root)
if os.path.isdir(working_dir):
return os.path.normpath(working_dir)
working_dir = os.path.join(working_dir, 'tags', branch, root)
if os.path.isdir(working_dir):
return os.path.normpath(working_dir)
log.error('Could not find %s/branches/%s/%s', self.repo_location, branch, root)
return repo_dir
|
Returns the directory of the pillars (repo cache + branch + root)
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/svn_pillar.py#L125-L145
| null |
class SvnPillar(object):
'''
Deal with the remote SVN repository for Pillar
'''
def __init__(self, branch, repo_location, root, opts):
'''
Try to initialize the SVN repo object
'''
repo_hash = hashlib.md5(repo_location).hexdigest()
repo_dir = os.path.join(opts['cachedir'], 'pillar_svnfs', repo_hash)
self.branch = branch
self.root = root
self.repo_dir = repo_dir
self.repo_location = repo_location
if not os.path.isdir(repo_dir):
os.makedirs(repo_dir)
log.debug('Checking out fileserver for svn_pillar module')
try:
CLIENT.checkout(repo_location, repo_dir)
except pysvn.ClientError:
log.error(
'Failed to initialize svn_pillar %s %s',
repo_location, repo_dir
)
def update(self):
try:
log.debug('Updating fileserver for svn_pillar module')
CLIENT.update(self.repo_dir)
except pysvn.ClientError as exc:
log.error(
'Unable to fetch the latest changes from remote %s: %s',
self.repo_location, exc
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.