diff --git a/salt/auth/django.py b/salt/auth/django.py index 915513fbc64..4b1fb2c2998 100644 --- a/salt/auth/django.py +++ b/salt/auth/django.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Provide authentication using Django Web Framework @@ -47,16 +46,11 @@ indicated above, though the model DOES NOT have to be named 'SaltExternalAuthModel'. """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import logging import os import sys -# Import 3rd-party libs -from salt.ext import six - # pylint: disable=import-error try: import django @@ -118,7 +112,7 @@ def __django_auth_setup(): django_module_name, globals(), locals(), "SaltExternalAuthModel" ) # pylint: enable=possibly-unused-variable - DJANGO_AUTH_CLASS_str = "django_auth_module.{0}".format(django_model_name) + DJANGO_AUTH_CLASS_str = "django_auth_module.{}".format(django_model_name) DJANGO_AUTH_CLASS = eval(DJANGO_AUTH_CLASS_str) # pylint: disable=W0123 @@ -211,7 +205,7 @@ def acl(username): found = False for d in auth_dict[a.user_fk.username]: if isinstance(d, dict): - if a.minion_or_fn_matcher in six.iterkeys(d): + if a.minion_or_fn_matcher in d.keys(): auth_dict[a.user_fk.username][a.minion_or_fn_matcher].append( a.minion_fn ) diff --git a/salt/auth/keystone.py b/salt/auth/keystone.py index 6e44f282baa..29ab72ca231 100644 --- a/salt/auth/keystone.py +++ b/salt/auth/keystone.py @@ -1,11 +1,9 @@ -# -*- coding: utf-8 -*- """ Provide authentication using OpenStack Keystone :depends: - keystoneclient Python module """ -from __future__ import absolute_import, print_function, unicode_literals try: from keystoneclient.v2_0 import client diff --git a/salt/auth/mysql.py b/salt/auth/mysql.py index 7c56bfab532..b2e1a59a352 100644 --- a/salt/auth/mysql.py +++ b/salt/auth/mysql.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - """ Provide authentication using MySQL. @@ -49,7 +47,6 @@ Enable MySQL authentication. :depends: - MySQL-python Python module """ -from __future__ import absolute_import, print_function, unicode_literals import logging diff --git a/salt/auth/yubico.py b/salt/auth/yubico.py index c4c39c2b28f..f0b37eb6c0d 100644 --- a/salt/auth/yubico.py +++ b/salt/auth/yubico.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - """ Provide authentication using YubiKey. @@ -38,8 +36,6 @@ the API key will be updated on all the YubiCloud servers. """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals import logging diff --git a/salt/executors/splay.py b/salt/executors/splay.py index d30826559f3..9a692c1c5fb 100644 --- a/salt/executors/splay.py +++ b/salt/executors/splay.py @@ -1,9 +1,6 @@ -# -*- coding: utf-8 -*- """ Splay function calls across targeted minions """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals import logging import time diff --git a/salt/grains/chronos.py b/salt/grains/chronos.py index 60478a76938..91d527f8e77 100644 --- a/salt/grains/chronos.py +++ b/salt/grains/chronos.py @@ -1,14 +1,10 @@ -# -*- coding: utf-8 -*- """ Generate chronos proxy minion grains. .. versionadded:: 2015.8.2 """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals -# Import Salt libs import salt.utils.http import salt.utils.platform diff --git a/salt/grains/cimc.py b/salt/grains/cimc.py index 080b124a6b6..72b89d931bb 100644 --- a/salt/grains/cimc.py +++ b/salt/grains/cimc.py @@ -1,17 +1,12 @@ -# -*- coding: utf-8 -*- """ Generate baseline proxy minion grains for cimc hosts. """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals import logging import salt.proxy.cimc - -# Import Salt Libs import salt.utils.platform __proxyenabled__ = ["cimc"] diff --git a/salt/grains/esxi.py b/salt/grains/esxi.py index ab6495b8771..cfb4aa52492 100644 --- a/salt/grains/esxi.py +++ b/salt/grains/esxi.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Generate baseline proxy minion grains for ESXi hosts. @@ -6,8 +5,6 @@ Generate baseline proxy minion grains for ESXi hosts. """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals import logging diff --git a/salt/grains/fibre_channel.py b/salt/grains/fibre_channel.py index 0b4334bb0dc..412f154d6e8 100644 --- a/salt/grains/fibre_channel.py +++ b/salt/grains/fibre_channel.py @@ -10,12 +10,10 @@ To enable these grains set ``fibre_channel_grains: True`` in the minion config. fibre_channel_grains: True """ -# Import Python libs import glob import logging -# Import Salt libs import salt.modules.cmdmod import salt.utils.files import salt.utils.platform diff --git a/salt/grains/fx2.py b/salt/grains/fx2.py index eaf8d24e1dc..e341fb721ef 100644 --- a/salt/grains/fx2.py +++ b/salt/grains/fx2.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Generate baseline proxy minion grains for Dell FX2 chassis. The challenge is that most of Salt isn't bootstrapped yet, @@ -6,7 +5,6 @@ so we need to repeat a bunch of things that would normally happen in proxy/fx2.py--just enough to get data from the chassis to include in grains. """ -from __future__ import absolute_import, print_function, unicode_literals import logging diff --git a/salt/grains/iscsi.py b/salt/grains/iscsi.py index 73210af1a65..a5dfefb4141 100644 --- a/salt/grains/iscsi.py +++ b/salt/grains/iscsi.py @@ -9,12 +9,10 @@ To enable these grains set `iscsi_grains: True` in the minion config. iscsi_grains: True """ -# Import Python libs import errno import logging -# Import Salt libs import salt.modules.cmdmod import salt.utils.files import salt.utils.path diff --git a/salt/grains/lvm.py b/salt/grains/lvm.py index 0166425db25..0903dcae3e1 100644 --- a/salt/grains/lvm.py +++ b/salt/grains/lvm.py @@ -2,10 +2,8 @@ Detect LVM Volumes """ -# Import python libs import logging -# Import salt libs import salt.modules.cmdmod import salt.utils.files import salt.utils.path diff --git a/salt/grains/marathon.py b/salt/grains/marathon.py index 0afcf781212..dba5f65cf5c 100644 --- a/salt/grains/marathon.py +++ b/salt/grains/marathon.py @@ -1,11 +1,9 @@ -# -*- coding: utf-8 -*- """ Generate marathon proxy minion grains. .. versionadded:: 2015.8.2 """ -from __future__ import absolute_import, print_function, unicode_literals import salt.utils.http import salt.utils.platform @@ -42,9 +40,7 @@ def os_data(): def marathon(): response = salt.utils.http.query( - "{0}/v2/info".format( - __opts__["proxy"].get("base_url", "http://locahost:8080",) - ), + "{}/v2/info".format(__opts__["proxy"].get("base_url", "http://locahost:8080",)), decode_type="json", decode=True, ) diff --git a/salt/grains/mdadm.py b/salt/grains/mdadm.py index f5e0fc704a5..87c9ef97f28 100644 --- a/salt/grains/mdadm.py +++ b/salt/grains/mdadm.py @@ -1,13 +1,9 @@ -# -*- coding: utf-8 -*- """ Detect MDADM RAIDs """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import logging -# Import salt libs import salt.utils.files log = logging.getLogger(__name__) @@ -28,7 +24,7 @@ def mdadm(): continue if " : " in line: devices.add(line.split(" : ")[0]) - except IOError: + except OSError: return {} devices = sorted(devices) diff --git a/salt/grains/nvme.py b/salt/grains/nvme.py index f4e8a32e5b4..60cef03e32f 100644 --- a/salt/grains/nvme.py +++ b/salt/grains/nvme.py @@ -9,12 +9,10 @@ To enable these grains set `nvme_grains: True` in the minion config. nvme_grains: True """ -# Import Python libs import errno import logging -# Import Salt libs import salt.utils.files import salt.utils.path import salt.utils.platform diff --git a/salt/grains/panos.py b/salt/grains/panos.py index aead7896426..60d0e52b71e 100644 --- a/salt/grains/panos.py +++ b/salt/grains/panos.py @@ -1,17 +1,12 @@ -# -*- coding: utf-8 -*- """ Generate baseline proxy minion grains for panos hosts. """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals import logging import salt.proxy.panos - -# Import Salt Libs import salt.utils.platform __proxyenabled__ = ["panos"] diff --git a/salt/grains/philips_hue.py b/salt/grains/philips_hue.py index c52cedf4783..12a340ba2da 100644 --- a/salt/grains/philips_hue.py +++ b/salt/grains/philips_hue.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright 2015 SUSE LLC # diff --git a/salt/grains/ssh_sample.py b/salt/grains/ssh_sample.py index 1985a14cb61..a51b7917178 100644 --- a/salt/grains/ssh_sample.py +++ b/salt/grains/ssh_sample.py @@ -1,8 +1,6 @@ -# -*- coding: utf-8 -*- """ Generate baseline proxy minion grains """ -from __future__ import absolute_import, print_function, unicode_literals import salt.utils.platform diff --git a/salt/modules/apcups.py b/salt/modules/apcups.py index 2792604d895..084720f890b 100644 --- a/salt/modules/apcups.py +++ b/salt/modules/apcups.py @@ -1,15 +1,10 @@ -# -*- coding: utf-8 -*- """ Module for apcupsd """ -from __future__ import absolute_import, print_function, unicode_literals -# Import Python libs import logging import salt.utils.decorators as decorators - -# Import Salt libs import salt.utils.path log = logging.getLogger(__name__) @@ -34,7 +29,7 @@ def __virtual__(): return __virtualname__ return ( False, - "{0} module can only be loaded on when apcupsd is installed".format( + "{} module can only be loaded on when apcupsd is installed".format( __virtualname__ ), ) diff --git a/salt/modules/aptly.py b/salt/modules/aptly.py index c3fca5a1944..a3409abfc3b 100644 --- a/salt/modules/aptly.py +++ b/salt/modules/aptly.py @@ -1,11 +1,8 @@ -# -*- coding: utf-8 -*- """ Aptly Debian repository manager. .. versionadded:: 2018.3.0 """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import logging import os @@ -16,9 +13,6 @@ import salt.utils.path import salt.utils.stringutils from salt.exceptions import SaltInvocationError -# Import salt libs -from salt.ext import six - _DEFAULT_CONFIG_PATH = "/etc/aptly.conf" log = logging.getLogger(__name__) @@ -183,7 +177,7 @@ def get_repo(name, config_path=_DEFAULT_CONFIG_PATH, with_packages=False): salt '*' aptly.get_repo name="test-repo" """ _validate_config(config_path) - with_packages = six.text_type(bool(with_packages)).lower() + with_packages = str(bool(with_packages)).lower() ret = dict() cmd = [ @@ -390,7 +384,7 @@ def delete_repo(name, config_path=_DEFAULT_CONFIG_PATH, force=False): salt '*' aptly.delete_repo name="test-repo" """ _validate_config(config_path) - force = six.text_type(bool(force)).lower() + force = str(bool(force)).lower() current_repo = __salt__["aptly.get_repo"](name=name, config_path=config_path) @@ -517,7 +511,7 @@ def cleanup_db(config_path=_DEFAULT_CONFIG_PATH, dry_run=False): salt '*' aptly.cleanup_db """ _validate_config(config_path) - dry_run = six.text_type(bool(dry_run)).lower() + dry_run = str(bool(dry_run)).lower() ret = {"deleted_keys": list(), "deleted_files": list()} diff --git a/salt/modules/augeas_cfg.py b/salt/modules/augeas_cfg.py index 27c5a3dfb1c..2af91159809 100644 --- a/salt/modules/augeas_cfg.py +++ b/salt/modules/augeas_cfg.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manages configuration files via augeas @@ -23,21 +22,15 @@ This module requires the ``augeas`` Python module. For affected Debian/Ubuntu hosts, installing ``libpython2.7`` has been known to resolve the issue. """ -from __future__ import absolute_import, print_function, unicode_literals import logging - -# Import python libs import os import re -# Import salt libs import salt.utils.args import salt.utils.data import salt.utils.stringutils from salt.exceptions import SaltInvocationError -from salt.ext import six -from salt.ext.six.moves import zip # Make sure augeas python interface is installed HAS_AUGEAS = False @@ -90,8 +83,7 @@ def _recurmatch(path, aug): for i in aug.match(clean_path + "/*"): i = i.replace("!", "\\!") # escape some dirs - for _match in _recurmatch(i, aug): - yield _match + yield from _recurmatch(i, aug) def _lstrip_word(word, prefix): @@ -100,8 +92,8 @@ def _lstrip_word(word, prefix): from the beginning of the string """ - if six.text_type(word).startswith(prefix): - return six.text_type(word)[len(prefix) :] + if str(word).startswith(prefix): + return str(word)[len(prefix) :] return word @@ -110,7 +102,7 @@ def _check_load_paths(load_path): Checks the validity of the load_path, returns a sanitized version with invalid paths removed. """ - if load_path is None or not isinstance(load_path, six.string_types): + if load_path is None or not isinstance(load_path, str): return None _paths = [] @@ -198,7 +190,7 @@ def execute(context=None, lens=None, commands=(), load_path=None): cmd, arg = command.split(" ", 1) if cmd not in METHOD_MAP: - ret["error"] = "Command {0} is not supported (yet)".format(cmd) + ret["error"] = "Command {} is not supported (yet)".format(cmd) return ret method = METHOD_MAP[cmd] @@ -207,7 +199,7 @@ def execute(context=None, lens=None, commands=(), load_path=None): parts = salt.utils.args.shlex_split(arg) if len(parts) not in nargs: - err = "{0} takes {1} args: {2}".format(method, nargs, parts) + err = "{} takes {} args: {}".format(method, nargs, parts) raise ValueError(err) if method == "set": path = make_path(parts[0]) @@ -226,7 +218,7 @@ def execute(context=None, lens=None, commands=(), load_path=None): label, where, path = parts if where not in ("before", "after"): raise ValueError( - 'Expected "before" or "after", not {0}'.format(where) + 'Expected "before" or "after", not {}'.format(where) ) path = make_path(path) args = {"path": path, "label": label, "before": where == "before"} @@ -240,7 +232,7 @@ def execute(context=None, lens=None, commands=(), load_path=None): arg = command ret["error"] = ( "Invalid formatted command, " - "see debug log for details: {0}".format(arg) + "see debug log for details: {}".format(arg) ) return ret @@ -253,13 +245,13 @@ def execute(context=None, lens=None, commands=(), load_path=None): try: aug.save() ret["retval"] = True - except IOError as err: - ret["error"] = six.text_type(err) + except OSError as err: + ret["error"] = str(err) if lens and not lens.endswith(".lns"): ret["error"] += ( '\nLenses are normally configured as "name.lns". ' - 'Did you mean "{0}.lns"?'.format(lens) + 'Did you mean "{}.lns"?'.format(lens) ) aug.close() @@ -296,12 +288,12 @@ def get(path, value="", load_path=None): path = path.rstrip("/") if value: - path += "/{0}".format(value.strip("/")) + path += "/{}".format(value.strip("/")) try: _match = aug.match(path) except RuntimeError as err: - return {"error": six.text_type(err)} + return {"error": str(err)} if _match: ret[path] = aug.get(path) @@ -349,7 +341,7 @@ def setvalue(*args): %wheel ALL = PASSWD : ALL , NOPASSWD : /usr/bin/apt-get , /usr/bin/aptitude """ load_path = None - load_paths = [x for x in args if six.text_type(x).startswith("load_path=")] + load_paths = [x for x in args if str(x).startswith("load_path=")] if load_paths: if len(load_paths) > 1: raise SaltInvocationError("Only one 'load_path=' value is permitted") @@ -363,10 +355,9 @@ def setvalue(*args): tuples = [ x for x in args - if not six.text_type(x).startswith("prefix=") - and not six.text_type(x).startswith("load_path=") + if not str(x).startswith("prefix=") and not str(x).startswith("load_path=") ] - prefix = [x for x in args if six.text_type(x).startswith("prefix=")] + prefix = [x for x in args if str(x).startswith("prefix=")] if prefix: if len(prefix) > 1: raise SaltInvocationError("Only one 'prefix=' value is permitted") @@ -382,15 +373,15 @@ def setvalue(*args): if prefix: target_path = os.path.join(prefix.rstrip("/"), path.lstrip("/")) try: - aug.set(target_path, six.text_type(value)) + aug.set(target_path, str(value)) except ValueError as err: - ret["error"] = "Multiple values: {0}".format(err) + ret["error"] = "Multiple values: {}".format(err) try: aug.save() ret["retval"] = True - except IOError as err: - ret["error"] = six.text_type(err) + except OSError as err: + ret["error"] = str(err) return ret @@ -467,8 +458,8 @@ def remove(path, load_path=None): ret["error"] = "Invalid node" else: ret["retval"] = True - except (RuntimeError, IOError) as err: - ret["error"] = six.text_type(err) + except (RuntimeError, OSError) as err: + ret["error"] = str(err) ret["count"] = count @@ -518,7 +509,7 @@ def ls(path, load_path=None): # pylint: disable=C0103 matches = _match(match_path) ret = {} - for key, value in six.iteritems(matches): + for key, value in matches.items(): name = _lstrip_word(key, path) if _match(key + "/*"): ret[name + "/"] = value # has sub nodes, e.g. directory diff --git a/salt/modules/bluez_bluetooth.py b/salt/modules/bluez_bluetooth.py index ac1d2a29008..ba2ec098e5d 100644 --- a/salt/modules/bluez_bluetooth.py +++ b/salt/modules/bluez_bluetooth.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Support for Bluetooth (using BlueZ in Linux). @@ -9,19 +8,11 @@ The following packages are required packages for this module: bluez-utils >= 5.7 pybluez >= 0.18 """ -from __future__ import absolute_import, print_function, unicode_literals +import shlex -# Import salt libs import salt.utils.validate.net from salt.exceptions import CommandExecutionError -# Import 3rd-party libs -# pylint: disable=import-error -from salt.ext.six.moves import shlex_quote as _cmd_quote - -# pylint: enable=import-error - - HAS_PYBLUEZ = False try: import bluetooth # pylint: disable=import-error @@ -89,7 +80,7 @@ def address_(): dev = comps[0] ret[dev] = { "device": dev, - "path": "/sys/class/bluetooth/{0}".format(dev), + "path": "/sys/class/bluetooth/{}".format(dev), } if "BD Address" in line: comps = line.split() @@ -121,7 +112,7 @@ def power(dev, mode): else: state = "down" mode = "off" - cmd = "hciconfig {0} {1}".format(dev, state) + cmd = "hciconfig {} {}".format(dev, state) __salt__["cmd.run"](cmd).splitlines() info = address_() if info[dev]["power"] == mode: @@ -142,9 +133,9 @@ def discoverable(dev): if dev not in address_(): raise CommandExecutionError("Invalid dev passed to bluetooth.discoverable") - cmd = "hciconfig {0} iscan".format(dev) + cmd = "hciconfig {} iscan".format(dev) __salt__["cmd.run"](cmd).splitlines() - cmd = "hciconfig {0}".format(dev) + cmd = "hciconfig {}".format(dev) out = __salt__["cmd.run"](cmd) if "UP RUNNING ISCAN" in out: return True @@ -164,9 +155,9 @@ def noscan(dev): if dev not in address_(): raise CommandExecutionError("Invalid dev passed to bluetooth.noscan") - cmd = "hciconfig {0} noscan".format(dev) + cmd = "hciconfig {} noscan".format(dev) __salt__["cmd.run"](cmd).splitlines() - cmd = "hciconfig {0}".format(dev) + cmd = "hciconfig {}".format(dev) out = __salt__["cmd.run"](cmd) if "SCAN" in out: return False @@ -203,7 +194,7 @@ def block(bdaddr): if not salt.utils.validate.net.mac(bdaddr): raise CommandExecutionError("Invalid BD address passed to bluetooth.block") - cmd = "hciconfig {0} block".format(bdaddr) + cmd = "hciconfig {} block".format(bdaddr) __salt__["cmd.run"](cmd).splitlines() @@ -220,7 +211,7 @@ def unblock(bdaddr): if not salt.utils.validate.net.mac(bdaddr): raise CommandExecutionError("Invalid BD address passed to bluetooth.unblock") - cmd = "hciconfig {0} unblock".format(bdaddr) + cmd = "hciconfig {} unblock".format(bdaddr) __salt__["cmd.run"](cmd).splitlines() @@ -251,8 +242,8 @@ def pair(address, key): ) addy = address_() - cmd = "echo {0} | bluez-simple-agent {1} {2}".format( - _cmd_quote(addy["device"]), _cmd_quote(address), _cmd_quote(key) + cmd = "echo {} | bluez-simple-agent {} {}".format( + shlex.quote(addy["device"]), shlex.quote(address), shlex.quote(key) ) out = __salt__["cmd.run"](cmd, python_shell=True).splitlines() return out @@ -276,7 +267,7 @@ def unpair(address): if not salt.utils.validate.net.mac(address): raise CommandExecutionError("Invalid BD address passed to bluetooth.unpair") - cmd = "bluez-test-device remove {0}".format(address) + cmd = "bluez-test-device remove {}".format(address) out = __salt__["cmd.run"](cmd).splitlines() return out diff --git a/salt/modules/boto_cfn.py b/salt/modules/boto_cfn.py index cfe9ebc167d..4c6b700482a 100644 --- a/salt/modules/boto_cfn.py +++ b/salt/modules/boto_cfn.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Connection module for Amazon Cloud Formation @@ -32,19 +31,13 @@ Connection module for Amazon Cloud Formation # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import logging import salt.utils.versions -# Import Salt libs -from salt.ext import six - log = logging.getLogger(__name__) -# Import third party libs # pylint: disable=import-error try: # pylint: disable=unused-import @@ -124,7 +117,7 @@ def describe(name, region=None, key=None, keyid=None, profile=None): "tags", ) - ret = dict([(k, getattr(stack, k)) for k in keys if hasattr(stack, k)]) + ret = {k: getattr(stack, k) for k in keys if hasattr(stack, k)} o = getattr(stack, "outputs") p = getattr(stack, "parameters") outputs = {} @@ -191,7 +184,7 @@ def create( stack_policy_url, ) except BotoServerError as e: - msg = "Failed to create stack {0}.\n{1}".format(name, e) + msg = "Failed to create stack {}.\n{}".format(name, e) log.error(msg) log.debug(e) return False @@ -251,10 +244,10 @@ def update_stack( log.debug("Updated result is : %s.", update) return update except BotoServerError as e: - msg = "Failed to update stack {0}.".format(name) + msg = "Failed to update stack {}.".format(name) log.debug(e) log.error(msg) - return six.text_type(e) + return str(e) def delete(name, region=None, key=None, keyid=None, profile=None): @@ -272,10 +265,10 @@ def delete(name, region=None, key=None, keyid=None, profile=None): try: return conn.delete_stack(name) except BotoServerError as e: - msg = "Failed to create stack {0}.".format(name) + msg = "Failed to create stack {}.".format(name) log.error(msg) log.debug(e) - return six.text_type(e) + return str(e) def get_template(name, region=None, key=None, keyid=None, profile=None): @@ -296,9 +289,9 @@ def get_template(name, region=None, key=None, keyid=None, profile=None): return template except BotoServerError as e: log.debug(e) - msg = "Template {0} does not exist".format(name) + msg = "Template {} does not exist".format(name) log.error(msg) - return six.text_type(e) + return str(e) def validate_template( @@ -327,6 +320,6 @@ def validate_template( return conn.validate_template(template_body, template_url) except BotoServerError as e: log.debug(e) - msg = "Error while trying to validate template {0}.".format(template_body) + msg = "Error while trying to validate template {}.".format(template_body) log.error(msg) - return six.text_type(e) + return str(e) diff --git a/salt/modules/boto_cloudfront.py b/salt/modules/boto_cloudfront.py index 1469cae3801..f9bd0697ef8 100644 --- a/salt/modules/boto_cloudfront.py +++ b/salt/modules/boto_cloudfront.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Connection module for Amazon CloudFront @@ -50,17 +49,12 @@ Connection module for Amazon CloudFront # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import logging -# Import Salt libs -import salt.ext.six as six import salt.utils.versions from salt.utils.odict import OrderedDict -# Import third party libs try: # pylint: disable=unused-import import boto3 @@ -102,7 +96,7 @@ def _list_distributions( continue for partial_dist in distribution_list["Items"]: tags = conn.list_tags_for_resource(Resource=partial_dist["ARN"]) - tags = dict((kv["Key"], kv["Value"]) for kv in tags["Tags"]["Items"]) + tags = {kv["Key"]: kv["Value"] for kv in tags["Tags"]["Items"]} id_ = partial_dist["Id"] if "Name" not in tags: @@ -247,13 +241,13 @@ def export_distributions(region=None, key=None, keyid=None, profile=None): {"config": config}, {"tags": tags}, ] - results["Manage CloudFront distribution {0}".format(name)] = { + results["Manage CloudFront distribution {}".format(name)] = { "boto_cloudfront.present": distribution_sls_data, } - except botocore.exceptions.ClientError as err: + except botocore.exceptions.ClientError as err: # pylint: disable=W0706 # Raise an exception, as this is meant to be user-invoked at the CLI # as opposed to being called from execution or state modules - six.reraise(*sys.exc_info()) + raise dumper = __utils__["yaml.get_dumper"]("IndentedSafeOrderedDumper") return __utils__["yaml.dump"](results, default_flow_style=False, Dumper=dumper,) @@ -301,7 +295,7 @@ def create_distribution( if tags["Name"] != name: return {"error": "Must not pass `Name` in `tags` but as `name`"} tags["Name"] = name - tags = {"Items": [{"Key": k, "Value": v} for k, v in six.iteritems(tags)]} + tags = {"Items": [{"Key": k, "Value": v} for k, v in tags.items()]} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: @@ -385,8 +379,7 @@ def update_distribution( if "new" in tags_diff: tags_to_add = { "Items": [ - {"Key": k, "Value": v} - for k, v in six.iteritems(tags_diff["new"]) + {"Key": k, "Value": v} for k, v in tags_diff["new"].items() ], } conn.tag_resource( diff --git a/salt/modules/boto_ec2.py b/salt/modules/boto_ec2.py index 72c1e7dac6b..5ff306b3edc 100644 --- a/salt/modules/boto_ec2.py +++ b/salt/modules/boto_ec2.py @@ -51,7 +51,6 @@ import salt.utils.data import salt.utils.json import salt.utils.versions from salt.exceptions import CommandExecutionError, SaltInvocationError -from salt.ext.six.moves import map try: # pylint: disable=unused-import diff --git a/salt/modules/boto_efs.py b/salt/modules/boto_efs.py index 5400ffbd8c8..70f226bf67c 100644 --- a/salt/modules/boto_efs.py +++ b/salt/modules/boto_efs.py @@ -48,10 +48,8 @@ Connection module for Amazon EFS """ -# Import python libs import logging -# Import salt libs import salt.utils.versions try: diff --git a/salt/modules/boto_iot.py b/salt/modules/boto_iot.py index ddb0bbbf585..906bb3c37a0 100644 --- a/salt/modules/boto_iot.py +++ b/salt/modules/boto_iot.py @@ -55,7 +55,6 @@ import logging import salt.utils.compat import salt.utils.json import salt.utils.versions -from salt.ext.six import string_types log = logging.getLogger(__name__) @@ -317,7 +316,7 @@ def create_policy( try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) - if not isinstance(policyDocument, string_types): + if not isinstance(policyDocument, str): policyDocument = salt.utils.json.dumps(policyDocument) policy = conn.create_policy( policyName=policyName, policyDocument=policyDocument @@ -443,7 +442,7 @@ def create_policy_version( try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) - if not isinstance(policyDocument, string_types): + if not isinstance(policyDocument, str): policyDocument = salt.utils.json.dumps(policyDocument) policy = conn.create_policy_version( policyName=policyName, diff --git a/salt/modules/boto_lambda.py b/salt/modules/boto_lambda.py index b735ece593f..68f8f17a196 100644 --- a/salt/modules/boto_lambda.py +++ b/salt/modules/boto_lambda.py @@ -87,7 +87,6 @@ import salt.utils.files import salt.utils.json import salt.utils.versions from salt.exceptions import SaltInvocationError -from salt.ext.six.moves import range # pylint: disable=import-error log = logging.getLogger(__name__) diff --git a/salt/modules/boto_s3.py b/salt/modules/boto_s3.py index e11e726d2c1..cde38cb099a 100644 --- a/salt/modules/boto_s3.py +++ b/salt/modules/boto_s3.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Connection module for Amazon S3 using boto3 @@ -50,12 +49,9 @@ Connection module for Amazon S3 using boto3 # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import logging -# Import Salt libs import salt.utils.versions log = logging.getLogger(__name__) diff --git a/salt/modules/boto_s3_bucket.py b/salt/modules/boto_s3_bucket.py index c8e9c747d0f..cafdd35feb5 100644 --- a/salt/modules/boto_s3_bucket.py +++ b/salt/modules/boto_s3_bucket.py @@ -57,7 +57,6 @@ import salt.utils.compat import salt.utils.json import salt.utils.versions from salt.exceptions import SaltInvocationError -from salt.ext.six.moves import range # pylint: disable=import-error log = logging.getLogger(__name__) diff --git a/salt/modules/boto_sqs.py b/salt/modules/boto_sqs.py index 4155a3c63f5..4e808d6d36e 100644 --- a/salt/modules/boto_sqs.py +++ b/salt/modules/boto_sqs.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Connection module for Amazon SQS @@ -44,26 +43,19 @@ Connection module for Amazon SQS # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 -from __future__ import absolute_import, print_function, unicode_literals -# Import Python libs import logging +import urllib.parse -# Import Salt libs import salt.utils.json import salt.utils.versions -# Import 3rd-party libs -from salt.ext import six -from salt.ext.six.moves.urllib.parse import urlparse as _urlparse - log = logging.getLogger(__name__) __func_alias__ = { "list_": "list", } -# Import third party libs try: # pylint: disable=unused-import import boto3 @@ -90,7 +82,7 @@ def _preprocess_attributes(attributes): """ Pre-process incoming queue attributes before setting them """ - if isinstance(attributes, six.string_types): + if isinstance(attributes, str): attributes = salt.utils.json.loads(attributes) def stringified(val): @@ -100,7 +92,7 @@ def _preprocess_attributes(attributes): return salt.utils.json.dumps(val) return val - return dict((attr, stringified(val)) for attr, val in six.iteritems(attributes)) + return {attr: stringified(val) for attr, val in attributes.items()} def exists(name, region=None, key=None, keyid=None, profile=None): @@ -186,7 +178,7 @@ def list_(prefix="", region=None, key=None, keyid=None, profile=None): def extract_name(queue_url): # Note: this logic taken from boto, so should be safe - return _urlparse(queue_url).path.split("/")[2] + return urllib.parse.urlparse(queue_url).path.split("/")[2] try: r = conn.list_queues(QueueNamePrefix=prefix) diff --git a/salt/modules/boto_ssm.py b/salt/modules/boto_ssm.py index 95c21dc594d..20a48ecd5a3 100644 --- a/salt/modules/boto_ssm.py +++ b/salt/modules/boto_ssm.py @@ -12,10 +12,8 @@ Connection module for Amazon SSM :depends: boto3 """ -# Import Python libs import logging -# Import Salt libs import salt.utils.boto3mod import salt.utils.json as json import salt.utils.versions diff --git a/salt/modules/capirca_acl.py b/salt/modules/capirca_acl.py index ed48897e81b..11b64cfdd40 100644 --- a/salt/modules/capirca_acl.py +++ b/salt/modules/capirca_acl.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Capirca ACL =========== @@ -21,19 +20,14 @@ The firewall configuration is generated by Capirca_. To install Capirca, execute: ``pip install capirca``. """ -from __future__ import absolute_import, print_function, unicode_literals import datetime import inspect import logging import re -# Import Salt libs import salt.utils.files -# Import third party libs -from salt.ext import six - log = logging.getLogger(__file__) @@ -196,7 +190,7 @@ if HAS_CAPIRCA: """ def __init__(self): - for field, default in six.iteritems(_TERM_FIELDS): + for field, default in _TERM_FIELDS.items(): setattr(self, field, default) @@ -242,7 +236,7 @@ def _get_services_mapping(): try: with salt.utils.files.fopen("/etc/services", "r") as srv_f: services_txt = salt.utils.stringutils.to_unicode(srv_f.read()) - except IOError as ioe: + except OSError as ioe: log.error("Unable to read from /etc/services:") log.error(ioe) return _SERVICES # no mapping possible, sorry @@ -338,11 +332,11 @@ def _clean_term_opts(term_opts): """ clean_opts = {} _services = _get_services_mapping() - for field, value in six.iteritems(term_opts): + for field, value in term_opts.items(): # firstly we'll process special fields like source_service or destination_services # which will inject values directly in the source or destination port and protocol if field == "source_service" and value: - if isinstance(value, six.string_types): + if isinstance(value, str): value = _make_it_list(clean_opts, field, value) log.debug("Processing special source services:") log.debug(value) @@ -363,7 +357,7 @@ def _clean_term_opts(term_opts): log.debug("Built protocol field, after processing special source services:") log.debug(clean_opts.get("protocol")) elif field == "destination_service" and value: - if isinstance(value, six.string_types): + if isinstance(value, str): value = _make_it_list(clean_opts, field, value) log.debug("Processing special destination services:") log.debug(value) @@ -394,10 +388,6 @@ def _clean_term_opts(term_opts): # IP-type fields need to be transformed ip_values = [] for addr in value: - if six.PY2: - addr = six.text_type(addr) - # Adding this, as ipaddress would complain about valid - # addresses not being valid. #pythonIsFun ip_values.append(capirca.lib.policy.nacaddr.IP(addr)) value = ip_values[:] clean_opts[field] = value @@ -519,11 +509,11 @@ def _get_term_object( log.debug("Final term opts:") term_opts.update(term_fields) log.debug(term_fields) - for field, value in six.iteritems(term_opts): + for field, value in term_opts.items(): # setting the field attributes to the term instance of _Term setattr(term, field, value) log.debug("Term config:") - log.debug(six.text_type(term)) + log.debug(str(term)) return term @@ -572,11 +562,11 @@ def _get_policy_object( policy_filters.append((header, filter_terms)) policy.filters = policy_filters log.debug("Policy config:") - log.debug(six.text_type(policy)) + log.debug(str(policy)) platform_generator = _import_platform_generator(platform) policy_config = platform_generator(policy, 2) log.debug("Generating policy config for %s:", platform) - log.debug(six.text_type(policy_config)) + log.debug(str(policy_config)) return policy_config @@ -1229,7 +1219,7 @@ def get_policy_config( saltenv=saltenv, merge_pillar=merge_pillar, ) - policy_text = six.text_type(policy_object) + policy_text = str(policy_object) return _revision_tag( policy_text, revision_id=revision_id, diff --git a/salt/modules/ceph.py b/salt/modules/ceph.py index f3df17cdc1b..2e3723bbe92 100644 --- a/salt/modules/ceph.py +++ b/salt/modules/ceph.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Module to provide ceph control with salt. @@ -6,8 +5,6 @@ Module to provide ceph control with salt. .. versionadded:: 2016.11.0 """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals import logging @@ -25,7 +22,7 @@ except ImportError: def __virtual__(): if HAS_CEPH_CFG is False: - msg = "ceph_cfg unavailable: {0} execution module cant be loaded ".format( + msg = "ceph_cfg unavailable: {} execution module cant be loaded ".format( __virtualname__ ) return False, msg diff --git a/salt/modules/chassis.py b/salt/modules/chassis.py index bd92bc5e41c..a6267177cf8 100644 --- a/salt/modules/chassis.py +++ b/salt/modules/chassis.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Glue execution module to link to the :mod:`fx2 proxymodule `. @@ -13,9 +12,7 @@ parameter in :mod:`salt.modules.dracr ` and calls it. .. versionadded:: 2015.8.2 """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import logging import salt.utils.platform diff --git a/salt/modules/cimc.py b/salt/modules/cimc.py index 786dbd6e919..5bde68524e5 100644 --- a/salt/modules/cimc.py +++ b/salt/modules/cimc.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Module to provide Cisco UCS compatibility to Salt @@ -25,14 +24,10 @@ rest API. """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals import logging import salt.proxy.cimc - -# Import Salt Libs import salt.utils.platform log = logging.getLogger(__name__) @@ -77,7 +72,7 @@ def activate_backup_image(reset=False): r = "yes" inconfig = """""".format( + adminState='trigger' image='backup' resetOnActivate='{}' />""".format( r ) @@ -121,7 +116,7 @@ def create_user(uid=None, username=None, password=None, priv=None): "The privilege level must be specified." ) - dn = "sys/user-ext/user-{0}".format(uid) + dn = "sys/user-ext/user-{}".format(uid) inconfig = """""".format( @@ -606,15 +601,15 @@ def mount_share( ) if username and password: - mount_options = " mountOptions='username={0},password={1}'".format( + mount_options = " mountOptions='username={},password={}'".format( username, password ) else: mount_options = "" - dn = "sys/svc-ext/vmedia-svc/vmmap-{0}".format(name) - inconfig = """""".format( name, mount_type, mount_options, remote_file, remote_share ) @@ -665,7 +660,7 @@ def set_hostname(hostname=None): raise salt.exceptions.CommandExecutionError("Hostname option must be provided.") dn = "sys/rack-unit-1/mgmt/if-1" - inconfig = """""".format( + inconfig = """""".format( hostname ) @@ -716,7 +711,7 @@ def set_logging_levels(remote=None, local=None): if remote: if remote in logging_options: - query += ' remoteSeverity="{0}"'.format(remote) + query += ' remoteSeverity="{}"'.format(remote) else: raise salt.exceptions.CommandExecutionError( "Remote Severity option is not valid." @@ -724,14 +719,14 @@ def set_logging_levels(remote=None, local=None): if local: if local in logging_options: - query += ' localSeverity="{0}"'.format(local) + query += ' localSeverity="{}"'.format(local) else: raise salt.exceptions.CommandExecutionError( "Local Severity option is not valid." ) dn = "sys/svc-ext/syslog" - inconfig = """""".format(query) + inconfig = """""".format(query) ret = __proxy__["cimc.set_config_modify"](dn, inconfig, False) @@ -762,8 +757,8 @@ def set_ntp_server(server1="", server2="", server3="", server4=""): """ dn = "sys/svc-ext/ntp-svc" - inconfig = """""".format( + inconfig = """""".format( server1, server2, server3, server4 ) @@ -821,7 +816,7 @@ def set_power_configuration(policy=None, delayType=None, delayValue=None): if delayType == "fixed": query += ' delayType="fixed"' if delayValue: - query += ' delay="{0}"'.format(delayValue) + query += ' delay="{}"'.format(delayValue) elif delayType == "random": query += ' delayType="random"' else: @@ -839,7 +834,7 @@ def set_power_configuration(policy=None, delayType=None, delayValue=None): dn = "sys/rack-unit-1/board/Resume-on-AC-power-loss" inconfig = """ + dn="sys/rack-unit-1/board/Resume-on-AC-power-loss"{}> """.format( query ) @@ -877,13 +872,13 @@ def set_syslog_server(server=None, type="primary"): if type == "primary": dn = "sys/svc-ext/syslog/client-primary" - inconfig = """ """.format( server ) elif type == "secondary": dn = "sys/svc-ext/syslog/client-secondary" - inconfig = """ """.format( server ) @@ -927,18 +922,18 @@ def set_user(uid=None, username=None, password=None, priv=None, status=None): raise salt.exceptions.CommandExecutionError("The user ID must be specified.") if status: - conf += ' accountStatus="{0}"'.format(status) + conf += ' accountStatus="{}"'.format(status) if username: - conf += ' name="{0}"'.format(username) + conf += ' name="{}"'.format(username) if priv: - conf += ' priv="{0}"'.format(priv) + conf += ' priv="{}"'.format(priv) if password: - conf += ' pwd="{0}"'.format(password) + conf += ' pwd="{}"'.format(password) - dn = "sys/user-ext/user-{0}".format(uid) + dn = "sys/user-ext/user-{}".format(uid) inconfig = """""".format(uid, conf) @@ -975,7 +970,7 @@ def tftp_update_bios(server=None, path=None): dn = "sys/rack-unit-1/bios/fw-updatable" inconfig = """""".format( server, path ) @@ -1013,7 +1008,7 @@ def tftp_update_cimc(server=None, path=None): dn = "sys/rack-unit-1/mgmt/fw-updatable" inconfig = """""".format( server, path ) diff --git a/salt/modules/ciscoconfparse_mod.py b/salt/modules/ciscoconfparse_mod.py index 747a75c19eb..793ea69aff6 100644 --- a/salt/modules/ciscoconfparse_mod.py +++ b/salt/modules/ciscoconfparse_mod.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Execution module for `ciscoconfparse `_ @@ -19,13 +18,10 @@ See http://www.pennington.net/py/ciscoconfparse/index.html for further details. This module depends on the Python library with the same name, ``ciscoconfparse`` - to install execute: ``pip install ciscoconfparse``. """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals from salt.exceptions import SaltException # Import Salt modules -from salt.ext import six try: import ciscoconfparse @@ -64,7 +60,7 @@ def _get_ccp(config=None, config_path=None, saltenv="base"): config = __salt__["cp.get_file_str"](config_path, saltenv=saltenv) if config is False: raise SaltException("{} is not available".format(config_path)) - if isinstance(config, six.string_types): + if isinstance(config, str): config = config.splitlines() ccp = ciscoconfparse.CiscoConfParse(config) return ccp diff --git a/salt/modules/composer.py b/salt/modules/composer.py index e0caa9c3cea..7feb5d0f2ca 100644 --- a/salt/modules/composer.py +++ b/salt/modules/composer.py @@ -1,14 +1,10 @@ -# -*- coding: utf-8 -*- """ Use composer to install PHP dependencies for a directory """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import logging import os.path -# Import salt libs import salt.utils.args import salt.utils.path from salt.exceptions import ( @@ -52,7 +48,7 @@ def did_composer_install(dir): salt '*' composer.did_composer_install /var/www/application """ - lockFile = "{0}/vendor".format(dir) + lockFile = "{}/vendor".format(dir) if os.path.exists(lockFile): return True return False @@ -140,7 +136,7 @@ def _run_composer( # Validate Composer is there if not _valid_composer(composer): raise CommandNotFoundError( - "'composer.{0}' is not available. Couldn't find '{1}'.".format( + "'composer.{}' is not available. Couldn't find '{}'.".format( action, composer ) ) @@ -151,7 +147,7 @@ def _run_composer( # Don't need a dir for the 'selfupdate' action; all other actions do need a dir if directory is None and action != "selfupdate": raise SaltInvocationError( - "The 'directory' argument is required for composer.{0}".format(action) + "The 'directory' argument is required for composer.{}".format(action) ) # Base Settings diff --git a/salt/modules/container_resource.py b/salt/modules/container_resource.py index e4f5bbfeda1..7c5dedfc278 100644 --- a/salt/modules/container_resource.py +++ b/salt/modules/container_resource.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Common resources for LXC and systemd-nspawn containers @@ -10,8 +9,6 @@ These functions are not designed to be called directly, but instead from the common logic to be re-used for common actions. """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import copy import functools @@ -21,7 +18,6 @@ import pipes import time import traceback -# Import salt libs import salt.utils.args import salt.utils.path import salt.utils.vt @@ -48,13 +44,13 @@ def _validate(wrapped): } if container_type not in valid_driver: raise SaltInvocationError( - "Invalid container type '{0}'. Valid types are: {1}".format( + "Invalid container type '{}'. Valid types are: {}".format( container_type, ", ".join(sorted(valid_driver)) ) ) if exec_driver not in valid_driver[container_type]: raise SaltInvocationError( - "Invalid command execution driver. Valid drivers are: {0}".format( + "Invalid command execution driver. Valid drivers are: {}".format( ", ".join(valid_driver[container_type]) ) ) @@ -72,16 +68,16 @@ def _nsenter(pid): """ Return the nsenter command to attach to the named container """ - return "nsenter --target {0} --mount --uts --ipc --net --pid".format(pid) + return "nsenter --target {} --mount --uts --ipc --net --pid".format(pid) def _get_md5(name, path, run_func): """ Get the MD5 checksum of a file from a container """ - output = run_func( - name, "md5sum {0}".format(pipes.quote(path)), ignore_retcode=True - )["stdout"] + output = run_func(name, "md5sum {}".format(pipes.quote(path)), ignore_retcode=True)[ + "stdout" + ] try: return output.split()[0] except IndexError: @@ -106,10 +102,10 @@ def cache_file(source): if source.startswith("salt://"): cached_source = __salt__["cp.cache_file"](source) if not cached_source: - raise CommandExecutionError("Unable to cache {0}".format(source)) + raise CommandExecutionError("Unable to cache {}".format(source)) return cached_source except AttributeError: - raise SaltInvocationError("Invalid source file {0}".format(source)) + raise SaltInvocationError("Invalid source file {}".format(source)) return source @@ -147,7 +143,7 @@ def run( cmd_func = "cmd.run" elif output not in valid_output: raise SaltInvocationError( - "'output' param must be one of the following: {0}".format( + "'output' param must be one of the following: {}".format( ", ".join(valid_output) ) ) @@ -168,57 +164,55 @@ def run( if exec_driver == "lxc-attach": full_cmd = "lxc-attach " if path: - full_cmd += "-P {0} ".format(pipes.quote(path)) + full_cmd += "-P {} ".format(pipes.quote(path)) if keep_env is not True: full_cmd += "--clear-env " if "PATH" not in to_keep: - full_cmd += "--set-var {0} ".format(PATH) + full_cmd += "--set-var {} ".format(PATH) # --clear-env results in a very restrictive PATH # (/bin:/usr/bin), use a good fallback. full_cmd += " ".join( [ - "--set-var {0}={1}".format(x, pipes.quote(os.environ[x])) + "--set-var {}={}".format(x, pipes.quote(os.environ[x])) for x in to_keep if x in os.environ ] ) - full_cmd += " -n {0} -- {1}".format(pipes.quote(name), cmd) + full_cmd += " -n {} -- {}".format(pipes.quote(name), cmd) elif exec_driver == "nsenter": - pid = __salt__["{0}.pid".format(container_type)](name) - full_cmd = "nsenter --target {0} --mount --uts --ipc --net --pid -- ".format( - pid - ) + pid = __salt__["{}.pid".format(container_type)](name) + full_cmd = "nsenter --target {} --mount --uts --ipc --net --pid -- ".format(pid) if keep_env is not True: full_cmd += "env -i " if "PATH" not in to_keep: - full_cmd += "{0} ".format(PATH) + full_cmd += "{} ".format(PATH) full_cmd += " ".join( [ - "{0}={1}".format(x, pipes.quote(os.environ[x])) + "{}={}".format(x, pipes.quote(os.environ[x])) for x in to_keep if x in os.environ ] ) - full_cmd += " {0}".format(cmd) + full_cmd += " {}".format(cmd) elif exec_driver == "docker-exec": # We're using docker exec on the CLI as opposed to via docker-py, since # the Docker API doesn't return stdout and stderr separately. full_cmd = "docker exec " if stdin: full_cmd += "-i " - full_cmd += "{0} ".format(name) + full_cmd += "{} ".format(name) if keep_env is not True: full_cmd += "env -i " if "PATH" not in to_keep: - full_cmd += "{0} ".format(PATH) + full_cmd += "{} ".format(PATH) full_cmd += " ".join( [ - "{0}={1}".format(x, pipes.quote(os.environ[x])) + "{}={}".format(x, pipes.quote(os.environ[x])) for x in to_keep if x in os.environ ] ) - full_cmd += " {0}".format(cmd) + full_cmd += " {}".format(cmd) if not use_vt: ret = __salt__[cmd_func]( @@ -305,13 +299,13 @@ def copy_to( salt myminion container_resource.copy_to mycontainer /local/file/path /container/file/path container_type=docker exec_driver=nsenter """ # Get the appropriate functions - state = __salt__["{0}.state".format(container_type)] + state = __salt__["{}.state".format(container_type)] def run_all(*args, **akwargs): akwargs = copy.deepcopy(akwargs) if container_type in ["lxc"] and "path" not in akwargs: akwargs["path"] = path - return __salt__["{0}.run_all".format(container_type)](*args, **akwargs) + return __salt__["{}.run_all".format(container_type)](*args, **akwargs) state_kwargs = {} cmd_kwargs = {"ignore_retcode": True} @@ -327,7 +321,7 @@ def copy_to( c_state = _state(name) if c_state != "running": - raise CommandExecutionError("Container '{0}' is not running".format(name)) + raise CommandExecutionError("Container '{}' is not running".format(name)) local_file = cache_file(source) source_dir, source_name = os.path.split(local_file) @@ -336,7 +330,7 @@ def copy_to( if not os.path.isabs(local_file): raise SaltInvocationError("Source path must be absolute") elif not os.path.exists(local_file): - raise SaltInvocationError("Source file {0} does not exist".format(local_file)) + raise SaltInvocationError("Source file {} does not exist".format(local_file)) elif not os.path.isfile(local_file): raise SaltInvocationError("Source must be a regular file") @@ -344,7 +338,7 @@ def copy_to( if not os.path.isabs(dest): raise SaltInvocationError("Destination path must be absolute") if ( - run_all(name, "test -d {0}".format(pipes.quote(dest)), **cmd_kwargs)["retcode"] + run_all(name, "test -d {}".format(pipes.quote(dest)), **cmd_kwargs)["retcode"] == 0 ): # Destination is a directory, full path to dest file will include the @@ -356,38 +350,38 @@ def copy_to( # parent directory. dest_dir, dest_name = os.path.split(dest) if ( - run_all(name, "test -d {0}".format(pipes.quote(dest_dir)), **cmd_kwargs)[ + run_all(name, "test -d {}".format(pipes.quote(dest_dir)), **cmd_kwargs)[ "retcode" ] != 0 ): if makedirs: result = run_all( - name, "mkdir -p {0}".format(pipes.quote(dest_dir)), **cmd_kwargs + name, "mkdir -p {}".format(pipes.quote(dest_dir)), **cmd_kwargs ) if result["retcode"] != 0: error = ( - "Unable to create destination directory {0} in " - "container '{1}'".format(dest_dir, name) + "Unable to create destination directory {} in " + "container '{}'".format(dest_dir, name) ) if result["stderr"]: - error += ": {0}".format(result["stderr"]) + error += ": {}".format(result["stderr"]) raise CommandExecutionError(error) else: raise SaltInvocationError( - "Directory {0} does not exist on {1} container '{2}'".format( + "Directory {} does not exist on {} container '{}'".format( dest_dir, container_type, name ) ) if ( not overwrite - and run_all(name, "test -e {0}".format(pipes.quote(dest)), **cmd_kwargs)[ + and run_all(name, "test -e {}".format(pipes.quote(dest)), **cmd_kwargs)[ "retcode" ] == 0 ): raise CommandExecutionError( - "Destination path {0} already exists. Use overwrite=True to " + "Destination path {} already exists. Use overwrite=True to " "overwrite it".format(dest) ) @@ -407,18 +401,18 @@ def copy_to( if exec_driver == "lxc-attach": lxcattach = "lxc-attach" if path: - lxcattach += " -P {0}".format(pipes.quote(path)) + lxcattach += " -P {}".format(pipes.quote(path)) copy_cmd = ( 'cat "{0}" | {4} --clear-env --set-var {1} -n {2} -- ' 'tee "{3}"'.format(local_file, PATH, name, dest, lxcattach) ) elif exec_driver == "nsenter": - pid = __salt__["{0}.pid".format(container_type)](name) - copy_cmd = 'cat "{0}" | {1} env -i {2} tee "{3}"'.format( + pid = __salt__["{}.pid".format(container_type)](name) + copy_cmd = 'cat "{}" | {} env -i {} tee "{}"'.format( local_file, _nsenter(pid), PATH, dest ) elif exec_driver == "docker-exec": - copy_cmd = 'cat "{0}" | docker exec -i {1} env -i {2} tee "{3}"'.format( + copy_cmd = 'cat "{}" | docker exec -i {} env -i {} tee "{}"'.format( local_file, name, PATH, dest ) __salt__["cmd.run"](copy_cmd, python_shell=True, output_loglevel="quiet") diff --git a/salt/modules/cpan.py b/salt/modules/cpan.py index 201f7a26567..b92f081d308 100644 --- a/salt/modules/cpan.py +++ b/salt/modules/cpan.py @@ -1,18 +1,13 @@ -# -*- coding: utf-8 -*- """ Manage Perl modules using CPAN .. versionadded:: 2015.5.0 """ -from __future__ import absolute_import, print_function, unicode_literals import logging - -# Import python libs import os import os.path -# Import salt libs import salt.utils.files import salt.utils.path @@ -48,7 +43,7 @@ def install(module): old_info = show(module) - cmd = "cpan -i {0}".format(module) + cmd = "cpan -i {}".format(module) out = __salt__["cmd.run"](cmd) if "don't know what it is" in out: @@ -158,7 +153,7 @@ def show(module): ret["name"] = module # This section parses out details from CPAN, if possible - cmd = "cpan -D {0}".format(module) + cmd = "cpan -D {}".format(module) out = __salt__["cmd.run"](cmd).splitlines() mode = "skip" info = [] diff --git a/salt/modules/cyg.py b/salt/modules/cyg.py index d7b68c01ee1..9f7a61af59a 100644 --- a/salt/modules/cyg.py +++ b/salt/modules/cyg.py @@ -1,30 +1,20 @@ -# -*- coding: utf-8 -*- """ Manage cygwin packages. Module file to accompany the cyg state. """ -from __future__ import absolute_import, print_function, unicode_literals import bz2 - -# Import python libs import logging import os import re +import urllib.request -# Import Salt libs import salt.utils.files import salt.utils.platform import salt.utils.stringutils from salt.exceptions import SaltInvocationError -# Import 3rd-party libs -from salt.ext import six - -# Import 3rd-party libs -from salt.ext.six.moves.urllib.request import urlopen as _urlopen - LOG = logging.getLogger(__name__) DEFAULT_MIRROR = "ftp://mirrors.kernel.org/sourceware/cygwin/" @@ -86,7 +76,7 @@ def _get_all_packages(mirror=DEFAULT_MIRROR, cyg_arch="x86_64"): if not __context__["cyg.all_packages"][mirror]: pkg_source = "/".join([mirror, cyg_arch, "setup.bz2"]) - file_data = _urlopen(pkg_source).read() + file_data = urllib.request.urlopen(pkg_source).read() file_lines = ( bz2.decompress(file_data).decode("utf_8", errors="replace").splitlines() ) @@ -139,9 +129,9 @@ def _run_silent_cygwin(cyg_arch="x86_64", args=None, mirrors=None): installation up and running. """ cyg_cache_dir = os.sep.join(["c:", "cygcache"]) - cyg_setup = "setup-{0}.exe".format(cyg_arch) + cyg_setup = "setup-{}.exe".format(cyg_arch) cyg_setup_path = os.sep.join([cyg_cache_dir, cyg_setup]) - cyg_setup_source = "http://cygwin.com/{0}".format(cyg_setup) + cyg_setup_source = "http://cygwin.com/{}".format(cyg_setup) # cyg_setup_source_hash = 'http://cygwin.com/{0}.sig'.format(cyg_setup) # until a hash gets published that we can verify the newest setup against @@ -151,21 +141,21 @@ def _run_silent_cygwin(cyg_arch="x86_64", args=None, mirrors=None): elif os.path.exists(cyg_setup_path): os.remove(cyg_setup_path) - file_data = _urlopen(cyg_setup_source) + file_data = urllib.request.urlopen(cyg_setup_source) with salt.utils.files.fopen(cyg_setup_path, "wb") as fhw: fhw.write(file_data.read()) setup_command = cyg_setup_path options = [] - options.append("--local-package-dir {0}".format(cyg_cache_dir)) + options.append("--local-package-dir {}".format(cyg_cache_dir)) if mirrors is None: mirrors = [{DEFAULT_MIRROR: DEFAULT_MIRROR_KEY}] for mirror in mirrors: for mirror_url, key in mirror.items(): - options.append("--site {0}".format(mirror_url)) + options.append("--site {}".format(mirror_url)) if key: - options.append("--pubkey {0}".format(key)) + options.append("--pubkey {}".format(key)) options.append("--no-desktop") options.append("--quiet-mode") options.append("--disable-buggy-antivirus") @@ -306,7 +296,7 @@ def list_(package="", cyg_arch="x86_64"): args = " ".join(["-c", "-d", package]) stdout = _cygcheck(args, cyg_arch=cyg_arch) lines = [] - if isinstance(stdout, six.string_types): + if isinstance(stdout, str): lines = salt.utils.stringutils.to_unicode(stdout).splitlines() for line in lines: match = re.match(r"^([^ ]+) *([^ ]+)", line) diff --git a/salt/modules/daemontools.py b/salt/modules/daemontools.py index c44a37db37d..84a9dc2eabf 100644 --- a/salt/modules/daemontools.py +++ b/salt/modules/daemontools.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ daemontools service module. This module will create daemontools type service watcher. @@ -12,15 +11,12 @@ so it can be used to maintain services using the ``provider`` argument: service.running: - provider: daemontools """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import logging import os import os.path import re -# Import salt libs import salt.utils.path from salt.exceptions import CommandExecutionError @@ -48,7 +44,7 @@ def __virtual__(): BINS = frozenset(("svc", "supervise", "svok")) if all(salt.utils.path.which(b) for b in BINS) and SERVICE_DIR: return __virtualname__ - return (False, "Missing dependency: {0}".format(BINS)) + return (False, "Missing dependency: {}".format(BINS)) def _service_path(name): @@ -57,7 +53,7 @@ def _service_path(name): """ if not SERVICE_DIR: raise CommandExecutionError("Could not find service directory.") - return "{0}/{1}".format(SERVICE_DIR, name) + return "{}/{}".format(SERVICE_DIR, name) # -- states.service compatible args @@ -71,8 +67,8 @@ def start(name): salt '*' daemontools.start """ - __salt__["file.remove"]("{0}/down".format(_service_path(name))) - cmd = "svc -u {0}".format(_service_path(name)) + __salt__["file.remove"]("{}/down".format(_service_path(name))) + cmd = "svc -u {}".format(_service_path(name)) return not __salt__["cmd.retcode"](cmd, python_shell=False) @@ -87,8 +83,8 @@ def stop(name): salt '*' daemontools.stop """ - __salt__["file.touch"]("{0}/down".format(_service_path(name))) - cmd = "svc -d {0}".format(_service_path(name)) + __salt__["file.touch"]("{}/down".format(_service_path(name))) + cmd = "svc -d {}".format(_service_path(name)) return not __salt__["cmd.retcode"](cmd, python_shell=False) @@ -102,7 +98,7 @@ def term(name): salt '*' daemontools.term """ - cmd = "svc -t {0}".format(_service_path(name)) + cmd = "svc -t {}".format(_service_path(name)) return not __salt__["cmd.retcode"](cmd, python_shell=False) @@ -162,7 +158,7 @@ def status(name, sig=None): salt '*' daemontools.status """ - cmd = "svstat {0}".format(_service_path(name)) + cmd = "svstat {}".format(_service_path(name)) out = __salt__["cmd.run_stdout"](cmd, python_shell=False) try: pid = re.search(r"\(pid (\d+)\)", out).group(1) diff --git a/salt/modules/datadog_api.py b/salt/modules/datadog_api.py index 6dee8e99f5c..ad054116068 100644 --- a/salt/modules/datadog_api.py +++ b/salt/modules/datadog_api.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ An execution module that interacts with the Datadog API @@ -14,10 +13,7 @@ Full argument reference is available on the Datadog API reference page https://docs.datadoghq.com/api/ """ -# Import salt libs -from __future__ import absolute_import, print_function, unicode_literals -# Import third party libs import requests from salt.exceptions import SaltInvocationError diff --git a/salt/modules/ddns.py b/salt/modules/ddns.py index 0b348498c8b..f360812c703 100644 --- a/salt/modules/ddns.py +++ b/salt/modules/ddns.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Support for RFC 2136 dynamic DNS updates. @@ -23,14 +22,11 @@ Support for RFC 2136 dynamic DNS updates. {"keyname.": "keycontent"} """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import logging import salt.utils.files import salt.utils.json -from salt.ext import six log = logging.getLogger(__name__) @@ -66,7 +62,7 @@ def _config(name, key=None, **kwargs): if name in kwargs: value = kwargs[name] else: - value = __salt__["config.option"]("ddns.{0}".format(key)) + value = __salt__["config.option"]("ddns.{}".format(key)) if not value: value = None return value @@ -104,7 +100,7 @@ def add_host( if res is False: return False - fqdn = "{0}.{1}.".format(name, zone) + fqdn = "{}.{}.".format(name, zone) parts = ip.split(".")[::-1] popped = [] @@ -112,7 +108,7 @@ def add_host( while len(parts) > 1: p = parts.pop(0) popped.append(p) - zone = "{0}.{1}".format(".".join(parts), "in-addr.arpa.") + zone = "{}.{}".format(".".join(parts), "in-addr.arpa.") name = ".".join(popped) ptr = update( zone, name, ttl, "PTR", fqdn, nameserver, timeout, replace, port, **kwargs @@ -134,7 +130,7 @@ def delete_host(zone, name, nameserver="127.0.0.1", timeout=5, port=53, **kwargs salt ns1 ddns.delete_host example.com host1 """ - fqdn = "{0}.{1}".format(name, zone) + fqdn = "{}.{}".format(name, zone) request = dns.message.make_query(fqdn, "A") answer = dns.query.udp(request, nameserver, timeout, port) try: @@ -155,7 +151,7 @@ def delete_host(zone, name, nameserver="127.0.0.1", timeout=5, port=53, **kwargs while len(parts) > 1: p = parts.pop(0) popped.append(p) - zone = "{0}.{1}".format(".".join(parts), "in-addr.arpa.") + zone = "{}.{}".format(".".join(parts), "in-addr.arpa.") name = ".".join(popped) ptr = delete( zone, @@ -196,12 +192,12 @@ def update( salt ns1 ddns.update example.com host1 60 A 10.0.0.1 """ - name = six.text_type(name) + name = str(name) if name[-1:] == ".": fqdn = name else: - fqdn = "{0}.{1}".format(name, zone) + fqdn = "{}.{}".format(name, zone) request = dns.message.make_query(fqdn, rdtype) answer = dns.query.udp(request, nameserver, timeout, port) @@ -255,12 +251,12 @@ def delete( salt ns1 ddns.delete example.com host1 A """ - name = six.text_type(name) + name = str(name) if name[-1:] == ".": fqdn = name else: - fqdn = "{0}.{1}".format(name, zone) + fqdn = "{}.{}".format(name, zone) request = dns.message.make_query(fqdn, (rdtype or "ANY")) answer = dns.query.udp(request, nameserver, timeout, port) diff --git a/salt/modules/deb_apache.py b/salt/modules/deb_apache.py index 89c3d448bd0..0266cbc72eb 100644 --- a/salt/modules/deb_apache.py +++ b/salt/modules/deb_apache.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Support for Apache @@ -6,14 +5,10 @@ Please note: The functions in here are Debian-specific. Placing them in this separate file will allow them to load only on Debian-based systems, while still loading under the ``apache`` namespace. """ -from __future__ import absolute_import, print_function, unicode_literals import logging - -# Import python libs import os -# Import salt libs import salt.utils.decorators.path import salt.utils.path @@ -64,11 +59,11 @@ def check_site_enabled(site): if site.endswith(".conf"): site_file = site else: - site_file = "{0}.conf".format(site) - if os.path.islink("{0}/{1}".format(SITE_ENABLED_DIR, site_file)): + site_file = "{}.conf".format(site) + if os.path.islink("{}/{}".format(SITE_ENABLED_DIR, site_file)): return True elif site == "default" and os.path.islink( - "{0}/000-{1}".format(SITE_ENABLED_DIR, site_file) + "{}/000-{}".format(SITE_ENABLED_DIR, site_file) ): return True else: @@ -100,9 +95,9 @@ def a2ensite(site): ret["Site"] = site if status == 1: - ret["Status"] = "Site {0} Not found".format(site) + ret["Status"] = "Site {} Not found".format(site) elif status == 0: - ret["Status"] = "Site {0} enabled".format(site) + ret["Status"] = "Site {} enabled".format(site) else: ret["Status"] = status @@ -134,9 +129,9 @@ def a2dissite(site): ret["Site"] = site if status == 256: - ret["Status"] = "Site {0} Not found".format(site) + ret["Status"] = "Site {} Not found".format(site) elif status == 0: - ret["Status"] = "Site {0} disabled".format(site) + ret["Status"] = "Site {} disabled".format(site) else: ret["Status"] = status @@ -161,8 +156,8 @@ def check_mod_enabled(mod): if mod.endswith(".load") or mod.endswith(".conf"): mod_file = mod else: - mod_file = "{0}.load".format(mod) - return os.path.islink("/etc/apache2/mods-enabled/{0}".format(mod_file)) + mod_file = "{}.load".format(mod) + return os.path.islink("/etc/apache2/mods-enabled/{}".format(mod_file)) def a2enmod(mod): @@ -190,9 +185,9 @@ def a2enmod(mod): ret["Mod"] = mod if status == 1: - ret["Status"] = "Mod {0} Not found".format(mod) + ret["Status"] = "Mod {} Not found".format(mod) elif status == 0: - ret["Status"] = "Mod {0} enabled".format(mod) + ret["Status"] = "Mod {} enabled".format(mod) else: ret["Status"] = status @@ -224,9 +219,9 @@ def a2dismod(mod): ret["Mod"] = mod if status == 256: - ret["Status"] = "Mod {0} Not found".format(mod) + ret["Status"] = "Mod {} Not found".format(mod) elif status == 0: - ret["Status"] = "Mod {0} disabled".format(mod) + ret["Status"] = "Mod {} disabled".format(mod) else: ret["Status"] = status @@ -252,8 +247,8 @@ def check_conf_enabled(conf): if conf.endswith(".conf"): conf_file = conf else: - conf_file = "{0}.conf".format(conf) - return os.path.islink("/etc/apache2/conf-enabled/{0}".format(conf_file)) + conf_file = "{}.conf".format(conf) + return os.path.islink("/etc/apache2/conf-enabled/{}".format(conf_file)) @salt.utils.decorators.path.which("a2enconf") @@ -284,9 +279,9 @@ def a2enconf(conf): ret["Conf"] = conf if status == 1: - ret["Status"] = "Conf {0} Not found".format(conf) + ret["Status"] = "Conf {} Not found".format(conf) elif status == 0: - ret["Status"] = "Conf {0} enabled".format(conf) + ret["Status"] = "Conf {} enabled".format(conf) else: ret["Status"] = status @@ -321,9 +316,9 @@ def a2disconf(conf): ret["Conf"] = conf if status == 256: - ret["Status"] = "Conf {0} Not found".format(conf) + ret["Status"] = "Conf {} Not found".format(conf) elif status == 0: - ret["Status"] = "Conf {0} disabled".format(conf) + ret["Status"] = "Conf {} disabled".format(conf) else: ret["Status"] = status diff --git a/salt/modules/deb_postgres.py b/salt/modules/deb_postgres.py index 722e0091044..440450c67af 100644 --- a/salt/modules/deb_postgres.py +++ b/salt/modules/deb_postgres.py @@ -3,16 +3,12 @@ Module to provide Postgres compatibility to salt for debian family specific tool """ -# Import python libs import logging import pipes -# Import salt libs import salt.utils.path -# Import 3rd-party libs - log = logging.getLogger(__name__) __virtualname__ = "postgres" diff --git a/salt/modules/djangomod.py b/salt/modules/djangomod.py index 48f1f0fe4fa..7408b64528f 100644 --- a/salt/modules/djangomod.py +++ b/salt/modules/djangomod.py @@ -1,22 +1,13 @@ -# -*- coding: utf-8 -*- """ Manage Django sites """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals - import os import salt.exceptions - -# Import Salt libs import salt.utils.path -# Import 3rd-party libs -from salt.ext import six - # Define the module's virtual name __virtualname__ = "django" @@ -65,17 +56,17 @@ def command( salt '*' django.command """ dja = _get_django_admin(bin_env) - cmd = "{0} {1} --settings={2}".format(dja, command, settings_module) + cmd = "{} {} --settings={}".format(dja, command, settings_module) if pythonpath: - cmd = "{0} --pythonpath={1}".format(cmd, pythonpath) + cmd = "{} --pythonpath={}".format(cmd, pythonpath) for arg in args: - cmd = "{0} --{1}".format(cmd, arg) + cmd = "{} --{}".format(cmd, arg) - for key, value in six.iteritems(kwargs): + for key, value in kwargs.items(): if not key.startswith("__"): - cmd = "{0} --{1}={2}".format(cmd, key, value) + cmd = "{} --{}={}".format(cmd, key, value) return __salt__["cmd.run"](cmd, env=env, runas=runas, python_shell=False) @@ -202,9 +193,9 @@ def migrate( args.append("noinput") if app_label and migration_name: - cmd = "migrate {0} {1}".format(app_label, migration_name) + cmd = "migrate {} {}".format(app_label, migration_name) elif app_label: - cmd = "migrate {0}".format(app_label) + cmd = "migrate {}".format(app_label) else: cmd = "migrate" @@ -271,7 +262,7 @@ def loaddata( if database: kwargs["database"] = database - cmd = "{0} {1}".format("loaddata", " ".join(fixtures.split(","))) + cmd = "{} {}".format("loaddata", " ".join(fixtures.split(","))) return command(settings_module, cmd, bin_env, pythonpath, env, *args, **kwargs) diff --git a/salt/modules/dnsmasq.py b/salt/modules/dnsmasq.py index d1bd5eec71b..e3f1d8bfa80 100644 --- a/salt/modules/dnsmasq.py +++ b/salt/modules/dnsmasq.py @@ -1,22 +1,15 @@ -# -*- coding: utf-8 -*- """ Module for managing dnsmasq """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import logging import os -# Import salt libs import salt.utils.files import salt.utils.platform from salt.exceptions import CommandExecutionError -# Import 3rd-party libs -from salt.ext import six - log = logging.getLogger(__name__) @@ -106,7 +99,7 @@ def set_config(config_file="/etc/dnsmasq.conf", follow=True, **kwargs): continue if filename.endswith("#") and filename.endswith("#"): continue - includes.append("{0}/{1}".format(dnsopts["conf-dir"], filename)) + includes.append("{}/{}".format(dnsopts["conf-dir"], filename)) ret_kwargs = {} for key in kwargs: @@ -117,17 +110,17 @@ def set_config(config_file="/etc/dnsmasq.conf", follow=True, **kwargs): ret_kwargs[key] = kwargs[key] if key in dnsopts: - if isinstance(dnsopts[key], six.string_types): + if isinstance(dnsopts[key], str): for config in includes: __salt__["file.sed"]( path=config, - before="^{0}=.*".format(key), - after="{0}={1}".format(key, kwargs[key]), + before="^{}=.*".format(key), + after="{}={}".format(key, kwargs[key]), ) else: - __salt__["file.append"](config_file, "{0}={1}".format(key, kwargs[key])) + __salt__["file.append"](config_file, "{}={}".format(key, kwargs[key])) else: - __salt__["file.append"](config_file, "{0}={1}".format(key, kwargs[key])) + __salt__["file.append"](config_file, "{}={}".format(key, kwargs[key])) return ret_kwargs @@ -156,7 +149,7 @@ def get_config(config_file="/etc/dnsmasq.conf"): if filename.endswith("#") and filename.endswith("#"): continue dnsopts.update( - _parse_dnamasq("{0}/{1}".format(dnsopts["conf-dir"], filename)) + _parse_dnamasq("{}/{}".format(dnsopts["conf-dir"], filename)) ) return dnsopts @@ -168,7 +161,7 @@ def _parse_dnamasq(filename): fileopts = {} if not os.path.isfile(filename): - raise CommandExecutionError("Error: No such file '{0}'".format(filename)) + raise CommandExecutionError("Error: No such file '{}'".format(filename)) with salt.utils.files.fopen(filename, "r") as fp_: for line in fp_: @@ -180,7 +173,7 @@ def _parse_dnamasq(filename): if "=" in line: comps = line.split("=") if comps[0] in fileopts: - if isinstance(fileopts[comps[0]], six.string_types): + if isinstance(fileopts[comps[0]], str): temp = fileopts[comps[0]] fileopts[comps[0]] = [temp] fileopts[comps[0]].append(comps[1].strip()) diff --git a/salt/modules/drac.py b/salt/modules/drac.py index 5ba4100b0df..1897c42a3be 100644 --- a/salt/modules/drac.py +++ b/salt/modules/drac.py @@ -1,20 +1,12 @@ -# -*- coding: utf-8 -*- """ Manage Dell DRAC """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import logging -# Import Salt libs import salt.utils.path -# Import 3rd-party libs -from salt.ext import six -from salt.ext.six.moves import range - log = logging.getLogger(__name__) @@ -51,7 +43,7 @@ def __execute_cmd(command): """ Execute rac commands """ - cmd = __salt__["cmd.run_all"]("racadm {0}".format(command)) + cmd = __salt__["cmd.run_all"]("racadm {}".format(command)) if cmd["retcode"] != 0: log.warning("racadm return an exit code '%s'.", cmd["retcode"]) @@ -115,7 +107,7 @@ def nameservers(*ns): for i in range(1, len(ns) + 1): if not __execute_cmd( "config -g cfgLanNetworking -o \ - cfgDNSServer{0} {1}".format( + cfgDNSServer{} {}".format( i, ns[i - 1] ) ): @@ -143,7 +135,7 @@ def syslog(server, enable=True): ): return __execute_cmd( "config -g cfgRemoteHosts -o \ - cfgRhostsSyslogServer1 {0}".format( + cfgRhostsSyslogServer1 {}".format( server ) ) @@ -191,7 +183,7 @@ def list_users(): for idx in range(1, 17): cmd = __salt__["cmd.run_all"]( "racadm getconfig -g \ - cfgUserAdmin -i {0}".format( + cfgUserAdmin -i {}".format( idx ) ) @@ -236,7 +228,7 @@ def delete_user(username, uid=None): if uid: return __execute_cmd( 'config -g cfgUserAdmin -o \ - cfgUserAdminUserName -i {0} ""'.format( + cfgUserAdminUserName -i {} ""'.format( uid ) ) @@ -266,7 +258,7 @@ def change_password(username, password, uid=None): if uid: return __execute_cmd( "config -g cfgUserAdmin -o \ - cfgUserAdminPassword -i {0} {1}".format( + cfgUserAdminPassword -i {} {}".format( uid, password ) ) @@ -308,7 +300,7 @@ def create_user(username, password, permissions, users=None): log.warning("'%s' already exists", username) return False - for idx in six.iterkeys(users): + for idx in users.keys(): _uids.add(users[idx]["index"]) uid = sorted(list(set(range(2, 12)) - _uids), reverse=True).pop() @@ -316,7 +308,7 @@ def create_user(username, password, permissions, users=None): # Create user accountvfirst if not __execute_cmd( "config -g cfgUserAdmin -o \ - cfgUserAdminUserName -i {0} {1}".format( + cfgUserAdminUserName -i {} {}".format( uid, username ) ): @@ -338,7 +330,7 @@ def create_user(username, password, permissions, users=None): # Enable users admin if not __execute_cmd( "config -g cfgUserAdmin -o \ - cfgUserAdminEnable -i {0} 1".format( + cfgUserAdminEnable -i {} 1".format( uid ) ): @@ -398,7 +390,7 @@ def set_permissions(username, permissions, uid=None): return __execute_cmd( "config -g cfgUserAdmin -o \ - cfgUserAdminPrivilege -i {0} 0x{1:08X}".format( + cfgUserAdminPrivilege -i {} 0x{:08X}".format( uid, permission ) ) @@ -417,7 +409,7 @@ def set_snmp(community): """ return __execute_cmd( "config -g cfgOobSnmp -o \ - cfgOobSnmpAgentCommunity {0}".format( + cfgOobSnmpAgentCommunity {}".format( community ) ) @@ -434,7 +426,7 @@ def set_network(ip, netmask, gateway): salt dell drac.set_network [DRAC IP] [NETMASK] [GATEWAY] salt dell drac.set_network 192.168.0.2 255.255.255.0 192.168.0.1 """ - return __execute_cmd("setniccfg -s {0} {1} {2}".format(ip, netmask, gateway)) + return __execute_cmd("setniccfg -s {} {} {}".format(ip, netmask, gateway)) def server_reboot(): diff --git a/salt/modules/dracr.py b/salt/modules/dracr.py index 22c9c5f9686..680055a4d67 100644 --- a/salt/modules/dracr.py +++ b/salt/modules/dracr.py @@ -1,26 +1,17 @@ -# -*- coding: utf-8 -*- """ Manage Dell DRAC. .. versionadded:: 2015.8.2 """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import logging import os import re import salt.utils.path - -# Import Salt libs from salt.exceptions import CommandExecutionError -# Import 3rd-party libs -from salt.ext import six -from salt.ext.six.moves import map, range - log = logging.getLogger(__name__) __proxyenabled__ = ["fx2"] @@ -78,15 +69,15 @@ def __execute_cmd( if module.startswith("ALL_"): modswitch = "-a " + module[module.index("_") + 1 : len(module)].lower() else: - modswitch = "-m {0}".format(module) + modswitch = "-m {}".format(module) else: modswitch = "" if not host: # This is a local call - cmd = __salt__["cmd.run_all"]("racadm {0} {1}".format(command, modswitch)) + cmd = __salt__["cmd.run_all"]("racadm {} {}".format(command, modswitch)) else: cmd = __salt__["cmd.run_all"]( - "racadm -r {0} -u {1} -p {2} {3} {4}".format( + "racadm -r {} -u {} -p {} {} {}".format( host, admin_username, admin_password, command, modswitch ), output_loglevel="quiet", @@ -109,15 +100,15 @@ def __execute_ret( if module == "ALL": modswitch = "-a " else: - modswitch = "-m {0}".format(module) + modswitch = "-m {}".format(module) else: modswitch = "" if not host: # This is a local call - cmd = __salt__["cmd.run_all"]("racadm {0} {1}".format(command, modswitch)) + cmd = __salt__["cmd.run_all"]("racadm {} {}".format(command, modswitch)) else: cmd = __salt__["cmd.run_all"]( - "racadm -r {0} -u {1} -p {2} {3} {4}".format( + "racadm -r {} -u {} -p {} {} {}".format( host, admin_username, admin_password, command, modswitch ), output_loglevel="quiet", @@ -162,7 +153,7 @@ def get_dns_dracname(host=None, admin_username=None, admin_password=None): def set_dns_dracname(name, host=None, admin_username=None, admin_password=None): ret = __execute_ret( - "set iDRAC.NIC.DNSRacName {0}".format(name), + "set iDRAC.NIC.DNSRacName {}".format(name), host=host, admin_username=admin_username, admin_password=admin_password, @@ -265,7 +256,7 @@ def network_info(host=None, admin_username=None, admin_password=None, module=Non if module not in inv.get("switch") and module not in inv.get("server"): cmd = {} cmd["retcode"] = -1 - cmd["stdout"] = "No module {0} found.".format(module) + cmd["stdout"] = "No module {} found.".format(module) return cmd cmd = __execute_ret( @@ -302,7 +293,7 @@ def nameservers(ns, host=None, admin_username=None, admin_password=None, module= for i in range(1, len(ns) + 1): if not __execute_cmd( - "config -g cfgLanNetworking -o " "cfgDNSServer{0} {1}".format(i, ns[i - 1]), + "config -g cfgLanNetworking -o " "cfgDNSServer{} {}".format(i, ns[i - 1]), host=host, admin_username=admin_username, admin_password=admin_password, @@ -341,7 +332,7 @@ def syslog( module=None, ): return __execute_cmd( - "config -g cfgRemoteHosts -o " "cfgRhostsSyslogServer1 {0}".format(server), + "config -g cfgRemoteHosts -o " "cfgRhostsSyslogServer1 {}".format(server), host=host, admin_username=admin_username, admin_password=admin_password, @@ -395,7 +386,7 @@ def list_users(host=None, admin_username=None, admin_password=None, module=None) for idx in range(1, 17): cmd = __execute_ret( - "getconfig -g " "cfgUserAdmin -i {0}".format(idx), + "getconfig -g " "cfgUserAdmin -i {}".format(idx), host=host, admin_username=admin_username, admin_password=admin_password, @@ -443,7 +434,7 @@ def delete_user( if uid: return __execute_cmd( - "config -g cfgUserAdmin -o " 'cfgUserAdminUserName -i {0} ""'.format(uid), + "config -g cfgUserAdmin -o " 'cfgUserAdminUserName -i {} ""'.format(uid), host=host, admin_username=admin_username, admin_password=admin_password, @@ -497,7 +488,7 @@ def change_password( if uid: return __execute_cmd( "config -g cfgUserAdmin -o " - "cfgUserAdminPassword -i {0} {1}".format(uid, password), + "cfgUserAdminPassword -i {} {}".format(uid, password), host=host, admin_username=admin_username, admin_password=admin_password, @@ -530,7 +521,7 @@ def deploy_password( on that then setting the password is much quicker. """ return __execute_cmd( - "deploy -u {0} -p {1}".format(username, password), + "deploy -u {} -p {}".format(username, password), host=host, admin_username=admin_username, admin_password=admin_password, @@ -553,7 +544,7 @@ def deploy_snmp(snmp, host=None, admin_username=None, admin_password=None, modul """ return __execute_cmd( - "deploy -v SNMPv2 {0} ro".format(snmp), + "deploy -v SNMPv2 {} ro".format(snmp), host=host, admin_username=admin_username, admin_password=admin_password, @@ -600,7 +591,7 @@ def create_user( log.warning("racadm: user '%s' already exists", username) return False - for idx in six.iterkeys(users): + for idx in users.keys(): _uids.add(users[idx]["index"]) uid = sorted(list(set(range(2, 12)) - _uids), reverse=True).pop() @@ -608,7 +599,7 @@ def create_user( # Create user account first if not __execute_cmd( "config -g cfgUserAdmin -o " - "cfgUserAdminUserName -i {0} {1}".format(uid, username), + "cfgUserAdminUserName -i {} {}".format(uid, username), host=host, admin_username=admin_username, admin_password=admin_password, @@ -630,7 +621,7 @@ def create_user( # Enable users admin if not __execute_cmd( - "config -g cfgUserAdmin -o " "cfgUserAdminEnable -i {0} 1".format(uid) + "config -g cfgUserAdmin -o " "cfgUserAdminEnable -i {} 1".format(uid) ): delete_user(username, uid) return False @@ -691,7 +682,7 @@ def set_permissions( return __execute_cmd( "config -g cfgUserAdmin -o " - "cfgUserAdminPrivilege -i {0} 0x{1:08X}".format(uid, permission), + "cfgUserAdminPrivilege -i {} 0x{:08X}".format(uid, permission), host=host, admin_username=admin_username, admin_password=admin_password, @@ -711,7 +702,7 @@ def set_snmp(community, host=None, admin_username=None, admin_password=None): salt dell dracr.set_snmp public """ return __execute_cmd( - "config -g cfgOobSnmp -o " "cfgOobSnmpAgentCommunity {0}".format(community), + "config -g cfgOobSnmp -o " "cfgOobSnmpAgentCommunity {}".format(community), host=host, admin_username=admin_username, admin_password=admin_password, @@ -734,7 +725,7 @@ def set_network( admin_username=root admin_password=calvin host=192.168.1.1 """ return __execute_cmd( - "setniccfg -s {0} {1} {2}".format( + "setniccfg -s {} {} {}".format( ip, netmask, gateway, @@ -775,7 +766,7 @@ def server_power( """ return __execute_cmd( - "serveraction {0}".format(status), + "serveraction {}".format(status), host=host, admin_username=admin_username, admin_password=admin_password, @@ -1065,7 +1056,7 @@ def get_slotname(slot, host=None, admin_username=None, admin_password=None): ) # The keys for this dictionary are strings, not integers, so convert the # argument to a string - slot = six.text_type(slot) + slot = str(slot) return slots[slot]["slotname"] @@ -1097,7 +1088,7 @@ def set_slotname(slot, name, host=None, admin_username=None, admin_password=None """ return __execute_cmd( - "config -g cfgServerInfo -o cfgServerName -i {0} {1}".format(slot, name), + "config -g cfgServerInfo -o cfgServerName -i {} {}".format(slot, name), host=host, admin_username=admin_username, admin_password=admin_password, @@ -1129,7 +1120,7 @@ def set_chassis_name(name, host=None, admin_username=None, admin_password=None): """ return __execute_cmd( - "setsysinfo -c chassisname {0}".format(name), + "setsysinfo -c chassisname {}".format(name), host=host, admin_username=admin_username, admin_password=admin_password, @@ -1229,27 +1220,21 @@ def inventory(host=None, admin_username=None, admin_password=None): line = re.split(" +", l.strip()) if in_server: - ret["server"][line[0]] = dict( - (k, v) - for d in map(mapit, fields["server"], line) - for (k, v) in d.items() - ) + ret["server"][line[0]] = { + k: v for d in map(mapit, fields["server"], line) for (k, v) in d.items() + } if in_switch: - ret["switch"][line[0]] = dict( - (k, v) - for d in map(mapit, fields["switch"], line) - for (k, v) in d.items() - ) + ret["switch"][line[0]] = { + k: v for d in map(mapit, fields["switch"], line) for (k, v) in d.items() + } if in_cmc: - ret["cmc"][line[0]] = dict( - (k, v) for d in map(mapit, fields["cmc"], line) for (k, v) in d.items() - ) + ret["cmc"][line[0]] = { + k: v for d in map(mapit, fields["cmc"], line) for (k, v) in d.items() + } if in_chassis: - ret["chassis"][line[0]] = dict( - (k, v) - for d in map(mapit, fields["chassis"], line) - for k, v in d.items() - ) + ret["chassis"][line[0]] = { + k: v for d in map(mapit, fields["chassis"], line) for k, v in d.items() + } return ret @@ -1279,7 +1264,7 @@ def set_chassis_location(location, host=None, admin_username=None, admin_passwor """ return __execute_cmd( - "setsysinfo -c chassislocation {0}".format(location), + "setsysinfo -c chassislocation {}".format(location), host=host, admin_username=admin_username, admin_password=admin_password, @@ -1382,7 +1367,7 @@ def set_general( cfg_sec, cfg_var, val, host=None, admin_username=None, admin_password=None ): return __execute_cmd( - "config -g {0} -o {1} {2}".format(cfg_sec, cfg_var, val), + "config -g {} -o {} {}".format(cfg_sec, cfg_var, val), host=host, admin_username=admin_username, admin_password=admin_password, @@ -1391,7 +1376,7 @@ def set_general( def get_general(cfg_sec, cfg_var, host=None, admin_username=None, admin_password=None): ret = __execute_ret( - "getconfig -g {0} -o {1}".format(cfg_sec, cfg_var), + "getconfig -g {} -o {}".format(cfg_sec, cfg_var), host=host, admin_username=admin_username, admin_password=admin_password, @@ -1472,7 +1457,7 @@ def _update_firmware(cmd, host=None, admin_username=None, admin_password=None): def bare_rac_cmd(cmd, host=None, admin_username=None, admin_password=None): ret = __execute_ret( - "{0}".format(cmd), + "{}".format(cmd), host=host, admin_username=admin_username, admin_password=admin_password, @@ -1502,13 +1487,13 @@ def update_firmware(filename, host=None, admin_username=None, admin_password=Non """ if os.path.exists(filename): return _update_firmware( - "update -f {0}".format(filename), + "update -f {}".format(filename), host=None, admin_username=None, admin_password=None, ) else: - raise CommandExecutionError("Unable to find firmware file {0}".format(filename)) + raise CommandExecutionError("Unable to find firmware file {}".format(filename)) def update_firmware_nfs_or_cifs( @@ -1547,13 +1532,13 @@ def update_firmware_nfs_or_cifs( """ if os.path.exists(filename): return _update_firmware( - "update -f {0} -l {1}".format(filename, share), + "update -f {} -l {}".format(filename, share), host=None, admin_username=None, admin_password=None, ) else: - raise CommandExecutionError("Unable to find firmware file {0}".format(filename)) + raise CommandExecutionError("Unable to find firmware file {}".format(filename)) # def get_idrac_nic() diff --git a/salt/modules/drbd.py b/salt/modules/drbd.py index ca2b2f9a780..71a56425e95 100644 --- a/salt/modules/drbd.py +++ b/salt/modules/drbd.py @@ -1,13 +1,9 @@ -# -*- coding: utf-8 -*- """ DRBD administration module """ -from __future__ import absolute_import, print_function, unicode_literals import logging -from salt.ext import six - log = logging.getLogger(__name__) @@ -57,8 +53,7 @@ def _analyse_status_type(line): ret = switch.get(spaces, "UNKNOWN") - # isinstance(ret, str) only works when run directly, calling need unicode(six) - if isinstance(ret, six.text_type): + if isinstance(ret, str): return ret for x in ret: diff --git a/salt/modules/dummyproxy_pkg.py b/salt/modules/dummyproxy_pkg.py index 6fc90be14c6..c1f07e44398 100644 --- a/salt/modules/dummyproxy_pkg.py +++ b/salt/modules/dummyproxy_pkg.py @@ -1,15 +1,11 @@ -# -*- coding: utf-8 -*- """ Package support for the dummy proxy used by the test suite """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import logging import salt.utils.data import salt.utils.platform -from salt.ext import six log = logging.getLogger(__name__) @@ -98,9 +94,9 @@ def installed( p = __proxy__["dummy.package_status"](name) if version is None: if "ret" in p: - return six.text_type(p["ret"]) + return str(p["ret"]) else: return True else: if p is not None: - return version == six.text_type(p) + return version == str(p) diff --git a/salt/modules/dummyproxy_service.py b/salt/modules/dummyproxy_service.py index 26ff95cd0a5..f328c13905a 100644 --- a/salt/modules/dummyproxy_service.py +++ b/salt/modules/dummyproxy_service.py @@ -1,13 +1,9 @@ -# -*- coding: utf-8 -*- """ Provide the service module for the dummy proxy used in integration tests """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import logging -# Import Salt libs import salt.utils.platform log = logging.getLogger(__name__) diff --git a/salt/modules/eix.py b/salt/modules/eix.py index 2d9e3192cff..f308ab765bf 100644 --- a/salt/modules/eix.py +++ b/salt/modules/eix.py @@ -1,10 +1,7 @@ -# -*- coding: utf-8 -*- """ Support for Eix """ -from __future__ import absolute_import, print_function, unicode_literals -# Import salt libs import salt.utils.path diff --git a/salt/modules/eselect.py b/salt/modules/eselect.py index e31b55c4d7c..0355a632d11 100644 --- a/salt/modules/eselect.py +++ b/salt/modules/eselect.py @@ -1,14 +1,10 @@ -# -*- coding: utf-8 -*- """ Support for eselect, Gentoo's configuration and management tool. """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import logging -# Import salt libs import salt.utils.path log = logging.getLogger(__name__) @@ -54,7 +50,7 @@ def exec_action( salt '*' eselect.exec_action php update action_parameter='apache2' """ out = __salt__["cmd.run"]( - "eselect --brief --colour=no {0} {1} {2} {3}".format( + "eselect --brief --colour=no {} {} {} {}".format( module, module_parameter or "", action, action_parameter or "" ), python_shell=False, @@ -198,7 +194,7 @@ def set_target(module, target, module_parameter=None, action_parameter=None): salt '*' eselect.set_target kernel linux-3.17.5-gentoo """ if action_parameter: - action_parameter = "{0} {1}".format(action_parameter, target) + action_parameter = "{} {}".format(action_parameter, target) else: action_parameter = target diff --git a/salt/modules/esxcluster.py b/salt/modules/esxcluster.py index 14e36f975f7..59dfcd6bf0f 100644 --- a/salt/modules/esxcluster.py +++ b/salt/modules/esxcluster.py @@ -1,10 +1,7 @@ -# -*- coding: utf-8 -*- """ Module used to access the esxcluster proxy connection methods """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import logging import salt.utils.platform diff --git a/salt/modules/esxdatacenter.py b/salt/modules/esxdatacenter.py index 985c23135a9..619a587a65f 100644 --- a/salt/modules/esxdatacenter.py +++ b/salt/modules/esxdatacenter.py @@ -1,10 +1,7 @@ -# -*- coding: utf-8 -*- """ Module used to access the esxdatacenter proxy connection methods """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import logging import salt.utils.platform diff --git a/salt/modules/esxi.py b/salt/modules/esxi.py index 2473b51d998..628e246e5ce 100644 --- a/salt/modules/esxi.py +++ b/salt/modules/esxi.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Glues the VMware vSphere Execution Module to the VMware ESXi Proxy Minions to the :mod:`esxi proxymodule `. @@ -27,12 +26,9 @@ type manor. """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import logging -# Import Salt libs import salt.utils.platform log = logging.getLogger(__name__) diff --git a/salt/modules/esxvm.py b/salt/modules/esxvm.py index f242591c1f0..40639dd3e3e 100644 --- a/salt/modules/esxvm.py +++ b/salt/modules/esxvm.py @@ -1,14 +1,10 @@ -# -*- coding: utf-8 -*- """ Module used to access the esx proxy connection methods """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import logging -# Import Salt libs import salt.utils.platform log = logging.getLogger(__name__) diff --git a/salt/modules/freebsd_update.py b/salt/modules/freebsd_update.py index d2b175bc272..3256ac0b0d6 100644 --- a/salt/modules/freebsd_update.py +++ b/salt/modules/freebsd_update.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Support for freebsd-update utility on FreeBSD. @@ -9,15 +8,11 @@ Support for freebsd-update utility on FreeBSD. :platform: FreeBSD """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import logging -# Import salt libs import salt.utils.path from salt.exceptions import CommandNotFoundError -from salt.ext import six log = logging.getLogger(__name__) @@ -61,24 +56,24 @@ def _cmd(**kwargs): params = [] if "basedir" in kwargs: - params.append("-b {0}".format(kwargs["basedir"])) + params.append("-b {}".format(kwargs["basedir"])) if "workdir" in kwargs: - params.append("-d {0}".format(kwargs["workdir"])) + params.append("-d {}".format(kwargs["workdir"])) if "conffile" in kwargs: - params.append("-f {0}".format(kwargs["conffile"])) + params.append("-f {}".format(kwargs["conffile"])) if "force" in kwargs: params.append("-F") if "key" in kwargs: - params.append("-k {0}".format(kwargs["key"])) + params.append("-k {}".format(kwargs["key"])) if "newrelease" in kwargs: - params.append("-r {0}".format(kwargs["newrelease"])) + params.append("-r {}".format(kwargs["newrelease"])) if "server" in kwargs: - params.append("-s {0}".format(kwargs["server"])) + params.append("-s {}".format(kwargs["server"])) if "address" in kwargs: - params.append("-t {0}".format(kwargs["address"])) + params.append("-t {}".format(kwargs["address"])) if params: - return "{0} {1}".format(update_cmd, " ".join(params)) + return "{} {}".format(update_cmd, " ".join(params)) return update_cmd @@ -113,12 +108,12 @@ def _wrapper(orig, pre="", post="", err_=None, run_args=None, **kwargs): res = __salt__["cmd.run_all"](cmd_str) if isinstance(err_, dict): # copy return values if asked to - for k, v in six.itermitems(res): + for k, v in res.items(): err_[k] = v if "retcode" in res and res["retcode"] != 0: msg = " ".join([x for x in (res["stdout"], res["stderr"]) if x]) - ret = 'Unable to run "{0}" with run_args="{1}". Error: {2}'.format( + ret = 'Unable to run "{}" with run_args="{}". Error: {}'.format( cmd_str, run_args, msg ) log.error(ret) @@ -199,7 +194,7 @@ def update(**kwargs): return ret if "stdout" in err_: stdout[mode] = err_["stdout"] - return "\n".join(["{0}: {1}".format(k, v) for (k, v) in six.iteritems(stdout)]) + return "\n".join(["{}: {}".format(k, v) for (k, v) in stdout.items()]) def ids(**kwargs): diff --git a/salt/modules/freebsdjail.py b/salt/modules/freebsdjail.py index 94211fbd43f..fc3c3ce04f3 100644 --- a/salt/modules/freebsdjail.py +++ b/salt/modules/freebsdjail.py @@ -1,16 +1,12 @@ -# -*- coding: utf-8 -*- """ The jail module for FreeBSD """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import os import re import subprocess -# Import salt libs import salt.utils.args import salt.utils.files import salt.utils.stringutils @@ -42,7 +38,7 @@ def start(jail=""): salt '*' jail.start [] """ - cmd = "service jail onestart {0}".format(jail) + cmd = "service jail onestart {}".format(jail) return not __salt__["cmd.retcode"](cmd) @@ -56,7 +52,7 @@ def stop(jail=""): salt '*' jail.stop [] """ - cmd = "service jail onestop {0}".format(jail) + cmd = "service jail onestop {}".format(jail) return not __salt__["cmd.retcode"](cmd) @@ -70,7 +66,7 @@ def restart(jail=""): salt '*' jail.restart [] """ - cmd = "service jail onerestart {0}".format(jail) + cmd = "service jail onerestart {}".format(jail) return not __salt__["cmd.retcode"](cmd) @@ -149,7 +145,7 @@ def show_config(jail): line = salt.utils.stringutils.to_unicode(line) if not line.strip(): continue - if not line.startswith("jail_{0}_".format(jail)): + if not line.startswith("jail_{}_".format(jail)): continue key, value = line.split("=") ret[key.split("_", 2)[2]] = value.split('"')[1] diff --git a/salt/modules/freebsdkmod.py b/salt/modules/freebsdkmod.py index 037ba11b155..4e9e6549838 100644 --- a/salt/modules/freebsdkmod.py +++ b/salt/modules/freebsdkmod.py @@ -1,14 +1,10 @@ -# -*- coding: utf-8 -*- """ Module to manage FreeBSD kernel modules """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import os import re -# Import salt libs import salt.utils.files # Define the module's virtual name @@ -90,7 +86,7 @@ def _set_persistent_module(mod): if not mod or mod in mod_list(True) or mod not in available(): return set() __salt__["file.append"](_LOADER_CONF, _LOAD_MODULE.format(mod)) - return set([mod]) + return {mod} def _remove_persistent_module(mod, comment): @@ -106,7 +102,7 @@ def _remove_persistent_module(mod, comment): else: __salt__["file.sed"](_LOADER_CONF, _MODULE_RE.format(mod), "") - return set([mod]) + return {mod} def available(): @@ -204,7 +200,7 @@ def load(mod, persist=False): salt '*' kmod.load bhyve """ pre_mods = lsmod() - response = __salt__["cmd.run_all"]("kldload {0}".format(mod), python_shell=False) + response = __salt__["cmd.run_all"]("kldload {}".format(mod), python_shell=False) if response["retcode"] == 0: post_mods = lsmod() mods = _new_mods(pre_mods, post_mods) @@ -220,7 +216,7 @@ def load(mod, persist=False): # It's compiled into the kernel return [None] else: - return "Module {0} not found".format(mod) + return "Module {} not found".format(mod) def is_loaded(mod): @@ -257,7 +253,7 @@ def remove(mod, persist=False, comment=True): salt '*' kmod.remove vmm """ pre_mods = lsmod() - res = __salt__["cmd.run_all"]("kldunload {0}".format(mod), python_shell=False) + res = __salt__["cmd.run_all"]("kldunload {}".format(mod), python_shell=False) if res["retcode"] == 0: post_mods = lsmod() mods = _rm_mods(pre_mods, post_mods) @@ -266,4 +262,4 @@ def remove(mod, persist=False, comment=True): persist_mods = _remove_persistent_module(mod, comment) return sorted(list(mods | persist_mods)) else: - return "Error removing module {0}: {1}".format(mod, res["stderr"]) + return "Error removing module {}: {}".format(mod, res["stderr"]) diff --git a/salt/modules/freebsdports.py b/salt/modules/freebsdports.py index f8ec0e1f223..3ab53e24f80 100644 --- a/salt/modules/freebsdports.py +++ b/salt/modules/freebsdports.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Install software from the FreeBSD ``ports(7)`` system @@ -14,21 +13,16 @@ this module exclusively from the command line. salt minion-id ports.config security/nmap IPV6=off salt minion-id ports.install security/nmap """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import fnmatch import logging import os import re -# Import salt libs import salt.utils.data import salt.utils.files import salt.utils.path from salt.exceptions import CommandExecutionError, SaltInvocationError -from salt.ext import six -from salt.ext.six import string_types log = logging.getLogger(__name__) @@ -64,14 +58,14 @@ def _check_portname(name): Check if portname is valid and whether or not the directory exists in the ports tree. """ - if not isinstance(name, string_types) or "/" not in name: + if not isinstance(name, str) or "/" not in name: raise SaltInvocationError( - "Invalid port name '{0}' (category required)".format(name) + "Invalid port name '{}' (category required)".format(name) ) path = os.path.join("/usr/ports", name) if not os.path.isdir(path): - raise SaltInvocationError("Path '{0}' does not exist".format(path)) + raise SaltInvocationError("Path '{}' does not exist".format(path)) return path @@ -115,7 +109,7 @@ def _write_options(name, configuration): try: os.makedirs(dirname) except OSError as exc: - raise CommandExecutionError("Unable to make {0}: {1}".format(dirname, exc)) + raise CommandExecutionError("Unable to make {}: {}".format(dirname, exc)) with salt.utils.files.fopen(os.path.join(dirname, "options"), "w") as fp_: sorted_options = list(conf_ptr) @@ -146,7 +140,7 @@ def _normalize(val): """ if isinstance(val, bool): return "on" if val else "off" - return six.text_type(val).lower() + return str(val).lower() def install(name, clean=True): @@ -276,7 +270,7 @@ def showconfig(name, default=False, dict_return=False): error = result if error: - msg = "Error running 'make showconfig' for {0}: {1}".format(name, error) + msg = "Error running 'make showconfig' for {}: {}".format(name, error) log.error(msg) raise SaltInvocationError(msg) @@ -334,33 +328,27 @@ def config(name, reset=False, **kwargs): if not configuration: raise CommandExecutionError( - "Unable to get port configuration for '{0}'".format(name) + "Unable to get port configuration for '{}'".format(name) ) # Get top-level key for later reference pkg = next(iter(configuration)) conf_ptr = configuration[pkg] - opts = dict( - (six.text_type(x), _normalize(kwargs[x])) - for x in kwargs - if not x.startswith("_") - ) + opts = {str(x): _normalize(kwargs[x]) for x in kwargs if not x.startswith("_")} bad_opts = [x for x in opts if x not in conf_ptr] if bad_opts: raise SaltInvocationError( - "The following opts are not valid for port {0}: {1}".format( + "The following opts are not valid for port {}: {}".format( name, ", ".join(bad_opts) ) ) - bad_vals = [ - "{0}={1}".format(x, y) for x, y in six.iteritems(opts) if y not in ("on", "off") - ] + bad_vals = ["{}={}".format(x, y) for x, y in opts.items() if y not in ("on", "off")] if bad_vals: raise SaltInvocationError( - "The following key/value pairs are invalid: {0}".format(", ".join(bad_vals)) + "The following key/value pairs are invalid: {}".format(", ".join(bad_vals)) ) conf_ptr.update(opts) @@ -392,7 +380,7 @@ def update(extract=False): result = __salt__["cmd.run_all"](_portsnap() + ["fetch"], python_shell=False) if not result["retcode"] == 0: raise CommandExecutionError( - "Unable to fetch ports snapshot: {0}".format(result["stderr"]) + "Unable to fetch ports snapshot: {}".format(result["stderr"]) ) ret = [] @@ -408,20 +396,20 @@ def update(extract=False): except AttributeError: new_port_count = 0 - ret.append("Applied {0} new patches".format(patch_count)) - ret.append("Fetched {0} new ports or files".format(new_port_count)) + ret.append("Applied {} new patches".format(patch_count)) + ret.append("Fetched {} new ports or files".format(new_port_count)) if extract: result = __salt__["cmd.run_all"](_portsnap() + ["extract"], python_shell=False) if not result["retcode"] == 0: raise CommandExecutionError( - "Unable to extract ports snapshot {0}".format(result["stderr"]) + "Unable to extract ports snapshot {}".format(result["stderr"]) ) result = __salt__["cmd.run_all"](_portsnap() + ["update"], python_shell=False) if not result["retcode"] == 0: raise CommandExecutionError( - "Unable to apply ports snapshot: {0}".format(result["stderr"]) + "Unable to apply ports snapshot: {}".format(result["stderr"]) ) __context__.pop("ports.list_all", None) @@ -469,7 +457,7 @@ def search(name): Takes a while to run """ - name = six.text_type(name) + name = str(name) all_ports = list_all() if "/" in name: if name.count("/") > 1: diff --git a/salt/modules/freebsdservice.py b/salt/modules/freebsdservice.py index 9ccc7310f62..3fdc4a4f4f7 100644 --- a/salt/modules/freebsdservice.py +++ b/salt/modules/freebsdservice.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ The service module for FreeBSD @@ -8,19 +7,14 @@ The service module for FreeBSD *'service.start' is not available*), see :ref:`here `. """ -from __future__ import absolute_import, print_function, unicode_literals import fnmatch - -# Import python libs import logging import os import re import salt.utils.decorators as decorators import salt.utils.files - -# Import salt libs import salt.utils.path from salt.exceptions import CommandNotFoundError @@ -61,7 +55,7 @@ def _cmd(jail=None): jexec = salt.utils.path.which("jexec") if not jexec: raise CommandNotFoundError("'jexec' command not found") - service = "{0} {1} {2}".format(jexec, jail, service) + service = "{} {} {}".format(jexec, jail, service) return service @@ -77,7 +71,7 @@ def _get_jail_path(jail): jls = salt.utils.path.which("jls") if not jls: raise CommandNotFoundError("'jls' command not found") - jails = __salt__["cmd.run_stdout"]("{0} -n jid name path".format(jls)) + jails = __salt__["cmd.run_stdout"]("{} -n jid name path".format(jls)) for j in jails.splitlines(): jid, jname, path = (x.split("=")[1].strip() for x in j.split()) if jid == jail or jname == jail: @@ -94,10 +88,10 @@ def _get_rcscript(name, jail=None): Support for jail (representing jid or jail name) keyword argument in kwargs """ - cmd = "{0} -r".format(_cmd(jail)) + cmd = "{} -r".format(_cmd(jail)) prf = _get_jail_path(jail) if jail else "" for line in __salt__["cmd.run_stdout"](cmd, python_shell=False).splitlines(): - if line.endswith("{0}{1}".format(os.path.sep, name)): + if line.endswith("{}{}".format(os.path.sep, name)): return os.path.join(prf, line.lstrip(os.path.sep)) return None @@ -114,7 +108,7 @@ def _get_rcvar(name, jail=None): log.error("Service %s not found", name) return False - cmd = "{0} {1} rcvar".format(_cmd(jail), name) + cmd = "{} {} rcvar".format(_cmd(jail), name) for line in __salt__["cmd.run_stdout"](cmd, python_shell=False).splitlines(): if '_enable="' not in line: @@ -142,14 +136,14 @@ def get_enabled(jail=None): ret = [] service = _cmd(jail) prf = _get_jail_path(jail) if jail else "" - for svc in __salt__["cmd.run"]("{0} -e".format(service)).splitlines(): + for svc in __salt__["cmd.run"]("{} -e".format(service)).splitlines(): ret.append(os.path.basename(svc)) # This is workaround for bin/173454 bug for svc in get_all(jail): if svc in ret: continue - if not os.path.exists("{0}/etc/rc.conf.d/{1}".format(prf, svc)): + if not os.path.exists("{}/etc/rc.conf.d/{}".format(prf, svc)): continue if enabled(svc, jail=jail): ret.append(svc) @@ -205,12 +199,12 @@ def _switch(name, on, **kwargs): # pylint: disable=C0103 # pylint: disable=C01 config = kwargs.get( "config", __salt__["config.option"]( - "service.config", default="{0}/etc/rc.conf".format(chroot) + "service.config", default="{}/etc/rc.conf".format(chroot) ), ) if not config: - rcdir = "{0}/etc/rc.conf.d".format(chroot) + rcdir = "{}/etc/rc.conf.d".format(chroot) if not os.path.exists(rcdir) or not os.path.isdir(rcdir): log.error("%s not exists", rcdir) return False @@ -228,17 +222,17 @@ def _switch(name, on, **kwargs): # pylint: disable=C0103 # pylint: disable=C01 with salt.utils.files.fopen(config, "r") as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) - if not line.startswith("{0}=".format(rcvar)): + if not line.startswith("{}=".format(rcvar)): nlines.append(line) continue rest = line[len(line.split()[0]) :] # keep comments etc - nlines.append('{0}="{1}"{2}'.format(rcvar, val, rest)) + nlines.append('{}="{}"{}'.format(rcvar, val, rest)) edited = True if not edited: # Ensure that the file ends in a \n if len(nlines) > 1 and nlines[-1][-1] != "\n": - nlines[-1] = "{0}\n".format(nlines[-1]) - nlines.append('{0}="{1}"\n'.format(rcvar, val)) + nlines[-1] = "{}\n".format(nlines[-1]) + nlines.append('{}="{}"\n'.format(rcvar, val)) with salt.utils.files.fopen(config, "w") as ofile: nlines = [salt.utils.stringutils.to_str(_l) for _l in nlines] @@ -323,7 +317,7 @@ def enabled(name, **kwargs): log.error("Service %s not found", name) return False - cmd = "{0} {1} rcvar".format(_cmd(jail), name) + cmd = "{} {} rcvar".format(_cmd(jail), name) for line in __salt__["cmd.run_stdout"](cmd, python_shell=False).splitlines(): if '_enable="' not in line: @@ -400,7 +394,7 @@ def get_all(jail=None): """ ret = [] service = _cmd(jail) - for srv in __salt__["cmd.run"]("{0} -l".format(service)).splitlines(): + for srv in __salt__["cmd.run"]("{} -l".format(service)).splitlines(): if not srv.isupper(): ret.append(srv) return sorted(ret) @@ -420,7 +414,7 @@ def start(name, jail=None): salt '*' service.start """ - cmd = "{0} {1} onestart".format(_cmd(jail), name) + cmd = "{} {} onestart".format(_cmd(jail), name) return not __salt__["cmd.retcode"](cmd, python_shell=False) @@ -438,7 +432,7 @@ def stop(name, jail=None): salt '*' service.stop """ - cmd = "{0} {1} onestop".format(_cmd(jail), name) + cmd = "{} {} onestop".format(_cmd(jail), name) return not __salt__["cmd.retcode"](cmd, python_shell=False) @@ -456,7 +450,7 @@ def restart(name, jail=None): salt '*' service.restart """ - cmd = "{0} {1} onerestart".format(_cmd(jail), name) + cmd = "{} {} onerestart".format(_cmd(jail), name) return not __salt__["cmd.retcode"](cmd, python_shell=False) @@ -474,7 +468,7 @@ def reload_(name, jail=None): salt '*' service.reload """ - cmd = "{0} {1} onereload".format(_cmd(jail), name) + cmd = "{} {} onereload".format(_cmd(jail), name) return not __salt__["cmd.retcode"](cmd, python_shell=False) @@ -513,7 +507,7 @@ def status(name, sig=None, jail=None): services = [name] results = {} for service in services: - cmd = "{0} {1} onestatus".format(_cmd(jail), service) + cmd = "{} {} onestatus".format(_cmd(jail), service) results[service] = not __salt__["cmd.retcode"]( cmd, python_shell=False, ignore_retcode=True ) diff --git a/salt/modules/freezer.py b/salt/modules/freezer.py index c69f782179f..3df2479fcc5 100644 --- a/salt/modules/freezer.py +++ b/salt/modules/freezer.py @@ -1,19 +1,15 @@ -# -*- coding: utf-8 -*- - """ :maintainer: Alberto Planas :maturity: new :depends: None :platform: Linux """ -from __future__ import absolute_import, print_function, unicode_literals import logging import os import salt.utils.json as json from salt.exceptions import CommandExecutionError -from salt.ext.six.moves import zip from salt.utils.args import clean_kwargs from salt.utils.files import fopen diff --git a/salt/modules/gem.py b/salt/modules/gem.py index 4a2186b2db2..700c302c888 100644 --- a/salt/modules/gem.py +++ b/salt/modules/gem.py @@ -1,15 +1,10 @@ -# -*- coding: utf-8 -*- """ Manage ruby gems. """ -from __future__ import absolute_import, print_function, unicode_literals import logging - -# Import python libs import re -# Import Salt libs import salt.utils.itertools import salt.utils.platform from salt.exceptions import CommandExecutionError diff --git a/salt/modules/gentoo_service.py b/salt/modules/gentoo_service.py index 416f5f6a47c..5a35ba0fcbd 100644 --- a/salt/modules/gentoo_service.py +++ b/salt/modules/gentoo_service.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Top level package command wrapper, used to translate the os detected by grains to the correct service manager @@ -10,16 +9,12 @@ to the correct service manager `. """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import fnmatch import logging import re import salt.utils.odict as odict - -# Import salt libs import salt.utils.systemd # Set up logging @@ -93,11 +88,11 @@ def _disable_delta(name, requested_runlevels): def _service_cmd(*args): - return "/etc/init.d/{0} {1}".format(args[0], " ".join(args[1:])) + return "/etc/init.d/{} {}".format(args[0], " ".join(args[1:])) def _enable_disable_cmd(name, command, runlevels=()): - return "rc-update {0} {1} {2}".format( + return "rc-update {} {} {}".format( command, name, " ".join(sorted(runlevels)) ).strip() @@ -177,7 +172,7 @@ def get_all(): (enabled_services, disabled_services) = _get_service_list( include_enabled=True, include_disabled=True ) - enabled_services.update(dict([(s, []) for s in disabled_services])) + enabled_services.update({s: [] for s in disabled_services}) return odict.OrderedDict(enabled_services) diff --git a/salt/modules/gentoolkitmod.py b/salt/modules/gentoolkitmod.py index cc78c371149..729a0a17a53 100644 --- a/salt/modules/gentoolkitmod.py +++ b/salt/modules/gentoolkitmod.py @@ -1,15 +1,12 @@ -# -*- coding: utf-8 -*- """ Support for Gentoolkit """ -from __future__ import absolute_import, print_function, unicode_literals import os HAS_GENTOOLKIT = False -# Import third party libs try: from gentoolkit.eclean import search, clean, cli, exclude as excludemod @@ -51,7 +48,7 @@ def revdep_rebuild(lib=None): """ cmd = "revdep-rebuild -i --quiet --no-progress" if lib is not None: - cmd += " --library={0}".format(lib) + cmd += " --library={}".format(lib) return __salt__["cmd.retcode"](cmd, python_shell=False) == 0 @@ -63,7 +60,7 @@ def _pretty_size(size): while units and size >= 1000: size = size / 1024.0 units.pop() - return "{0}{1}".format(round(size, 1), units[-1]) + return "{}{}".format(round(size, 1), units[-1]) def _parse_exclude(exclude_file): @@ -138,7 +135,7 @@ def eclean_dist( try: exclude = _parse_exclude(exclude_file) except excludemod.ParseExcludeFileException as e: - ret = {e: "Invalid exclusion file: {0}".format(exclude_file)} + ret = {e: "Invalid exclusion file: {}".format(exclude_file)} return ret if time_limit != 0: @@ -222,7 +219,7 @@ def eclean_pkg( try: exclude = _parse_exclude(exclude_file) except excludemod.ParseExcludeFileException as e: - ret = {e: "Invalid exclusion file: {0}".format(exclude_file)} + ret = {e: "Invalid exclusion file: {}".format(exclude_file)} return ret if time_limit != 0: diff --git a/salt/modules/github.py b/salt/modules/github.py index c5811fdf8ef..3a9406a8440 100644 --- a/salt/modules/github.py +++ b/salt/modules/github.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Module for interacting with the GitHub v3 API. @@ -30,18 +29,12 @@ For example: allow_repo_privacy_changes: False """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import logging import salt.utils.http - -# Import Salt Libs from salt.exceptions import CommandExecutionError -from salt.ext import six -# Import third party libs HAS_LIBS = False try: # pylint: disable=no-name-in-module @@ -88,13 +81,13 @@ def _get_config_value(profile, config_name): if not config: raise CommandExecutionError( "Authentication information could not be found for the " - "'{0}' profile.".format(profile) + "'{}' profile.".format(profile) ) config_value = config.get(config_name) if config_value is None: raise CommandExecutionError( - "The '{0}' parameter was not found in the '{1}' " + "The '{}' parameter was not found in the '{}' " "profile.".format(config_name, profile) ) @@ -106,7 +99,7 @@ def _get_client(profile): Return the GitHub client, cached into __context__ for performance """ token = _get_config_value(profile, "token") - key = "github.{0}:{1}".format(token, _get_config_value(profile, "org_name")) + key = "github.{}:{}".format(token, _get_config_value(profile, "org_name")) if key not in __context__: __context__[key] = github.Github(token, per_page=100) @@ -125,7 +118,7 @@ def _get_members(organization, params=None): def _get_repos(profile, params=None, ignore_cache=False): # Use cache when no params are given org_name = _get_config_value(profile, "org_name") - key = "github.{0}:repos".format(org_name) + key = "github.{}:repos".format(org_name) if key not in __context__ or ignore_cache or params is not None: org_name = _get_config_value(profile, "org_name") @@ -149,7 +142,7 @@ def _get_repos(profile, params=None, ignore_cache=False): next_result.append(repo) # Cache a copy of each repo for single lookups - repo_key = "github.{0}:{1}:repo_info".format(org_name, repo.name.lower()) + repo_key = "github.{}:{}:repo_info".format(org_name, repo.name.lower()) __context__[repo_key] = _repo_to_dict(repo) __context__[key] = next_result @@ -177,7 +170,7 @@ def list_users(profile="github", ignore_cache=False): salt myminion github.list_users profile='my-github-profile' """ org_name = _get_config_value(profile, "org_name") - key = "github.{0}:users".format(org_name) + key = "github.{}:users".format(org_name) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization(org_name) @@ -348,7 +341,7 @@ def get_issue(issue_number, repo_name=None, profile="github", output="min"): repo_name = _get_config_value(profile, "repo_name") action = "/".join(["repos", org_name, repo_name]) - command = "issues/" + six.text_type(issue_number) + command = "issues/" + str(issue_number) ret = {} issue_data = _query(profile, action=action, command=command) @@ -402,7 +395,7 @@ def get_issue_comments( repo_name = _get_config_value(profile, "repo_name") action = "/".join(["repos", org_name, repo_name]) - command = "/".join(["issues", six.text_type(issue_number), "comments"]) + command = "/".join(["issues", str(issue_number), "comments"]) args = {} if since: @@ -691,7 +684,7 @@ def get_milestone( action = "/".join(["repos", org_name, repo_name]) if number: - command = "milestones/" + six.text_type(number) + command = "milestones/" + str(number) milestone_data = _query(profile, action=action, command=command) milestone_id = milestone_data.get("id") if output == "full": @@ -705,7 +698,7 @@ def get_milestone( else: milestones = get_milestones(repo_name=repo_name, profile=profile, output=output) - for key, val in six.iteritems(milestones): + for key, val in milestones.items(): if val.get("title") == name: ret[key] = val return ret @@ -760,7 +753,7 @@ def get_repo_info(repo_name, profile="github", ignore_cache=False): """ org_name = _get_config_value(profile, "org_name") - key = "github.{0}:{1}:repo_info".format( + key = "github.{}:{}:repo_info".format( _get_config_value(profile, "org_name"), repo_name.lower() ) @@ -780,7 +773,7 @@ def get_repo_info(repo_name, profile="github", ignore_cache=False): __context__[key] = ret except github.UnknownObjectException: raise CommandExecutionError( - "The '{0}' repository under the '{1}' organization could not " + "The '{}' repository under the '{}' organization could not " "be found.".format(repo_name, org_name) ) return __context__[key] @@ -813,7 +806,7 @@ def get_repo_teams(repo_name, profile="github"): repo = client.get_repo("/".join([org_name, repo_name])) except github.UnknownObjectException: raise CommandExecutionError( - "The '{0}' repository under the '{1}' organization could not " + "The '{}' repository under the '{}' organization could not " "be found.".format(repo_name, org_name) ) try: @@ -824,7 +817,7 @@ def get_repo_teams(repo_name, profile="github"): ) except github.UnknownObjectException: raise CommandExecutionError( - "Unable to retrieve teams for repository '{0}' under the '{1}' " + "Unable to retrieve teams for repository '{}' under the '{}' " "organization.".format(repo_name, org_name) ) return ret @@ -971,7 +964,7 @@ def add_repo( "license_template": license_template, } parameters = {"name": name} - for param_name, param_value in six.iteritems(given_params): + for param_name, param_value in given_params.items(): if param_value is not None: parameters[param_name] = param_value @@ -1039,7 +1032,7 @@ def edit_repo( if private is not None and not allow_private_change: raise CommandExecutionError( "The private field is set to be changed for " - "repo {0} but allow_repo_privacy_changes " + "repo {} but allow_repo_privacy_changes " "disallows this.".format(name) ) @@ -1057,7 +1050,7 @@ def edit_repo( "has_downloads": has_downloads, } parameters = {"name": name} - for param_name, param_value in six.iteritems(given_params): + for param_name, param_value in given_params.items(): if param_value is not None: parameters[param_name] = param_value @@ -1479,7 +1472,7 @@ def list_members_without_mfa(profile="github", ignore_cache=False): .. versionadded:: 2016.11.0 """ - key = "github.{0}:non_mfa_users".format(_get_config_value(profile, "org_name")) + key = "github.{}:non_mfa_users".format(_get_config_value(profile, "org_name")) if key not in __context__ or ignore_cache: client = _get_client(profile) @@ -1636,7 +1629,7 @@ def list_teams(profile="github", ignore_cache=False): .. versionadded:: 2016.11.0 """ - key = "github.{0}:teams".format(_get_config_value(profile, "org_name")) + key = "github.{}:teams".format(_get_config_value(profile, "org_name")) if key not in __context__ or ignore_cache: client = _get_client(profile) @@ -1840,7 +1833,7 @@ def _query( url += action if command: - url += "/{0}".format(command) + url += "/{}".format(command) log.debug("GitHub URL: %s", url) @@ -1893,7 +1886,7 @@ def _query( complete_result = complete_result + result["dict"] else: raise CommandExecutionError( - "GitHub Response Error: {0}".format(result.get("error")) + "GitHub Response Error: {}".format(result.get("error")) ) try: diff --git a/salt/modules/glanceng.py b/salt/modules/glanceng.py index 3e9c152dc09..6ca68f612da 100644 --- a/salt/modules/glanceng.py +++ b/salt/modules/glanceng.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Glance module for interacting with OpenStack Glance @@ -26,7 +25,6 @@ Example configuration identity_api_version: 3 """ -from __future__ import absolute_import, print_function, unicode_literals HAS_SHADE = False try: diff --git a/salt/modules/gnomedesktop.py b/salt/modules/gnomedesktop.py index 333780506ea..abefaeb8586 100644 --- a/salt/modules/gnomedesktop.py +++ b/salt/modules/gnomedesktop.py @@ -1,15 +1,11 @@ -# -*- coding: utf-8 -*- """ GNOME implementations """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import logging import re -# Import Salt libs import salt.utils.path try: @@ -20,7 +16,6 @@ except ImportError: HAS_PWD = False -# Import 3rd-party libs try: from gi.repository import Gio, GLib # pylint: disable=W0611 @@ -50,7 +45,7 @@ def __virtual__(): ) -class _GSettings(object): +class _GSettings: def __init__(self, user, schema, key): self.SCHEMA = schema self.KEY = key @@ -83,7 +78,7 @@ class _GSettings(object): cmd = self.gsetting_command + ["get", str(self.SCHEMA), str(self.KEY)] environ = {} - environ["XDG_RUNTIME_DIR"] = "/run/user/{0}".format(uid) + environ["XDG_RUNTIME_DIR"] = "/run/user/{}".format(uid) result = __salt__["cmd.run_all"]( cmd, runas=user, env=environ, python_shell=False ) @@ -108,12 +103,12 @@ class _GSettings(object): log.info("User does not exist") result = {} result["retcode"] = 1 - result["stdout"] = "User {0} does not exist".format(user) + result["stdout"] = "User {} does not exist".format(user) return result cmd = self.gsetting_command + ["set", self.SCHEMA, self.KEY, value] environ = {} - environ["XDG_RUNTIME_DIR"] = "/run/user/{0}".format(uid) + environ["XDG_RUNTIME_DIR"] = "/run/user/{}".format(uid) result = __salt__["cmd.run_all"]( cmd, runas=user, env=environ, python_shell=False ) diff --git a/salt/modules/google_chat.py b/salt/modules/google_chat.py index ff4af53ad22..faf83eb0891 100644 --- a/salt/modules/google_chat.py +++ b/salt/modules/google_chat.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Module for sending messages to google chat. @@ -9,8 +8,6 @@ where you would like the message to be sent, see: https://developers.google.com/hangouts/chat/how-tos/webhooks """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals import json diff --git a/salt/modules/grafana4.py b/salt/modules/grafana4.py index 402c92f0059..e9d840ab9c3 100644 --- a/salt/modules/grafana4.py +++ b/salt/modules/grafana4.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Module for working with the Grafana v4 API @@ -20,9 +19,6 @@ Module for working with the Grafana v4 API grafana_password: admin grafana_timeout: 3 """ -from __future__ import absolute_import, print_function, unicode_literals - -from salt.ext.six import string_types try: import requests @@ -44,7 +40,7 @@ def __virtual__(): else: return ( False, - 'The "{0}" module could not be loaded: ' + 'The "{}" module could not be loaded: ' '"requests" is not installed.'.format(__virtualname__), ) @@ -52,7 +48,7 @@ def __virtual__(): def _get_headers(profile): headers = {"Content-type": "application/json"} if profile.get("grafana_token", False): - headers["Authorization"] = "Bearer {0}".format(profile["grafana_token"]) + headers["Authorization"] = "Bearer {}".format(profile["grafana_token"]) return headers @@ -78,10 +74,10 @@ def get_users(profile="grafana"): salt '*' grafana4.get_users """ - if isinstance(profile, string_types): + if isinstance(profile, str): profile = __salt__["config.option"](profile) response = requests.get( - "{0}/api/users".format(profile["grafana_url"]), + "{}/api/users".format(profile["grafana_url"]), auth=_get_auth(profile), headers=_get_headers(profile), timeout=profile.get("grafana_timeout", 3), @@ -132,10 +128,10 @@ def get_user_data(userid, profile="grafana"): salt '*' grafana4.get_user_data """ - if isinstance(profile, string_types): + if isinstance(profile, str): profile = __salt__["config.option"](profile) response = requests.get( - "{0}/api/users/{1}".format(profile["grafana_url"], userid), + "{}/api/users/{}".format(profile["grafana_url"], userid), auth=_get_auth(profile), headers=_get_headers(profile), timeout=profile.get("grafana_timeout", 3), @@ -171,10 +167,10 @@ def create_user(profile="grafana", **kwargs): salt '*' grafana4.create_user login= password= email= """ - if isinstance(profile, string_types): + if isinstance(profile, str): profile = __salt__["config.option"](profile) response = requests.post( - "{0}/api/admin/users".format(profile["grafana_url"]), + "{}/api/admin/users".format(profile["grafana_url"]), json=kwargs, auth=_get_auth(profile), headers=_get_headers(profile), @@ -211,10 +207,10 @@ def update_user(userid, profile="grafana", **kwargs): salt '*' grafana4.update_user login= email= """ - if isinstance(profile, string_types): + if isinstance(profile, str): profile = __salt__["config.option"](profile) response = requests.put( - "{0}/api/users/{1}".format(profile["grafana_url"], userid), + "{}/api/users/{}".format(profile["grafana_url"], userid), json=kwargs, auth=_get_auth(profile), headers=_get_headers(profile), @@ -245,10 +241,10 @@ def update_user_password(userid, profile="grafana", **kwargs): salt '*' grafana4.update_user_password password= """ - if isinstance(profile, string_types): + if isinstance(profile, str): profile = __salt__["config.option"](profile) response = requests.put( - "{0}/api/admin/users/{1}/password".format(profile["grafana_url"], userid), + "{}/api/admin/users/{}/password".format(profile["grafana_url"], userid), json=kwargs, auth=_get_auth(profile), headers=_get_headers(profile), @@ -279,10 +275,10 @@ def update_user_permissions(userid, profile="grafana", **kwargs): salt '*' grafana4.update_user_permissions isGrafanaAdmin= """ - if isinstance(profile, string_types): + if isinstance(profile, str): profile = __salt__["config.option"](profile) response = requests.put( - "{0}/api/admin/users/{1}/permissions".format(profile["grafana_url"], userid), + "{}/api/admin/users/{}/permissions".format(profile["grafana_url"], userid), json=kwargs, auth=_get_auth(profile), headers=_get_headers(profile), @@ -310,10 +306,10 @@ def delete_user(userid, profile="grafana"): salt '*' grafana4.delete_user """ - if isinstance(profile, string_types): + if isinstance(profile, str): profile = __salt__["config.option"](profile) response = requests.delete( - "{0}/api/admin/users/{1}".format(profile["grafana_url"], userid), + "{}/api/admin/users/{}".format(profile["grafana_url"], userid), auth=_get_auth(profile), headers=_get_headers(profile), timeout=profile.get("grafana_timeout", 3), @@ -340,10 +336,10 @@ def get_user_orgs(userid, profile="grafana"): salt '*' grafana4.get_user_orgs """ - if isinstance(profile, string_types): + if isinstance(profile, str): profile = __salt__["config.option"](profile) response = requests.get( - "{0}/api/users/{1}/orgs".format(profile["grafana_url"], userid), + "{}/api/users/{}/orgs".format(profile["grafana_url"], userid), auth=_get_auth(profile), headers=_get_headers(profile), timeout=profile.get("grafana_timeout", 3), @@ -373,10 +369,10 @@ def delete_user_org(userid, orgid, profile="grafana"): salt '*' grafana4.delete_user_org """ - if isinstance(profile, string_types): + if isinstance(profile, str): profile = __salt__["config.option"](profile) response = requests.delete( - "{0}/api/orgs/{1}/users/{2}".format(profile["grafana_url"], orgid, userid), + "{}/api/orgs/{}/users/{}".format(profile["grafana_url"], orgid, userid), auth=_get_auth(profile), headers=_get_headers(profile), timeout=profile.get("grafana_timeout", 3), @@ -400,10 +396,10 @@ def get_orgs(profile="grafana"): salt '*' grafana4.get_orgs """ - if isinstance(profile, string_types): + if isinstance(profile, str): profile = __salt__["config.option"](profile) response = requests.get( - "{0}/api/orgs".format(profile["grafana_url"]), + "{}/api/orgs".format(profile["grafana_url"]), auth=_get_auth(profile), headers=_get_headers(profile), timeout=profile.get("grafana_timeout", 3), @@ -430,10 +426,10 @@ def get_org(name, profile="grafana"): salt '*' grafana4.get_org """ - if isinstance(profile, string_types): + if isinstance(profile, str): profile = __salt__["config.option"](profile) response = requests.get( - "{0}/api/orgs/name/{1}".format(profile["grafana_url"], name), + "{}/api/orgs/name/{}".format(profile["grafana_url"], name), auth=_get_auth(profile), headers=_get_headers(profile), timeout=profile.get("grafana_timeout", 3), @@ -460,11 +456,11 @@ def switch_org(orgname, profile="grafana"): salt '*' grafana4.switch_org """ - if isinstance(profile, string_types): + if isinstance(profile, str): profile = __salt__["config.option"](profile) org = get_org(orgname, profile) response = requests.post( - "{0}/api/user/using/{1}".format(profile["grafana_url"], org["id"]), + "{}/api/user/using/{}".format(profile["grafana_url"], org["id"]), auth=_get_auth(profile), headers=_get_headers(profile), timeout=profile.get("grafana_timeout", 3), @@ -491,12 +487,12 @@ def get_org_users(orgname=None, profile="grafana"): salt '*' grafana4.get_org_users """ - if isinstance(profile, string_types): + if isinstance(profile, str): profile = __salt__["config.option"](profile) if orgname: switch_org(orgname, profile) response = requests.get( - "{0}/api/org/users".format(profile["grafana_url"]), + "{}/api/org/users".format(profile["grafana_url"]), auth=_get_auth(profile), headers=_get_headers(profile), timeout=profile.get("grafana_timeout", 3), @@ -533,12 +529,12 @@ def create_org_user(orgname=None, profile="grafana", **kwargs): salt '*' grafana4.create_org_user loginOrEmail= role= """ - if isinstance(profile, string_types): + if isinstance(profile, str): profile = __salt__["config.option"](profile) if orgname: switch_org(orgname, profile) response = requests.post( - "{0}/api/org/users".format(profile["grafana_url"]), + "{}/api/org/users".format(profile["grafana_url"]), json=kwargs, auth=_get_auth(profile), headers=_get_headers(profile), @@ -579,12 +575,12 @@ def update_org_user(userid, orgname=None, profile="grafana", **kwargs): salt '*' grafana4.update_org_user loginOrEmail= role= """ - if isinstance(profile, string_types): + if isinstance(profile, str): profile = __salt__["config.option"](profile) if orgname: switch_org(orgname, profile) response = requests.patch( - "{0}/api/org/users/{1}".format(profile["grafana_url"], userid), + "{}/api/org/users/{}".format(profile["grafana_url"], userid), json=kwargs, auth=_get_auth(profile), headers=_get_headers(profile), @@ -615,12 +611,12 @@ def delete_org_user(userid, orgname=None, profile="grafana"): salt '*' grafana4.delete_org_user """ - if isinstance(profile, string_types): + if isinstance(profile, str): profile = __salt__["config.option"](profile) if orgname: switch_org(orgname, profile) response = requests.delete( - "{0}/api/org/users/{1}".format(profile["grafana_url"], userid), + "{}/api/org/users/{}".format(profile["grafana_url"], userid), auth=_get_auth(profile), headers=_get_headers(profile), timeout=profile.get("grafana_timeout", 3), @@ -647,12 +643,12 @@ def get_org_address(orgname=None, profile="grafana"): salt '*' grafana4.get_org_address """ - if isinstance(profile, string_types): + if isinstance(profile, str): profile = __salt__["config.option"](profile) if orgname: switch_org(orgname, profile) response = requests.get( - "{0}/api/org/address".format(profile["grafana_url"]), + "{}/api/org/address".format(profile["grafana_url"]), auth=_get_auth(profile), headers=_get_headers(profile), timeout=profile.get("grafana_timeout", 3), @@ -697,12 +693,12 @@ def update_org_address(orgname=None, profile="grafana", **kwargs): salt '*' grafana4.update_org_address country= """ - if isinstance(profile, string_types): + if isinstance(profile, str): profile = __salt__["config.option"](profile) if orgname: switch_org(orgname, profile) response = requests.put( - "{0}/api/org/address".format(profile["grafana_url"]), + "{}/api/org/address".format(profile["grafana_url"]), json=kwargs, auth=_get_auth(profile), headers=_get_headers(profile), @@ -730,12 +726,12 @@ def get_org_prefs(orgname=None, profile="grafana"): salt '*' grafana4.get_org_prefs """ - if isinstance(profile, string_types): + if isinstance(profile, str): profile = __salt__["config.option"](profile) if orgname: switch_org(orgname, profile) response = requests.get( - "{0}/api/org/preferences".format(profile["grafana_url"]), + "{}/api/org/preferences".format(profile["grafana_url"]), auth=_get_auth(profile), headers=_get_headers(profile), timeout=profile.get("grafana_timeout", 3), @@ -771,12 +767,12 @@ def update_org_prefs(orgname=None, profile="grafana", **kwargs): salt '*' grafana4.update_org_prefs theme= timezone= """ - if isinstance(profile, string_types): + if isinstance(profile, str): profile = __salt__["config.option"](profile) if orgname: switch_org(orgname, profile) response = requests.put( - "{0}/api/org/preferences".format(profile["grafana_url"]), + "{}/api/org/preferences".format(profile["grafana_url"]), json=kwargs, auth=_get_auth(profile), headers=_get_headers(profile), @@ -804,10 +800,10 @@ def create_org(profile="grafana", **kwargs): salt '*' grafana4.create_org """ - if isinstance(profile, string_types): + if isinstance(profile, str): profile = __salt__["config.option"](profile) response = requests.post( - "{0}/api/orgs".format(profile["grafana_url"]), + "{}/api/orgs".format(profile["grafana_url"]), json=kwargs, auth=_get_auth(profile), headers=_get_headers(profile), @@ -838,10 +834,10 @@ def update_org(orgid, profile="grafana", **kwargs): salt '*' grafana4.update_org name= """ - if isinstance(profile, string_types): + if isinstance(profile, str): profile = __salt__["config.option"](profile) response = requests.put( - "{0}/api/orgs/{1}".format(profile["grafana_url"], orgid), + "{}/api/orgs/{}".format(profile["grafana_url"], orgid), json=kwargs, auth=_get_auth(profile), headers=_get_headers(profile), @@ -869,10 +865,10 @@ def delete_org(orgid, profile="grafana"): salt '*' grafana4.delete_org """ - if isinstance(profile, string_types): + if isinstance(profile, str): profile = __salt__["config.option"](profile) response = requests.delete( - "{0}/api/orgs/{1}".format(profile["grafana_url"], orgid), + "{}/api/orgs/{}".format(profile["grafana_url"], orgid), auth=_get_auth(profile), headers=_get_headers(profile), timeout=profile.get("grafana_timeout", 3), @@ -899,12 +895,12 @@ def get_datasources(orgname=None, profile="grafana"): salt '*' grafana4.get_datasources """ - if isinstance(profile, string_types): + if isinstance(profile, str): profile = __salt__["config.option"](profile) if orgname: switch_org(orgname, profile) response = requests.get( - "{0}/api/datasources".format(profile["grafana_url"]), + "{}/api/datasources".format(profile["grafana_url"]), auth=_get_auth(profile), headers=_get_headers(profile), timeout=profile.get("grafana_timeout", 3), @@ -1003,12 +999,12 @@ def create_datasource(orgname=None, profile="grafana", **kwargs): salt '*' grafana4.create_datasource """ - if isinstance(profile, string_types): + if isinstance(profile, str): profile = __salt__["config.option"](profile) if orgname: switch_org(orgname, profile) response = requests.post( - "{0}/api/datasources".format(profile["grafana_url"]), + "{}/api/datasources".format(profile["grafana_url"]), json=kwargs, auth=_get_auth(profile), headers=_get_headers(profile), @@ -1081,10 +1077,10 @@ def update_datasource(datasourceid, orgname=None, profile="grafana", **kwargs): salt '*' grafana4.update_datasource """ - if isinstance(profile, string_types): + if isinstance(profile, str): profile = __salt__["config.option"](profile) response = requests.put( - "{0}/api/datasources/{1}".format(profile["grafana_url"], datasourceid), + "{}/api/datasources/{}".format(profile["grafana_url"], datasourceid), json=kwargs, auth=_get_auth(profile), headers=_get_headers(profile), @@ -1114,10 +1110,10 @@ def delete_datasource(datasourceid, orgname=None, profile="grafana"): salt '*' grafana4.delete_datasource """ - if isinstance(profile, string_types): + if isinstance(profile, str): profile = __salt__["config.option"](profile) response = requests.delete( - "{0}/api/datasources/{1}".format(profile["grafana_url"], datasourceid), + "{}/api/datasources/{}".format(profile["grafana_url"], datasourceid), auth=_get_auth(profile), headers=_get_headers(profile), timeout=profile.get("grafana_timeout", 3), @@ -1147,12 +1143,12 @@ def get_dashboard(slug, orgname=None, profile="grafana"): salt '*' grafana4.get_dashboard """ - if isinstance(profile, string_types): + if isinstance(profile, str): profile = __salt__["config.option"](profile) if orgname: switch_org(orgname, profile) response = requests.get( - "{0}/api/dashboards/db/{1}".format(profile["grafana_url"], slug), + "{}/api/dashboards/db/{}".format(profile["grafana_url"], slug), auth=_get_auth(profile), headers=_get_headers(profile), timeout=profile.get("grafana_timeout", 3), @@ -1185,12 +1181,12 @@ def delete_dashboard(slug, orgname=None, profile="grafana"): salt '*' grafana4.delete_dashboard """ - if isinstance(profile, string_types): + if isinstance(profile, str): profile = __salt__["config.option"](profile) if orgname: switch_org(orgname, profile) response = requests.delete( - "{0}/api/dashboards/db/{1}".format(profile["grafana_url"], slug), + "{}/api/dashboards/db/{}".format(profile["grafana_url"], slug), auth=_get_auth(profile), headers=_get_headers(profile), timeout=profile.get("grafana_timeout", 3), @@ -1223,12 +1219,12 @@ def create_update_dashboard(orgname=None, profile="grafana", **kwargs): salt '*' grafana4.create_update_dashboard dashboard= overwrite=True orgname= """ - if isinstance(profile, string_types): + if isinstance(profile, str): profile = __salt__["config.option"](profile) if orgname: switch_org(orgname, profile) response = requests.post( - "{0}/api/dashboards/db".format(profile.get("grafana_url")), + "{}/api/dashboards/db".format(profile.get("grafana_url")), json=kwargs, auth=_get_auth(profile), headers=_get_headers(profile), diff --git a/salt/modules/grub_legacy.py b/salt/modules/grub_legacy.py index 9271fda2c1a..7bb46f8be9a 100644 --- a/salt/modules/grub_legacy.py +++ b/salt/modules/grub_legacy.py @@ -1,15 +1,10 @@ -# -*- coding: utf-8 -*- """ Support for GRUB Legacy """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import os import salt.utils.decorators as decorators - -# Import salt libs import salt.utils.files from salt.exceptions import CommandExecutionError @@ -80,14 +75,14 @@ def conf(): if line.startswith("\n"): in_stanza = False if "title" in stanza: - stanza += "order {0}".format(pos) + stanza += "order {}".format(pos) pos += 1 stanzas.append(stanza) stanza = "" continue if line.strip().startswith("title"): if in_stanza: - stanza += "order {0}".format(pos) + stanza += "order {}".format(pos) pos += 1 stanzas.append(stanza) stanza = "" @@ -102,10 +97,10 @@ def conf(): if not line.endswith("\n"): line += "\n" stanza += line - stanza += "order {0}".format(pos) + stanza += "order {}".format(pos) pos += 1 stanzas.append(stanza) - except (IOError, OSError) as exc: + except OSError as exc: msg = "Could not read grub config: {0}" raise CommandExecutionError(msg.format(exc)) diff --git a/salt/modules/hadoop.py b/salt/modules/hadoop.py index 5f16226442a..df65ff9538e 100644 --- a/salt/modules/hadoop.py +++ b/salt/modules/hadoop.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Support for hadoop @@ -9,10 +8,7 @@ Support for hadoop """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals -# Import salt libs import salt.utils.path __authorized_modules__ = ["version", "namenode", "dfsadmin", "dfs", "fs"] diff --git a/salt/modules/haproxyconn.py b/salt/modules/haproxyconn.py index 2544d9498a6..fd9d71ed31e 100644 --- a/salt/modules/haproxyconn.py +++ b/salt/modules/haproxyconn.py @@ -1,12 +1,9 @@ -# -*- coding: utf-8 -*- """ Support for haproxy .. versionadded:: 2014.7.0 """ -# Import Python libs -from __future__ import absolute_import, generators, print_function, unicode_literals import logging import os @@ -50,9 +47,9 @@ def _get_conn(socket=DEFAULT_SOCKET_URL): """ Get connection to haproxy socket. """ - assert os.path.exists(socket), "{0} does not exist.".format(socket) + assert os.path.exists(socket), "{} does not exist.".format(socket) issock = os.stat(socket).st_mode - assert stat.S_ISSOCK(issock), "{0} is not a socket.".format(socket) + assert stat.S_ISSOCK(issock), "{} is not a socket.".format(socket) ha_conn = haproxy.conn.HaPConn(socket) return ha_conn diff --git a/salt/modules/helm.py b/salt/modules/helm.py index 0d0b4837247..19790726716 100644 --- a/salt/modules/helm.py +++ b/salt/modules/helm.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Interface with Helm @@ -33,16 +32,12 @@ Detailed Function Documentation ------------------------------- """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import copy import logging import re from salt.exceptions import CommandExecutionError - -# Import Salt libs from salt.serializers import json log = logging.getLogger(__name__) diff --git a/salt/modules/hg.py b/salt/modules/hg.py index 2817133525e..2835a531494 100644 --- a/salt/modules/hg.py +++ b/salt/modules/hg.py @@ -1,17 +1,12 @@ -# -*- coding: utf-8 -*- """ Support for the Mercurial SCM """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import logging import salt.utils.data import salt.utils.path - -# Import salt libs from salt.exceptions import CommandExecutionError log = logging.getLogger(__name__) @@ -28,7 +23,7 @@ def __virtual__(): def _ssh_flag(identity_path): - return ["--ssh", "ssh -i {0}".format(identity_path)] + return ["--ssh", "ssh -i {}".format(identity_path)] def revision(cwd, rev="tip", short=False, user=None): @@ -53,7 +48,7 @@ def revision(cwd, rev="tip", short=False, user=None): salt '*' hg.revision /path/to/repo mybranch """ - cmd = ["hg", "id", "-i", "--debug" if not short else "", "-r", "{0}".format(rev)] + cmd = ["hg", "id", "-i", "--debug" if not short else "", "-r", "{}".format(rev)] result = __salt__["cmd.run_all"](cmd, cwd=cwd, runas=user, python_shell=False) @@ -86,7 +81,7 @@ def describe(cwd, rev="tip", user=None): "hg", "log", "-r", - "{0}".format(rev), + "{}".format(rev), "--template", "'{{latesttag}}-{{latesttagdistance}}-{{node|short}}'", ] @@ -130,16 +125,16 @@ def archive(cwd, output, rev="tip", fmt=None, prefix=None, user=None): cmd = [ "hg", "archive", - "{0}".format(output), + "{}".format(output), "--rev", - "{0}".format(rev), + "{}".format(rev), ] if fmt: cmd.append("--type") - cmd.append("{0}".format(fmt)) + cmd.append("{}".format(fmt)) if prefix: cmd.append("--prefix") - cmd.append('"{0}"'.format(prefix)) + cmd.append('"{}"'.format(prefix)) return __salt__["cmd.run"](cmd, cwd=cwd, runas=user, python_shell=False) @@ -182,7 +177,7 @@ def pull(cwd, opts=None, user=None, identity=None, repository=None): ret = __salt__["cmd.run_all"](cmd, cwd=cwd, runas=user, python_shell=False) if ret["retcode"] != 0: raise CommandExecutionError( - "Hg command failed: {0}".format(ret.get("stderr", ret["stdout"])) + "Hg command failed: {}".format(ret.get("stderr", ret["stdout"])) ) return ret["stdout"] @@ -210,14 +205,14 @@ def update(cwd, rev, force=False, user=None): salt devserver1 hg.update /path/to/repo somebranch """ - cmd = ["hg", "update", "{0}".format(rev)] + cmd = ["hg", "update", "{}".format(rev)] if force: cmd.append("-C") ret = __salt__["cmd.run_all"](cmd, cwd=cwd, runas=user, python_shell=False) if ret["retcode"] != 0: raise CommandExecutionError( - "Hg command failed: {0}".format(ret.get("stderr", ret["stdout"])) + "Hg command failed: {}".format(ret.get("stderr", ret["stdout"])) ) return ret["stdout"] @@ -250,17 +245,17 @@ def clone(cwd, repository, opts=None, user=None, identity=None): salt '*' hg.clone /path/to/repo https://bitbucket.org/birkenfeld/sphinx """ - cmd = ["hg", "clone", "{0}".format(repository), "{0}".format(cwd)] + cmd = ["hg", "clone", "{}".format(repository), "{}".format(cwd)] if opts: for opt in opts.split(): - cmd.append("{0}".format(opt)) + cmd.append("{}".format(opt)) if identity: cmd.extend(_ssh_flag(identity)) ret = __salt__["cmd.run_all"](cmd, runas=user, python_shell=False) if ret["retcode"] != 0: raise CommandExecutionError( - "Hg command failed: {0}".format(ret.get("stderr", ret["stdout"])) + "Hg command failed: {}".format(ret.get("stderr", ret["stdout"])) ) return ret["stdout"] @@ -290,7 +285,7 @@ def status(cwd, opts=None, user=None): cmd = ["hg", "status"] if opts: for opt in opts.split(): - cmd.append("{0}".format(opt)) + cmd.append("{}".format(opt)) out = __salt__["cmd.run_stdout"](cmd, cwd=cwd, runas=user, python_shell=False) types = { "M": "modified", @@ -311,6 +306,6 @@ def status(cwd, opts=None, user=None): return ret if salt.utils.data.is_iter(cwd): - return dict((cwd, _status(cwd)) for cwd in cwd) + return {cwd: _status(cwd) for cwd in cwd} else: return _status(cwd) diff --git a/salt/modules/icinga2.py b/salt/modules/icinga2.py index 21db5fe2d74..ef222ced217 100644 --- a/salt/modules/icinga2.py +++ b/salt/modules/icinga2.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Module to provide icinga2 compatibility to salt. @@ -7,12 +6,9 @@ Module to provide icinga2 compatibility to salt. :depends: - icinga2 server """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import logging -# Import Salt libs import salt.utils.path import salt.utils.platform from salt.utils.icinga2 import get_certs_path @@ -75,9 +71,9 @@ def generate_cert(domain): "--cn", domain, "--key", - "{0}{1}.key".format(get_certs_path(), domain), + "{}{}.key".format(get_certs_path(), domain), "--cert", - "{0}{1}.crt".format(get_certs_path(), domain), + "{}{}.crt".format(get_certs_path(), domain), ], python_shell=False, ) @@ -104,11 +100,11 @@ def save_cert(domain, master): "pki", "save-cert", "--key", - "{0}{1}.key".format(get_certs_path(), domain), + "{}{}.key".format(get_certs_path(), domain), "--cert", - "{0}{1}.cert".format(get_certs_path(), domain), + "{}{}.cert".format(get_certs_path(), domain), "--trustedcert", - "{0}trusted-master.crt".format(get_certs_path()), + "{}trusted-master.crt".format(get_certs_path()), "--host", master, ], @@ -144,13 +140,13 @@ def request_cert(domain, master, ticket, port): "--ticket", ticket, "--key", - "{0}{1}.key".format(get_certs_path(), domain), + "{}{}.key".format(get_certs_path(), domain), "--cert", - "{0}{1}.crt".format(get_certs_path(), domain), + "{}{}.crt".format(get_certs_path(), domain), "--trustedcert", - "{0}trusted-master.crt".format(get_certs_path()), + "{}trusted-master.crt".format(get_certs_path()), "--ca", - "{0}ca.crt".format(get_certs_path()), + "{}ca.crt".format(get_certs_path()), ], python_shell=False, ) @@ -186,7 +182,7 @@ def node_setup(domain, master, ticket): "--master_host", master, "--trustedcert", - "{0}trusted-master.crt".format(get_certs_path()), + "{}trusted-master.crt".format(get_certs_path()), ], python_shell=False, ) diff --git a/salt/modules/ifttt.py b/salt/modules/ifttt.py index f2fe6d4f9fc..3c49b25a111 100644 --- a/salt/modules/ifttt.py +++ b/salt/modules/ifttt.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Support for IFTTT @@ -12,13 +11,10 @@ Requires an ``api_key`` in ``/etc/salt/minion``: secret_key: '280d4699-a817-4719-ba6f-ca56e573e44f' """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import logging import time -# Import salt libs import salt.utils.http import salt.utils.json @@ -43,7 +39,7 @@ def _query(event=None, method="GET", args=None, header_dict=None, data=None): secret_key = __salt__["config.get"]("ifttt.secret_key") or __salt__["config.get"]( "ifttt:secret_key" ) - path = "https://maker.ifttt.com/trigger/{0}/with/key/{1}".format(event, secret_key) + path = "https://maker.ifttt.com/trigger/{}/with/key/{}".format(event, secret_key) if header_dict is None: header_dict = {"Content-type": "application/json"} diff --git a/salt/modules/influxdb08mod.py b/salt/modules/influxdb08mod.py index d04cb7e7584..8a46c7d4ef6 100644 --- a/salt/modules/influxdb08mod.py +++ b/salt/modules/influxdb08mod.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ InfluxDB - A distributed time series database @@ -22,8 +21,6 @@ version 0.5-0.8) overwrite options passed into pillar. """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import logging diff --git a/salt/modules/influxdbmod.py b/salt/modules/influxdbmod.py index 53dace02e54..42e71bfeec5 100644 --- a/salt/modules/influxdbmod.py +++ b/salt/modules/influxdbmod.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ InfluxDB - A distributed time series database @@ -27,7 +26,6 @@ version 0.9+) would override ``user`` and ``password`` while still using the defaults for ``host`` and ``port``. """ -from __future__ import absolute_import, print_function, unicode_literals import collections import logging @@ -368,11 +366,9 @@ def get_retention_policy(database, name, **client_args): try: return next( - ( - p - for p in client.get_list_retention_policies(database) - if p.get("name") == name - ) + p + for p in client.get_list_retention_policies(database) + if p.get("name") == name ) except StopIteration: return {} @@ -609,7 +605,7 @@ def get_continuous_query(database, name, **client_args): try: for db, cqs in client.query("SHOW CONTINUOUS QUERIES").items(): if db[0] == database: - return next((cq for cq in cqs if cq.get("name") == name)) + return next(cq for cq in cqs if cq.get("name") == name) except StopIteration: return {} return {} @@ -679,7 +675,7 @@ def drop_continuous_query(database, name, **client_args): """ client = _client(**client_args) - query = "DROP CONTINUOUS QUERY {0} ON {1}".format(name, database) + query = "DROP CONTINUOUS QUERY {} ON {}".format(name, database) client.query(query) return True diff --git a/salt/modules/infoblox.py b/salt/modules/infoblox.py index d04d0ef6d4f..a779b6322f9 100644 --- a/salt/modules/infoblox.py +++ b/salt/modules/infoblox.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ This module have been tested on infoblox API v1.2.1, other versions of the API are likly workable. @@ -32,19 +31,14 @@ API documents can be found on your infoblox server at: api_key=passs """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import time -# Import Salt libs -from salt.ext import six - IMPORT_ERR = None try: import libinfoblox except Exception as exc: # pylint: disable=broad-except - IMPORT_ERR = six.text_type(exc) + IMPORT_ERR = str(exc) __virtualname__ = "infoblox" @@ -67,7 +61,7 @@ def _get_config(**api_opts): "api_key": "", } if "__salt__" in globals(): - config_key = "{0}.config".format(__virtualname__) + config_key = "{}.config".format(__virtualname__) config.update(__salt__["config.get"](config_key, {})) # pylint: disable=C0201 for k in set(config.keys()) & set(api_opts.keys()): @@ -78,7 +72,7 @@ def _get_config(**api_opts): def _get_infoblox(**api_opts): config = _get_config(**api_opts) # TODO: perhaps cache in __opts__ - cache_key = "infoblox_session_{0},{1},{2}".format( + cache_key = "infoblox_session_{},{},{}".format( config["api_url"], config["api_user"], config["api_key"] ) if cache_key in cache: @@ -149,7 +143,7 @@ def update_object(objref, data, **api_opts): salt-call infoblox.update_object objref=[ref_of_object] data={} """ if "__opts__" in globals() and __opts__["test"]: - return {"Test": "Would attempt to update object: {0}".format(objref)} + return {"Test": "Would attempt to update object: {}".format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.update_object(objref, data) @@ -165,7 +159,7 @@ def delete_object(objref, **api_opts): salt-call infoblox.delete_object objref=[ref_of_object] """ if "__opts__" in globals() and __opts__["test"]: - return {"Test": "Would attempt to delete object: {0}".format(objref)} + return {"Test": "Would attempt to delete object: {}".format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.delete_object(objref) @@ -181,7 +175,7 @@ def create_object(object_type, data, **api_opts): salt-call infoblox.update_object object_type=record:host data={} """ if "__opts__" in globals() and __opts__["test"]: - return {"Test": "Would attempt to create object: {0}".format(object_type)} + return {"Test": "Would attempt to create object: {}".format(object_type)} infoblox = _get_infoblox(**api_opts) return infoblox.create_object(object_type, data) diff --git a/salt/modules/inspectlib/__init__.py b/salt/modules/inspectlib/__init__.py index 21a539ab520..9632a581874 100644 --- a/salt/modules/inspectlib/__init__.py +++ b/salt/modules/inspectlib/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright 2015 SUSE LLC # @@ -14,18 +13,14 @@ # See the License for the specific language governing permissions and # limitations under the License. -# Import Python libs -from __future__ import absolute_import import os from salt.modules.inspectlib.dbhandle import DBHandle - -# Import Salt libs from salt.modules.inspectlib.exceptions import InspectorSnapshotException -class EnvLoader(object): +class EnvLoader: """ Load environment. """ diff --git a/salt/modules/inspectlib/dbhandle.py b/salt/modules/inspectlib/dbhandle.py index b5d20b13056..7ebb2b0dc14 100644 --- a/salt/modules/inspectlib/dbhandle.py +++ b/salt/modules/inspectlib/dbhandle.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright 2015 SUSE LLC # @@ -15,7 +14,6 @@ # limitations under the License. # Import Python LIbs -from __future__ import absolute_import from salt.modules.inspectlib.entities import ( AllowedDir, @@ -27,7 +25,7 @@ from salt.modules.inspectlib.entities import ( from salt.modules.inspectlib.fsdb import CsvDB -class DBHandleBase(object): +class DBHandleBase: """ Handle for the *volatile* database, which serves the purpose of caching the inspected data. This database can be destroyed or corrupted, so it should @@ -95,7 +93,7 @@ class DBHandle(DBHandleBase): Keep singleton. """ if not cls.__instance: - cls.__instance = super(DBHandle, cls).__new__(cls) + cls.__instance = super().__new__(cls) return cls.__instance def __init__(self, path): diff --git a/salt/modules/inspectlib/entities.py b/salt/modules/inspectlib/entities.py index 196c6d01fe4..319204bbf3a 100644 --- a/salt/modules/inspectlib/entities.py +++ b/salt/modules/inspectlib/entities.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright 2016 SUSE LLC # @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. -from __future__ import absolute_import from salt.modules.inspectlib.fsdb import CsvDBEntity diff --git a/salt/modules/inspectlib/exceptions.py b/salt/modules/inspectlib/exceptions.py index 6852b7fea41..ca15a221329 100644 --- a/salt/modules/inspectlib/exceptions.py +++ b/salt/modules/inspectlib/exceptions.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright 2015 SUSE LLC # diff --git a/salt/modules/inspectlib/fsdb.py b/salt/modules/inspectlib/fsdb.py index 2874932b0a4..489fde56849 100644 --- a/salt/modules/inspectlib/fsdb.py +++ b/salt/modules/inspectlib/fsdb.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright 2016 SUSE LLC # @@ -18,7 +17,6 @@ :codeauthor: Bo Maryniuk """ -from __future__ import absolute_import, with_statement import csv import datetime @@ -28,11 +26,10 @@ import re import shutil import sys -from salt.ext.six.moves import zip from salt.utils.odict import OrderedDict -class CsvDBEntity(object): +class CsvDBEntity: """ Serializable object for the table. """ @@ -46,7 +43,7 @@ class CsvDBEntity(object): return [getattr(self, attr) for attr in description] -class CsvDB(object): +class CsvDB: """ File-based CSV database. This database is in-memory operating relatively small plain text csv files. @@ -273,7 +270,7 @@ class CsvDB(object): def _validate_object(self, obj): descr = self._tables.get(obj._TABLE) if descr is None: - raise Exception("Table {0} not found.".format(obj._TABLE)) + raise Exception("Table {} not found.".format(obj._TABLE)) return obj._serialize(self._tables[obj._TABLE]) def __criteria(self, obj, matches=None, mt=None, lt=None, eq=None): diff --git a/salt/modules/inspectlib/query.py b/salt/modules/inspectlib/query.py index ed0167f6787..079cc291725 100644 --- a/salt/modules/inspectlib/query.py +++ b/salt/modules/inspectlib/query.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright 2015 SUSE LLC # @@ -14,14 +13,11 @@ # See the License for the specific language governing permissions and # limitations under the License. -# Import Python Libs -from __future__ import absolute_import import logging import os import time -# Import Salt Libs import salt.utils.files import salt.utils.fsutils import salt.utils.network @@ -32,14 +28,14 @@ from salt.modules.inspectlib.exceptions import InspectorQueryException, SIExcept log = logging.getLogger(__name__) -class SysInfo(object): +class SysInfo: """ System information. """ def __init__(self, systype): if systype.lower() == "solaris": - raise SIException("Platform {0} not (yet) supported.".format(systype)) + raise SIException("Platform {} not (yet) supported.".format(systype)) def _grain(self, grain): """ @@ -51,9 +47,9 @@ class SysInfo(object): """ Get a size of a disk. """ - out = __salt__["cmd.run_all"]("df {0}".format(device)) + out = __salt__["cmd.run_all"]("df {}".format(device)) if out["retcode"]: - msg = "Disk size info error: {0}".format(out["stderr"]) + msg = "Disk size info error: {}".format(out["stderr"]) log.error(msg) raise SIException(msg) @@ -110,7 +106,7 @@ class SysInfo(object): """ out = __salt__["cmd.run_all"]("vmstat -s") if out["retcode"]: - raise SIException("Memory info error: {0}".format(out["stderr"])) + raise SIException("Memory info error: {}".format(out["stderr"])) ret = dict() for line in out["stdout"].split(os.linesep): @@ -182,13 +178,13 @@ class Query(EnvLoader): """ if scope and scope not in self.SCOPES: raise InspectorQueryException( - "Unknown scope: {0}. Must be one of: {1}".format( + "Unknown scope: {}. Must be one of: {}".format( repr(scope), ", ".join(self.SCOPES) ) ) elif not scope: raise InspectorQueryException( - "Scope cannot be empty. Must be one of: {0}".format( + "Scope cannot be empty. Must be one of: {}".format( ", ".join(self.SCOPES) ) ) @@ -468,13 +464,13 @@ class Query(EnvLoader): fmt = fmt.lower() if fmt == "b": - return "{0} Bytes".format(size) + return "{} Bytes".format(size) elif fmt == "kb": - return "{0} Kb".format(round((float(size) / 0x400), 2)) + return "{} Kb".format(round((float(size) / 0x400), 2)) elif fmt == "mb": - return "{0} Mb".format(round((float(size) / 0x400 / 0x400), 2)) + return "{} Mb".format(round((float(size) / 0x400 / 0x400), 2)) elif fmt == "gb": - return "{0} Gb".format(round((float(size) / 0x400 / 0x400 / 0x400), 2)) + return "{} Gb".format(round((float(size) / 0x400 / 0x400 / 0x400), 2)) filter = kwargs.get("filter") offset = kwargs.get("offset", 0) @@ -482,7 +478,7 @@ class Query(EnvLoader): timeformat = kwargs.get("time", "tz") if timeformat not in ["ticks", "tz"]: raise InspectorQueryException( - 'Unknown "{0}" value for parameter "time"'.format(timeformat) + 'Unknown "{}" value for parameter "time"'.format(timeformat) ) tfmt = ( lambda param: timeformat == "tz" @@ -493,14 +489,14 @@ class Query(EnvLoader): size_fmt = kwargs.get("size") if size_fmt is not None and size_fmt.lower() not in ["b", "kb", "mb", "gb"]: raise InspectorQueryException( - 'Unknown "{0}" value for parameter "size". ' + 'Unknown "{}" value for parameter "size". ' "Should be either B, Kb, Mb or Gb".format(timeformat) ) owners = kwargs.get("owners", "id") if owners not in ["name", "id"]: raise InspectorQueryException( - 'Unknown "{0}" value for parameter "owners". ' + 'Unknown "{}" value for parameter "owners". ' "Should be either name or id (default)".format(owners) ) @@ -511,7 +507,7 @@ class Query(EnvLoader): for i_type in incl_type: if i_type not in ["directory", "dir", "d", "file", "f", "link", "l"]: raise InspectorQueryException( - 'Unknown "{0}" values for parameter "type". ' + 'Unknown "{}" values for parameter "type". ' "Should be comma separated one or more of " "dir, file and/or link.".format(", ".join(incl_type)) ) diff --git a/salt/modules/jboss7.py b/salt/modules/jboss7.py index 1d8ca1649a2..180a0525472 100644 --- a/salt/modules/jboss7.py +++ b/salt/modules/jboss7.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Module for managing JBoss AS 7 through the CLI interface. @@ -22,19 +21,13 @@ Example: """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import logging import re -# Import Salt libs import salt.utils.dictdiffer as dictdiffer from salt.exceptions import SaltInvocationError -# Import 3rd-party libs -from salt.ext import six - log = logging.getLogger(__name__) __func_alias__ = {"reload_": "reload"} @@ -210,7 +203,7 @@ def create_datasource(jboss_config, name, datasource_properties, profile=None): def __get_properties_assignment_string(datasource_properties, ds_resource_description): assignment_strings = [] ds_attributes = ds_resource_description["attributes"] - for key, val in six.iteritems(datasource_properties): + for key, val in datasource_properties.items(): assignment_strings.append( __get_single_assignment_string(key, val, ds_attributes) ) @@ -219,7 +212,7 @@ def __get_properties_assignment_string(datasource_properties, ds_resource_descri def __get_single_assignment_string(key, val, ds_attributes): - return "{0}={1}".format(key, __format_value(key, val, ds_attributes)) + return "{}={}".format(key, __format_value(key, val, ds_attributes)) def __format_value(key, value, ds_attributes): @@ -234,16 +227,16 @@ def __format_value(key, value, ds_attributes): return "false" else: raise Exception( - "Don't know how to convert {0} to BOOLEAN type".format(value) + "Don't know how to convert {} to BOOLEAN type".format(value) ) elif type_ == "INT": - return six.text_type(value) + return str(value) elif type_ == "STRING": - return '"{0}"'.format(value) + return '"{}"'.format(value) else: raise Exception( - "Don't know how to format value {0} of type {1}".format(value, type_) + "Don't know how to format value {} of type {}".format(value, type_) ) @@ -298,7 +291,7 @@ def update_datasource(jboss_config, name, new_properties, profile=None): if not update_result["success"]: ret["result"] = False ret["comment"] = ret["comment"] + ( - "Could not update datasource property {0} with value {1},\n stdout: {2}\n".format( + "Could not update datasource property {} with value {},\n stdout: {}\n".format( key, new_properties[key], update_result["stdout"] ) ) diff --git a/salt/modules/jboss7_cli.py b/salt/modules/jboss7_cli.py index aa7de9d12d9..98f00a86983 100644 --- a/salt/modules/jboss7_cli.py +++ b/salt/modules/jboss7_cli.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Module for low-level interaction with JbossAS7 through CLI. @@ -36,20 +35,14 @@ Example: """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import logging import pprint import re import time -# Import Salt libs from salt.exceptions import CommandExecutionError -# Import 3rd-party libs -from salt.ext import six - log = logging.getLogger(__name__) @@ -117,7 +110,7 @@ def run_operation(jboss_config, operation, fail_on_error=True, retries=1): cli_result["success"] = cli_result["outcome"] == "success" else: raise CommandExecutionError( - "Operation has returned unparseable output: {0}".format( + "Operation has returned unparseable output: {}".format( cli_command_result["stdout"] ) ) @@ -160,13 +153,13 @@ def _call_cli(jboss_config, command, retries=1): command_segments = [ jboss_config["cli_path"], "--connect", - '--controller="{0}"'.format(jboss_config["controller"]), + '--controller="{}"'.format(jboss_config["controller"]), ] - if "cli_user" in six.iterkeys(jboss_config): - command_segments.append('--user="{0}"'.format(jboss_config["cli_user"])) - if "cli_password" in six.iterkeys(jboss_config): - command_segments.append('--password="{0}"'.format(jboss_config["cli_password"])) - command_segments.append('--command="{0}"'.format(__escape_command(command))) + if "cli_user" in jboss_config.keys(): + command_segments.append('--user="{}"'.format(jboss_config["cli_user"])) + if "cli_password" in jboss_config.keys(): + command_segments.append('--password="{}"'.format(jboss_config["cli_password"])) + command_segments.append('--command="{}"'.format(__escape_command(command))) cli_script = " ".join(command_segments) cli_command_result = __salt__["cmd.run_all"](cli_script) @@ -343,7 +336,7 @@ def __process_tokens_internal(tokens, start_at=0): log.debug(" TYPE: EXPRESSION") is_expression = True else: - raise CommandExecutionError("Unknown token! Token: {0}".format(token)) + raise CommandExecutionError("Unknown token! Token: {}".format(token)) token_no = token_no + 1 @@ -388,12 +381,7 @@ def __is_long(token): def __get_long(token): - if six.PY2: - # pylint: disable=incompatible-py3-code,undefined-variable - return long(token[0:-1]) - # pylint: enable=incompatible-py3-code,undefined-variable - else: - return int(token[0:-1]) + return int(token[0:-1]) def __is_datatype(token): diff --git a/salt/modules/jenkinsmod.py b/salt/modules/jenkinsmod.py index 6ba74868541..d87c13c3049 100644 --- a/salt/modules/jenkinsmod.py +++ b/salt/modules/jenkinsmod.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Module for controlling Jenkins @@ -23,17 +22,12 @@ Module for controlling Jenkins api_key: peWcBiMOS9HrZG15peWcBiMOS9HrZG15 """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import logging import salt.utils.files - -# Import Salt libs import salt.utils.stringutils -# Import 3rd-party libs # pylint: disable=import-error,no-name-in-module,redefined-builtin from salt.exceptions import CommandExecutionError, SaltInvocationError @@ -115,7 +109,7 @@ def _retrieve_config_xml(config_xml, saltenv): ret = __salt__["cp.cache_file"](config_xml, saltenv) if not ret: - raise CommandExecutionError("Failed to retrieve {0}".format(config_xml)) + raise CommandExecutionError("Failed to retrieve {}".format(config_xml)) return ret @@ -226,7 +220,7 @@ def get_job_info(name=None): server = _connect() if not job_exists(name): - raise CommandExecutionError("Job '{0}' does not exist".format(name)) + raise CommandExecutionError("Job '{}' does not exist".format(name)) job_info = server.get_job_info(name) if job_info: @@ -255,13 +249,13 @@ def build_job(name=None, parameters=None): server = _connect() if not job_exists(name): - raise CommandExecutionError("Job '{0}' does not exist.".format(name)) + raise CommandExecutionError("Job '{}' does not exist.".format(name)) try: server.build_job(name, parameters) except jenkins.JenkinsException as err: raise CommandExecutionError( - "Encountered error building job '{0}': {1}".format(name, err) + "Encountered error building job '{}': {}".format(name, err) ) return True @@ -288,7 +282,7 @@ def create_job(name=None, config_xml=None, saltenv="base"): raise SaltInvocationError("Required parameter 'name' is missing") if job_exists(name): - raise CommandExecutionError("Job '{0}' already exists".format(name)) + raise CommandExecutionError("Job '{}' already exists".format(name)) if not config_xml: config_xml = jenkins.EMPTY_CONFIG_XML @@ -303,7 +297,7 @@ def create_job(name=None, config_xml=None, saltenv="base"): server.create_job(name, config_xml) except jenkins.JenkinsException as err: raise CommandExecutionError( - "Encountered error creating job '{0}': {1}".format(name, err) + "Encountered error creating job '{}': {}".format(name, err) ) return config_xml @@ -342,7 +336,7 @@ def update_job(name=None, config_xml=None, saltenv="base"): server.reconfig_job(name, config_xml) except jenkins.JenkinsException as err: raise CommandExecutionError( - "Encountered error updating job '{0}': {1}".format(name, err) + "Encountered error updating job '{}': {}".format(name, err) ) return config_xml @@ -367,13 +361,13 @@ def delete_job(name=None): server = _connect() if not job_exists(name): - raise CommandExecutionError("Job '{0}' does not exist".format(name)) + raise CommandExecutionError("Job '{}' does not exist".format(name)) try: server.delete_job(name) except jenkins.JenkinsException as err: raise CommandExecutionError( - "Encountered error deleting job '{0}': {1}".format(name, err) + "Encountered error deleting job '{}': {}".format(name, err) ) return True @@ -398,13 +392,13 @@ def enable_job(name=None): server = _connect() if not job_exists(name): - raise CommandExecutionError("Job '{0}' does not exist".format(name)) + raise CommandExecutionError("Job '{}' does not exist".format(name)) try: server.enable_job(name) except jenkins.JenkinsException as err: raise CommandExecutionError( - "Encountered error enabling job '{0}': {1}".format(name, err) + "Encountered error enabling job '{}': {}".format(name, err) ) return True @@ -430,13 +424,13 @@ def disable_job(name=None): server = _connect() if not job_exists(name): - raise CommandExecutionError("Job '{0}' does not exist".format(name)) + raise CommandExecutionError("Job '{}' does not exist".format(name)) try: server.disable_job(name) except jenkins.JenkinsException as err: raise CommandExecutionError( - "Encountered error disabling job '{0}': {1}".format(name, err) + "Encountered error disabling job '{}': {}".format(name, err) ) return True @@ -462,7 +456,7 @@ def job_status(name=None): server = _connect() if not job_exists(name): - raise CommandExecutionError("Job '{0}' does not exist".format(name)) + raise CommandExecutionError("Job '{}' does not exist".format(name)) return server.get_job_info("empty")["buildable"] @@ -488,7 +482,7 @@ def get_job_config(name=None): server = _connect() if not job_exists(name): - raise CommandExecutionError("Job '{0}' does not exist".format(name)) + raise CommandExecutionError("Job '{}' does not exist".format(name)) job_info = server.get_job_config(name) return job_info diff --git a/salt/modules/kapacitor.py b/salt/modules/kapacitor.py index 2a3d86e6f8c..f3a47267a71 100644 --- a/salt/modules/kapacitor.py +++ b/salt/modules/kapacitor.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Kapacitor execution module. @@ -22,8 +21,6 @@ Kapacitor execution module. overwrite options passed into pillar. """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import logging as logger @@ -32,7 +29,6 @@ import salt.utils.json import salt.utils.path # Import Salt lobs -from salt.ext import six from salt.utils.decorators import memoize # Setup the logger @@ -53,9 +49,7 @@ def version(): """ version = __salt__["pkg.version"]("kapacitor") if not version: - version = six.string_types( - __salt__["config.option"]("kapacitor.version", "latest") - ) + version = str(__salt__["config.option"]("kapacitor.version", "latest")) return version @@ -67,7 +61,7 @@ def _get_url(): host = __salt__["config.option"]("kapacitor.host", "localhost") port = __salt__["config.option"]("kapacitor.port", 9092) - return "{0}://{1}:{2}".format(protocol, host, port) + return "{}://{}:{}".format(protocol, host, port) def get_task(name): @@ -86,9 +80,9 @@ def get_task(name): url = _get_url() if version() < "0.13": - task_url = "{0}/task?name={1}".format(url, name) + task_url = "{}/task?name={}".format(url, name) else: - task_url = "{0}/kapacitor/v1/tasks/{1}?skip-format=true".format(url, name) + task_url = "{}/kapacitor/v1/tasks/{}?skip-format=true".format(url, name) response = salt.utils.http.query(task_url, status=True) @@ -179,28 +173,28 @@ def define_task( return False if version() < "0.13": - cmd = "kapacitor define -name {0}".format(name) + cmd = "kapacitor define -name {}".format(name) else: - cmd = "kapacitor define {0}".format(name) + cmd = "kapacitor define {}".format(name) if tick_script.startswith("salt://"): tick_script = __salt__["cp.cache_file"](tick_script, __env__) - cmd += " -tick {0}".format(tick_script) + cmd += " -tick {}".format(tick_script) if task_type: - cmd += " -type {0}".format(task_type) + cmd += " -type {}".format(task_type) if not dbrps: dbrps = [] if database and retention_policy: - dbrp = "{0}.{1}".format(database, retention_policy) + dbrp = "{}.{}".format(database, retention_policy) dbrps.append(dbrp) if dbrps: for dbrp in dbrps: - cmd += " -dbrp {0}".format(dbrp) + cmd += " -dbrp {}".format(dbrp) return _run_cmd(cmd) @@ -218,7 +212,7 @@ def delete_task(name): salt '*' kapacitor.delete_task cpu """ - return _run_cmd("kapacitor delete tasks {0}".format(name)) + return _run_cmd("kapacitor delete tasks {}".format(name)) def enable_task(name): @@ -234,7 +228,7 @@ def enable_task(name): salt '*' kapacitor.enable_task cpu """ - return _run_cmd("kapacitor enable {0}".format(name)) + return _run_cmd("kapacitor enable {}".format(name)) def disable_task(name): @@ -250,4 +244,4 @@ def disable_task(name): salt '*' kapacitor.disable_task cpu """ - return _run_cmd("kapacitor disable {0}".format(name)) + return _run_cmd("kapacitor disable {}".format(name)) diff --git a/salt/modules/kerberos.py b/salt/modules/kerberos.py index a41a384bcae..ea898a22634 100644 --- a/salt/modules/kerberos.py +++ b/salt/modules/kerberos.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage Kerberos KDC @@ -20,12 +19,9 @@ authenticate as. auth_principal: kadmin/admin """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import logging -# Import Salt libs import salt.utils.path log = logging.getLogger(__name__) @@ -49,7 +45,7 @@ def __execute_kadmin(cmd): if __salt__["file.file_exists"](auth_keytab) and auth_principal: return __salt__["cmd.run_all"]( - 'kadmin -k -t {0} -p {1} -q "{2}"'.format(auth_keytab, auth_principal, cmd) + 'kadmin -k -t {} -p {} -q "{}"'.format(auth_keytab, auth_principal, cmd) ) else: log.error("Unable to find kerberos keytab/principal") @@ -99,7 +95,7 @@ def get_principal(name): """ ret = {} - cmd = __execute_kadmin("get_principal {0}".format(name)) + cmd = __execute_kadmin("get_principal {}".format(name)) if cmd["retcode"] != 0 or cmd["stderr"]: ret["comment"] = cmd["stderr"].splitlines()[-1] @@ -155,7 +151,7 @@ def get_policy(name): """ ret = {} - cmd = __execute_kadmin("get_policy {0}".format(name)) + cmd = __execute_kadmin("get_policy {}".format(name)) if cmd["retcode"] != 0 or cmd["stderr"]: ret["comment"] = cmd["stderr"].splitlines()[-1] @@ -214,9 +210,9 @@ def create_principal(name, enctypes=None): krb_cmd = "addprinc -randkey" if enctypes: - krb_cmd += " -e {0}".format(enctypes) + krb_cmd += " -e {}".format(enctypes) - krb_cmd += " {0}".format(name) + krb_cmd += " {}".format(name) cmd = __execute_kadmin(krb_cmd) @@ -242,7 +238,7 @@ def delete_principal(name): """ ret = {} - cmd = __execute_kadmin("delprinc -force {0}".format(name)) + cmd = __execute_kadmin("delprinc -force {}".format(name)) if cmd["retcode"] != 0 or cmd["stderr"]: ret["comment"] = cmd["stderr"].splitlines()[-1] @@ -265,12 +261,12 @@ def create_keytab(name, keytab, enctypes=None): """ ret = {} - krb_cmd = "ktadd -k {0}".format(keytab) + krb_cmd = "ktadd -k {}".format(keytab) if enctypes: - krb_cmd += " -e {0}".format(enctypes) + krb_cmd += " -e {}".format(enctypes) - krb_cmd += " {0}".format(name) + krb_cmd += " {}".format(name) cmd = __execute_kadmin(krb_cmd) diff --git a/salt/modules/keystoneng.py b/salt/modules/keystoneng.py index 98cf66c81fe..6aceed7276f 100644 --- a/salt/modules/keystoneng.py +++ b/salt/modules/keystoneng.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Keystone module for interacting with OpenStack Keystone @@ -26,7 +25,6 @@ Example configuration identity_api_version: 3 """ -from __future__ import absolute_import, print_function, unicode_literals HAS_SHADE = False try: diff --git a/salt/modules/keystore.py b/salt/modules/keystore.py index b941b9eb4f3..04ed7cc217e 100644 --- a/salt/modules/keystore.py +++ b/salt/modules/keystore.py @@ -1,16 +1,12 @@ -# -*- coding: utf-8 -*- """ Module to interact with keystores """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import logging import os from datetime import datetime -# Import third party libs from salt.exceptions import CommandExecutionError, SaltInvocationError log = logging.getLogger(__name__) @@ -32,7 +28,7 @@ def __virtual__(): Check dependencies """ if has_depends is False: - msg = "jks unavailable: {0} execution module cant be loaded ".format( + msg = "jks unavailable: {} execution module cant be loaded ".format( __virtualname__ ) return False, msg @@ -159,7 +155,7 @@ def add(name, keystore, passphrase, certificate, private_key=None): cert_string = __salt__["x509.get_pem_entry"](certificate) except SaltInvocationError: raise SaltInvocationError( - "Invalid certificate file or string: {0}".format(certificate) + "Invalid certificate file or string: {}".format(certificate) ) if private_key: diff --git a/salt/modules/launchctl_service.py b/salt/modules/launchctl_service.py index 0d1acf72584..9884118477d 100644 --- a/salt/modules/launchctl_service.py +++ b/salt/modules/launchctl_service.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Module for the management of MacOS systems that use launchd/launchctl @@ -11,8 +10,6 @@ Module for the management of MacOS systems that use launchd/launchctl :depends: - plistlib Python module """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import fnmatch import logging @@ -20,14 +17,12 @@ import os import plistlib import re -# Import salt libs import salt.utils.data import salt.utils.decorators as decorators import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.stringutils -from salt.ext import six from salt.utils.versions import LooseVersion as _LooseVersion # Set up logging @@ -108,18 +103,13 @@ def _available_services(): except Exception: # pylint: disable=broad-except # If plistlib is unable to read the file we'll need to use # the system provided plutil program to do the conversion - cmd = '/usr/bin/plutil -convert xml1 -o - -- "{0}"'.format( - true_path - ) + cmd = '/usr/bin/plutil -convert xml1 -o - -- "{}"'.format(true_path) plist_xml = __salt__["cmd.run_all"](cmd, python_shell=False)[ "stdout" ] - if six.PY2: - plist = plistlib.readPlistFromString(plist_xml) - else: - plist = plistlib.readPlistFromBytes( - salt.utils.stringutils.to_bytes(plist_xml) - ) + plist = plistlib.readPlistFromBytes( + salt.utils.stringutils.to_bytes(plist_xml) + ) try: available_services[plist.Label.lower()] = { @@ -147,7 +137,7 @@ def _service_by_name(name): # Match on label return services[name] - for service in six.itervalues(services): + for service in services.values(): if service["file_path"].lower() == name: # Match on full path return service @@ -185,9 +175,9 @@ def get_all(): def _get_launchctl_data(job_label, runas=None): if BEFORE_YOSEMITE: - cmd = "launchctl list -x {0}".format(job_label) + cmd = "launchctl list -x {}".format(job_label) else: - cmd = "launchctl list {0}".format(job_label) + cmd = "launchctl list {}".format(job_label) launchctl_data = __salt__["cmd.run_all"](cmd, python_shell=False, runas=runas) @@ -265,12 +255,7 @@ def status(name, runas=None): if launchctl_data: if BEFORE_YOSEMITE: - if six.PY3: - results[service] = "PID" in plistlib.loads(launchctl_data) - else: - results[service] = "PID" in dict( - plistlib.readPlistFromString(launchctl_data) - ) + results[service] = "PID" in plistlib.loads(launchctl_data) else: pattern = '"PID" = [0-9]+;' results[service] = True if re.search(pattern, launchctl_data) else False @@ -295,7 +280,7 @@ def stop(job_label, runas=None): """ service = _service_by_name(job_label) if service: - cmd = "launchctl unload -w {0}".format(service["file_path"], runas=runas) + cmd = "launchctl unload -w {}".format(service["file_path"], runas=runas) return not __salt__["cmd.retcode"](cmd, runas=runas, python_shell=False) return False @@ -315,7 +300,7 @@ def start(job_label, runas=None): """ service = _service_by_name(job_label) if service: - cmd = "launchctl load -w {0}".format(service["file_path"], runas=runas) + cmd = "launchctl load -w {}".format(service["file_path"], runas=runas) return not __salt__["cmd.retcode"](cmd, runas=runas, python_shell=False) return False diff --git a/salt/modules/layman.py b/salt/modules/layman.py index 3fb37893331..ad0964295b3 100644 --- a/salt/modules/layman.py +++ b/salt/modules/layman.py @@ -1,8 +1,6 @@ -# -*- coding: utf-8 -*- """ Support for Layman """ -from __future__ import absolute_import, print_function, unicode_literals import salt.exceptions import salt.utils.path @@ -49,7 +47,7 @@ def add(overlay): """ ret = list() old_overlays = list_local() - cmd = "layman --quietness=0 --add {0}".format(overlay) + cmd = "layman --quietness=0 --add {}".format(overlay) add_attempt = __salt__["cmd.run_all"](cmd, python_shell=False, stdin="y") if add_attempt["retcode"] != 0: raise salt.exceptions.CommandExecutionError(add_attempt["stdout"]) @@ -83,7 +81,7 @@ def delete(overlay): """ ret = list() old_overlays = list_local() - cmd = "layman --quietness=0 --delete {0}".format(overlay) + cmd = "layman --quietness=0 --delete {}".format(overlay) delete_attempt = __salt__["cmd.run_all"](cmd, python_shell=False) if delete_attempt["retcode"] != 0: raise salt.exceptions.CommandExecutionError(delete_attempt["stdout"]) @@ -115,7 +113,7 @@ def sync(overlay="ALL"): salt '*' layman.sync """ - cmd = "layman --quietness=0 --sync {0}".format(overlay) + cmd = "layman --quietness=0 --sync {}".format(overlay) return __salt__["cmd.retcode"](cmd, python_shell=False) == 0 diff --git a/salt/modules/ldapmod.py b/salt/modules/ldapmod.py index 0da327dbcaf..a726daf5b5e 100644 --- a/salt/modules/ldapmod.py +++ b/salt/modules/ldapmod.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Salt interface to LDAP commands @@ -40,18 +39,13 @@ Salt interface to LDAP commands badness may ensue - you have been warned. """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import logging import time -# Import Salt libs import salt.utils.data from salt.exceptions import CommandExecutionError -from salt.ext import six -# Import third party libs try: import ldap import ldap.modlist # pylint: disable=no-name-in-module @@ -89,7 +83,7 @@ def _config(name, key=None, **kwargs): if name in kwargs: value = kwargs[name] else: - value = __salt__["config.option"]("ldap.{0}".format(key)) + value = __salt__["config.option"]("ldap.{}".format(key)) return salt.utils.data.decode(value, to_str=True) @@ -168,19 +162,19 @@ def search( results = _ldap.search_s(dn, int(scope), filter, attrs) elapsed = time.time() - start if elapsed < 0.200: - elapsed_h = six.text_type(round(elapsed * 1000, 1)) + "ms" + elapsed_h = str(round(elapsed * 1000, 1)) + "ms" else: - elapsed_h = six.text_type(round(elapsed, 2)) + "s" + elapsed_h = str(round(elapsed, 2)) + "s" ret = { "results": results, "count": len(results), - "time": {"human": elapsed_h, "raw": six.text_type(round(elapsed, 5))}, + "time": {"human": elapsed_h, "raw": str(round(elapsed, 5))}, } return ret -class _LDAPConnection(object): +class _LDAPConnection: """ Setup an LDAP connection. """ @@ -197,13 +191,13 @@ class _LDAPConnection(object): self.bindpw = bindpw if self.uri == "": - self.uri = "ldap://{0}:{1}".format(self.server, self.port) + self.uri = "ldap://{}:{}".format(self.server, self.port) try: if no_verify: ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER) - self.ldap = ldap.initialize("{0}".format(self.uri)) + self.ldap = ldap.initialize("{}".format(self.uri)) self.ldap.protocol_version = 3 # ldap.VERSION3 self.ldap.set_option(ldap.OPT_REFERRALS, 0) # Needed for AD @@ -214,7 +208,7 @@ class _LDAPConnection(object): self.ldap.simple_bind_s(self.binddn, self.bindpw) except Exception as ldap_error: # pylint: disable=broad-except raise CommandExecutionError( - "Failed to bind to LDAP server {0} as {1}: {2}".format( + "Failed to bind to LDAP server {} as {}: {}".format( self.uri, self.binddn, ldap_error ) ) diff --git a/salt/modules/marathon.py b/salt/modules/marathon.py index 7f827918c7e..cec5eb48fae 100644 --- a/salt/modules/marathon.py +++ b/salt/modules/marathon.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Module providing a simple management interface to a marathon cluster. @@ -7,12 +6,9 @@ Currently this only works when run through a proxy minion. .. versionadded:: 2015.8.2 """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import logging -# Import Salt libs import salt.utils.http import salt.utils.json import salt.utils.platform @@ -48,7 +44,7 @@ def _app_id(app_id): Make sure the app_id is in the correct format. """ if app_id[0] != "/": - app_id = "/{0}".format(app_id) + app_id = "/{}".format(app_id) return app_id @@ -63,7 +59,7 @@ def apps(): salt marathon-minion-id marathon.apps """ response = salt.utils.http.query( - "{0}/v2/apps".format(_base_url()), decode_type="json", decode=True, + "{}/v2/apps".format(_base_url()), decode_type="json", decode=True, ) return {"apps": [app["id"] for app in response["dict"]["apps"]]} @@ -92,7 +88,7 @@ def app(id): salt marathon-minion-id marathon.app my-app """ response = salt.utils.http.query( - "{0}/v2/apps/{1}".format(_base_url(), id), decode_type="json", decode=True, + "{}/v2/apps/{}".format(_base_url(), id), decode_type="json", decode=True, ) return response["dict"] @@ -116,7 +112,7 @@ def update_app(id, config): data = salt.utils.json.dumps(config) try: response = salt.utils.http.query( - "{0}/v2/apps/{1}?force=true".format(_base_url(), id), + "{}/v2/apps/{}?force=true".format(_base_url(), id), method="PUT", decode_type="json", decode=True, @@ -144,7 +140,7 @@ def rm_app(id): salt marathon-minion-id marathon.rm_app my-app """ response = salt.utils.http.query( - "{0}/v2/apps/{1}".format(_base_url(), id), + "{}/v2/apps/{}".format(_base_url(), id), method="DELETE", decode_type="json", decode=True, @@ -163,7 +159,7 @@ def info(): salt marathon-minion-id marathon.info """ response = salt.utils.http.query( - "{0}/v2/info".format(_base_url()), decode_type="json", decode=True, + "{}/v2/info".format(_base_url()), decode_type="json", decode=True, ) return response["dict"] @@ -200,7 +196,7 @@ def restart_app(id, restart=False, force=True): return ret try: response = salt.utils.http.query( - "{0}/v2/apps/{1}/restart?force={2}".format(_base_url(), _app_id(id), force), + "{}/v2/apps/{}/restart?force={}".format(_base_url(), _app_id(id), force), method="POST", decode_type="json", decode=True, diff --git a/salt/modules/mattermost.py b/salt/modules/mattermost.py index 4271e26b8b8..adb3cb7b676 100644 --- a/salt/modules/mattermost.py +++ b/salt/modules/mattermost.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Module for sending messages to Mattermost @@ -15,12 +14,9 @@ Module for sending messages to Mattermost api_url: https://example.com """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import logging -# Import Salt libs import salt.utils.json import salt.utils.mattermost from salt.exceptions import SaltInvocationError @@ -134,7 +130,7 @@ def post_message(message, channel=None, username=None, api_url=None, hook=None): parameters["username"] = username parameters["text"] = "```" + message + "```" # pre-formatted, fixed-width text log.debug("Parameters: %s", parameters) - data = str("payload={0}").format( + data = "payload={}".format( salt.utils.json.dumps(parameters) ) # pylint: disable=blacklisted-function result = salt.utils.mattermost.query(api_url=api_url, hook=hook, data=data) diff --git a/salt/modules/mdata.py b/salt/modules/mdata.py index dda351e93f4..13f2e4cb396 100644 --- a/salt/modules/mdata.py +++ b/salt/modules/mdata.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Module for managaging metadata in SmartOS Zones @@ -9,14 +8,10 @@ Module for managaging metadata in SmartOS Zones :platform: smartos """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import logging import salt.utils.decorators as decorators - -# Import Salt libs import salt.utils.path import salt.utils.platform @@ -74,7 +69,7 @@ def __virtual__(): return __virtualname__ return ( False, - "{0} module can only be loaded on SmartOS zones".format(__virtualname__), + "{} module can only be loaded on SmartOS zones".format(__virtualname__), ) @@ -90,7 +85,7 @@ def list_(): """ mdata = _check_mdata_list() if mdata: - cmd = "{0}".format(mdata) + cmd = "{}".format(mdata) return __salt__["cmd.run"](cmd, ignore_retcode=True).splitlines() return {} @@ -121,7 +116,7 @@ def get_(*keyname): for k in keyname: if mdata: - cmd = "{0} {1}".format(mdata, k) + cmd = "{} {}".format(mdata, k) res = __salt__["cmd.run_all"](cmd, ignore_retcode=True) ret[k] = res["stdout"] if res["retcode"] == 0 else "" else: @@ -175,7 +170,7 @@ def delete_(*keyname): for k in keyname: if mdata and k in valid_keynames: - cmd = "{0} {1}".format(mdata, k) + cmd = "{} {}".format(mdata, k) ret[k] = __salt__["cmd.run_all"](cmd, ignore_retcode=True)["retcode"] == 0 else: ret[k] = True diff --git a/salt/modules/memcached.py b/salt/modules/memcached.py index 16bfbc3bc4f..32d57ae9e56 100644 --- a/salt/modules/memcached.py +++ b/salt/modules/memcached.py @@ -1,23 +1,17 @@ -# -*- coding: utf-8 -*- """ Module for Management of Memcached Keys .. versionadded:: 2014.1.0 """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import logging -# Import salt libs import salt.utils.functools from salt.exceptions import CommandExecutionError, SaltInvocationError -from salt.ext import six # TODO: use salt.utils.memcache -# Import third party libs try: import memcache @@ -56,8 +50,8 @@ def _connect(host=DEFAULT_HOST, port=DEFAULT_PORT): Returns a tuple of (user, host, port) with config, pillar, or default values assigned to missing values. """ - if six.text_type(port).isdigit(): - return memcache.Client(["{0}:{1}".format(host, port)], debug=0) + if str(port).isdigit(): + return memcache.Client(["{}:{}".format(host, port)], debug=0) raise SaltInvocationError("port must be an integer") @@ -123,9 +117,9 @@ def set_( salt '*' memcached.set """ - if not isinstance(time, six.integer_types): + if not isinstance(time, int): raise SaltInvocationError("'time' must be an integer") - if not isinstance(min_compress_len, six.integer_types): + if not isinstance(min_compress_len, int): raise SaltInvocationError("'min_compress_len' must be an integer") conn = _connect(host, port) _check_stats(conn) @@ -142,7 +136,7 @@ def delete(key, host=DEFAULT_HOST, port=DEFAULT_PORT, time=DEFAULT_TIME): salt '*' memcached.delete """ - if not isinstance(time, six.integer_types): + if not isinstance(time, int): raise SaltInvocationError("'time' must be an integer") conn = _connect(host, port) _check_stats(conn) @@ -167,9 +161,9 @@ def add( salt '*' memcached.add """ - if not isinstance(time, six.integer_types): + if not isinstance(time, int): raise SaltInvocationError("'time' must be an integer") - if not isinstance(min_compress_len, six.integer_types): + if not isinstance(min_compress_len, int): raise SaltInvocationError("'min_compress_len' must be an integer") conn = _connect(host, port) _check_stats(conn) @@ -195,9 +189,9 @@ def replace( salt '*' memcached.replace """ - if not isinstance(time, six.integer_types): + if not isinstance(time, int): raise SaltInvocationError("'time' must be an integer") - if not isinstance(min_compress_len, six.integer_types): + if not isinstance(min_compress_len, int): raise SaltInvocationError("'min_compress_len' must be an integer") conn = _connect(host, port) stats = conn.get_stats() @@ -220,10 +214,10 @@ def increment(key, delta=1, host=DEFAULT_HOST, port=DEFAULT_PORT): cur = get(key) if cur is None: - raise CommandExecutionError("Key '{0}' does not exist".format(key)) - elif not isinstance(cur, six.integer_types): + raise CommandExecutionError("Key '{}' does not exist".format(key)) + elif not isinstance(cur, int): raise CommandExecutionError( - "Value for key '{0}' must be an integer to be " "incremented".format(key) + "Value for key '{}' must be an integer to be " "incremented".format(key) ) try: @@ -251,10 +245,10 @@ def decrement(key, delta=1, host=DEFAULT_HOST, port=DEFAULT_PORT): cur = get(key) if cur is None: - raise CommandExecutionError("Key '{0}' does not exist".format(key)) - elif not isinstance(cur, six.integer_types): + raise CommandExecutionError("Key '{}' does not exist".format(key)) + elif not isinstance(cur, int): raise CommandExecutionError( - "Value for key '{0}' must be an integer to be " "decremented".format(key) + "Value for key '{}' must be an integer to be " "decremented".format(key) ) try: diff --git a/salt/modules/modjk.py b/salt/modules/modjk.py index ae8820bc1c3..3017454d171 100644 --- a/salt/modules/modjk.py +++ b/salt/modules/modjk.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Control Modjk via the Apache Tomcat "Status" worker (http://tomcat.apache.org/connectors-doc/reference/status.html) @@ -30,23 +29,8 @@ this module. realm: authentication realm2 for digest passwords timeout: 600 """ -from __future__ import absolute_import, print_function, unicode_literals - -# Import 3rd-party libs -# pylint: disable=import-error,no-name-in-module -from salt.ext import six -from salt.ext.six.moves.urllib.parse import urlencode as _urlencode -from salt.ext.six.moves.urllib.request import ( - HTTPBasicAuthHandler as _HTTPBasicAuthHandler, -) -from salt.ext.six.moves.urllib.request import ( - HTTPDigestAuthHandler as _HTTPDigestAuthHandler, -) -from salt.ext.six.moves.urllib.request import build_opener as _build_opener -from salt.ext.six.moves.urllib.request import install_opener as _install_opener -from salt.ext.six.moves.urllib.request import urlopen as _urlopen - -# pylint: enable=import-error,no-name-in-module +import urllib.parse +import urllib.request def __virtual__(): @@ -61,11 +45,11 @@ def _auth(url, user, passwd, realm): returns a authentication handler. """ - basic = _HTTPBasicAuthHandler() + basic = urllib.request.HTTPBasicAuthHandler() basic.add_password(realm=realm, uri=url, user=user, passwd=passwd) - digest = _HTTPDigestAuthHandler() + digest = urllib.request.HTTPDigestAuthHandler() digest.add_password(realm=realm, uri=url, user=user, passwd=passwd) - return _build_opener(basic, digest) + return urllib.request.build_opener(basic, digest) def _do_http(opts, profile="default"): @@ -75,25 +59,25 @@ def _do_http(opts, profile="default"): ret = {} - url = __salt__["config.get"]("modjk:{0}:url".format(profile), "") - user = __salt__["config.get"]("modjk:{0}:user".format(profile), "") - passwd = __salt__["config.get"]("modjk:{0}:pass".format(profile), "") - realm = __salt__["config.get"]("modjk:{0}:realm".format(profile), "") - timeout = __salt__["config.get"]("modjk:{0}:timeout".format(profile), "") + url = __salt__["config.get"]("modjk:{}:url".format(profile), "") + user = __salt__["config.get"]("modjk:{}:user".format(profile), "") + passwd = __salt__["config.get"]("modjk:{}:pass".format(profile), "") + realm = __salt__["config.get"]("modjk:{}:realm".format(profile), "") + timeout = __salt__["config.get"]("modjk:{}:timeout".format(profile), "") if not url: - raise Exception("missing url in profile {0}".format(profile)) + raise Exception("missing url in profile {}".format(profile)) if user and passwd: auth = _auth(url=url, realm=realm, user=user, passwd=passwd) - _install_opener(auth) + urllib.request.install_opener(auth) - url += "?{0}".format(_urlencode(opts)) + url += "?{}".format(urllib.prase.urlencode(opts)) - for line in _urlopen(url, timeout=timeout).read().splitlines(): + for line in urllib.request.urlopen(url, timeout=timeout).read().splitlines(): splt = line.split("=", 1) if splt[0] in ret: - ret[splt[0]] += ",{0}".format(splt[1]) + ret[splt[0]] += ",{}".format(splt[1]) else: ret[splt[0]] = splt[1] @@ -187,7 +171,7 @@ def list_configured_members(lbn, profile="default"): config = dump_config(profile) try: - ret = config["worker.{0}.balance_workers".format(lbn)] + ret = config["worker.{}.balance_workers".format(lbn)] except KeyError: return [] @@ -214,7 +198,7 @@ def workers(profile="default"): for lb in lbn: try: worker_list.extend( - config["worker.{0}.balance_workers".format(lb)].split(",") + config["worker.{}.balance_workers".format(lb)].split(",") ) except KeyError: pass @@ -223,8 +207,8 @@ def workers(profile="default"): for worker in worker_list: ret[worker] = { - "activation": config["worker.{0}.activation".format(worker)], - "state": config["worker.{0}.state".format(worker)], + "activation": config["worker.{}.activation".format(worker)], + "state": config["worker.{}.state".format(worker)], } return ret @@ -245,7 +229,7 @@ def recover_all(lbn, profile="default"): ret = {} config = get_running(profile) try: - workers_ = config["worker.{0}.balance_workers".format(lbn)].split(",") + workers_ = config["worker.{}.balance_workers".format(lbn)].split(",") except KeyError: return ret @@ -319,7 +303,7 @@ def bulk_stop(workers, lbn, profile="default"): ret = {} - if isinstance(workers, six.string_types): + if isinstance(workers, str): workers = workers.split(",") for worker in workers: @@ -348,7 +332,7 @@ def bulk_activate(workers, lbn, profile="default"): ret = {} - if isinstance(workers, six.string_types): + if isinstance(workers, str): workers = workers.split(",") for worker in workers: @@ -377,7 +361,7 @@ def bulk_disable(workers, lbn, profile="default"): ret = {} - if isinstance(workers, six.string_types): + if isinstance(workers, str): workers = workers.split(",") for worker in workers: @@ -406,7 +390,7 @@ def bulk_recover(workers, lbn, profile="default"): ret = {} - if isinstance(workers, six.string_types): + if isinstance(workers, str): workers = workers.split(",") for worker in workers: @@ -433,8 +417,8 @@ def worker_status(worker, profile="default"): config = get_running(profile) try: return { - "activation": config["worker.{0}.activation".format(worker)], - "state": config["worker.{0}.state".format(worker)], + "activation": config["worker.{}.activation".format(worker)], + "state": config["worker.{}.state".format(worker)], } except KeyError: return False diff --git a/salt/modules/mongodb.py b/salt/modules/mongodb.py index 9bdc423d0f5..9c6db2f0ed8 100644 --- a/salt/modules/mongodb.py +++ b/salt/modules/mongodb.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Module to provide MongoDB functionality to Salt @@ -13,19 +12,12 @@ Module to provide MongoDB functionality to Salt This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar. """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import logging import re -import sys -# Import salt libs import salt.utils.json from salt.exceptions import get_error_message as _get_error_message - -# Import third party libs -from salt.ext import six from salt.utils.versions import LooseVersion as _LooseVersion try: @@ -86,11 +78,11 @@ def _to_dict(objects): Potentially interprets a string as JSON for usage with mongo """ try: - if isinstance(objects, six.string_types): + if isinstance(objects, str): objects = salt.utils.json.loads(objects) except ValueError as err: log.error("Could not parse objects: %s", err) - six.reraise(*sys.exc_info()) + raise return objects @@ -114,7 +106,7 @@ def db_list(user=None, password=None, host=None, port=None, authdb=None): return conn.database_names() except pymongo.errors.PyMongoError as err: log.error(err) - return six.text_type(err) + return str(err) def db_exists(name, user=None, password=None, host=None, port=None, authdb=None): @@ -129,7 +121,7 @@ def db_exists(name, user=None, password=None, host=None, port=None, authdb=None) """ dbs = db_list(user, password, host, port, authdb=authdb) - if isinstance(dbs, six.string_types): + if isinstance(dbs, str): return False return name in dbs @@ -154,7 +146,7 @@ def db_remove(name, user=None, password=None, host=None, port=None, authdb=None) conn.drop_database(name) except pymongo.errors.PyMongoError as err: log.error("Removing database %s failed with error: %s", name, err) - return six.text_type(err) + return str(err) return True @@ -177,7 +169,7 @@ def version( """ conn = _connect(user, password, host, port, authdb=authdb) if not conn: - err_msg = "Failed to connect to MongoDB database {0}:{1}".format(host, port) + err_msg = "Failed to connect to MongoDB database {}:{}".format(host, port) log.error(err_msg) return (False, err_msg) @@ -186,7 +178,7 @@ def version( return _version(mdb) except pymongo.errors.PyMongoError as err: log.error("Listing users failed with error: %s", err) - return six.text_type(err) + return str(err) def user_find( @@ -203,7 +195,7 @@ def user_find( """ conn = _connect(user, password, host, port, authdb=authdb) if not conn: - err_msg = "Failed to connect to MongoDB database {0}:{1}".format(host, port) + err_msg = "Failed to connect to MongoDB database {}:{}".format(host, port) log.error(err_msg) return (False, err_msg) @@ -212,7 +204,7 @@ def user_find( return mdb.command("usersInfo", name)["users"] except pymongo.errors.PyMongoError as err: log.error("Listing users failed with error: %s", err) - return (False, six.text_type(err)) + return (False, str(err)) def user_list( @@ -250,7 +242,7 @@ def user_list( except pymongo.errors.PyMongoError as err: log.error("Listing users failed with error: %s", err) - return six.text_type(err) + return str(err) def user_exists( @@ -267,7 +259,7 @@ def user_exists( """ users = user_list(user, password, host, port, database, authdb) - if isinstance(users, six.string_types): + if isinstance(users, str): return "Failed to connect to mongo database" for user in users: @@ -310,7 +302,7 @@ def user_create( mdb.add_user(name, passwd, roles=roles) except pymongo.errors.PyMongoError as err: log.error("Creating database %s failed with error: %s", name, err) - return six.text_type(err) + return str(err) return True @@ -336,7 +328,7 @@ def user_remove( mdb.remove_user(name) except pymongo.errors.PyMongoError as err: log.error("Creating database %s failed with error: %s", name, err) - return six.text_type(err) + return str(err) return True @@ -364,7 +356,7 @@ def user_roles_exists( users = user_list(user, password, host, port, database, authdb) - if isinstance(users, six.string_types): + if isinstance(users, str): return "Failed to connect to mongo database" for user in users: @@ -413,7 +405,7 @@ def user_grant_roles( log.error( "Granting roles %s to user %s failed with error: %s", roles, name, err ) - return six.text_type(err) + return str(err) return True @@ -451,7 +443,7 @@ def user_revoke_roles( log.error( "Revoking roles %s from user %s failed with error: %s", roles, name, err ) - return six.text_type(err) + return str(err) return True @@ -523,7 +515,7 @@ def update_one( if not conn: return "Failed to connect to mongo database" - objects = six.text_type(objects) + objects = str(objects) objs = re.split(r"}\s+{", objects) if len(objs) != 2: @@ -562,7 +554,7 @@ def update_one( col = getattr(mdb, collection) ids = col.update_one(_id_field, {"$set": _update_doc}) nb_mod = ids.modified_count - return "{0} objects updated".format(nb_mod) + return "{} objects updated".format(nb_mod) except pymongo.errors.PyMongoError as err: log.error("Updating object %s failed with error %s", objects, err) return err @@ -643,7 +635,7 @@ def remove( mdb = pymongo.database.Database(conn, database) col = getattr(mdb, collection) ret = col.remove(query, w=w) - return "{0} objects removed".format(ret["n"]) + return "{} objects removed".format(ret["n"]) except pymongo.errors.PyMongoError as err: log.error("Removing objects failed with error: %s", _get_error_message(err)) return _get_error_message(err) diff --git a/salt/modules/monit.py b/salt/modules/monit.py index c8bd9a1070b..9da3a9ba6c1 100644 --- a/salt/modules/monit.py +++ b/salt/modules/monit.py @@ -1,14 +1,10 @@ -# -*- coding: utf-8 -*- """ Monit service module. This module will create a monit type service watcher. """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import re -# Import salt libs import salt.utils.path # Function alias to make sure not to shadow built-in's @@ -37,7 +33,7 @@ def start(name): salt '*' monit.start """ - cmd = "monit start {0}".format(name) + cmd = "monit start {}".format(name) return not __salt__["cmd.retcode"](cmd, python_shell=False) @@ -52,7 +48,7 @@ def stop(name): salt '*' monit.stop """ - cmd = "monit stop {0}".format(name) + cmd = "monit stop {}".format(name) return not __salt__["cmd.retcode"](cmd, python_shell=False) @@ -67,7 +63,7 @@ def restart(name): salt '*' monit.restart """ - cmd = "monit restart {0}".format(name) + cmd = "monit restart {}".format(name) return not __salt__["cmd.retcode"](cmd, python_shell=False) @@ -82,7 +78,7 @@ def unmonitor(name): salt '*' monit.unmonitor """ - cmd = "monit unmonitor {0}".format(name) + cmd = "monit unmonitor {}".format(name) return not __salt__["cmd.retcode"](cmd, python_shell=False) @@ -97,7 +93,7 @@ def monitor(name): salt '*' monit.monitor """ - cmd = "monit monitor {0}".format(name) + cmd = "monit monitor {}".format(name) return not __salt__["cmd.retcode"](cmd, python_shell=False) diff --git a/salt/modules/moosefs.py b/salt/modules/moosefs.py index f266d158758..21ee77cc708 100644 --- a/salt/modules/moosefs.py +++ b/salt/modules/moosefs.py @@ -1,10 +1,7 @@ -# -*- coding: utf-8 -*- """ Module for gathering and managing information about MooseFS """ -from __future__ import absolute_import, print_function, unicode_literals -# Import salt libs import salt.utils.path diff --git a/salt/modules/mssql.py b/salt/modules/mssql.py index 7211bb40b29..0f410b13c13 100644 --- a/salt/modules/mssql.py +++ b/salt/modules/mssql.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Module to provide MS SQL Server compatibility to salt. @@ -21,11 +20,7 @@ Module to provide MS SQL Server compatibility to salt. configs or pillars. """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals -# Import Salt libs -import salt.ext.six as six import salt.utils.json try: @@ -73,7 +68,7 @@ def _get_connection(**kwargs): class _MssqlEncoder(salt.utils.json.JSONEncoder): # E0202: 68:_MssqlEncoder.default: An attribute inherited from JSONEncoder hide this method def default(self, o): # pylint: disable=E0202 - return six.text_type(o) + return str(o) def tsql_query(query, **kwargs): @@ -95,7 +90,7 @@ def tsql_query(query, **kwargs): )["resultset"] except Exception as err: # pylint: disable=broad-except # Trying to look like the output of cur.fetchall() - return (("Could not run the query",), (six.text_type(err),)) + return (("Could not run the query",), (str(err),)) def version(**kwargs): @@ -141,7 +136,7 @@ def db_exists(database_name, **kwargs): return ( len( tsql_query( - "SELECT database_id FROM sys.databases WHERE NAME='{0}'".format( + "SELECT database_id FROM sys.databases WHERE NAME='{}'".format( database_name ), **kwargs @@ -165,7 +160,7 @@ def db_create(database, containment="NONE", new_database_options=None, **kwargs) """ if containment not in ["NONE", "PARTIAL"]: return "CONTAINMENT can be one of NONE and PARTIAL" - sql = "CREATE DATABASE [{0}] CONTAINMENT = {1} ".format(database, containment) + sql = "CREATE DATABASE [{}] CONTAINMENT = {} ".format(database, containment) if new_database_options: sql += " WITH " + ", ".join(new_database_options) conn = None @@ -176,7 +171,7 @@ def db_create(database, containment="NONE", new_database_options=None, **kwargs) # cur.execute(sql) conn.cursor().execute(sql) except Exception as e: # pylint: disable=broad-except - return "Could not create the database: {0}".format(e) + return "Could not create the database: {}".format(e) finally: if conn: conn.autocommit(False) @@ -206,18 +201,18 @@ def db_remove(database_name, **kwargs): conn.autocommit(True) cur = conn.cursor() cur.execute( - "ALTER DATABASE {0} SET SINGLE_USER WITH ROLLBACK IMMEDIATE".format( + "ALTER DATABASE {} SET SINGLE_USER WITH ROLLBACK IMMEDIATE".format( database_name ) ) - cur.execute("DROP DATABASE {0}".format(database_name)) + cur.execute("DROP DATABASE {}".format(database_name)) conn.autocommit(False) conn.close() return True else: return False except Exception as e: # pylint: disable=broad-except - return "Could not find the database: {0}".format(e) + return "Could not find the database: {}".format(e) def role_list(**kwargs): @@ -247,7 +242,7 @@ def role_exists(role, **kwargs): """ # We should get one, and only one row return ( - len(tsql_query(query='sp_helprole "{0}"'.format(role), as_dict=True, **kwargs)) + len(tsql_query(query='sp_helprole "{}"'.format(role), as_dict=True, **kwargs)) == 1 ) @@ -268,9 +263,9 @@ def role_create(role, owner=None, grants=None, **kwargs): if not grants: grants = [] - sql = "CREATE ROLE {0}".format(role) + sql = "CREATE ROLE {}".format(role) if owner: - sql += " AUTHORIZATION {0}".format(owner) + sql += " AUTHORIZATION {}".format(owner) conn = None try: conn = _get_connection(**kwargs) @@ -279,9 +274,9 @@ def role_create(role, owner=None, grants=None, **kwargs): # cur.execute(sql) conn.cursor().execute(sql) for grant in grants: - conn.cursor().execute("GRANT {0} TO [{1}]".format(grant, role)) + conn.cursor().execute("GRANT {} TO [{}]".format(grant, role)) except Exception as e: # pylint: disable=broad-except - return "Could not create the role: {0}".format(e) + return "Could not create the role: {}".format(e) finally: if conn: conn.autocommit(False) @@ -303,12 +298,12 @@ def role_remove(role, **kwargs): conn = _get_connection(**kwargs) conn.autocommit(True) cur = conn.cursor() - cur.execute("DROP ROLE {0}".format(role)) + cur.execute("DROP ROLE {}".format(role)) conn.autocommit(True) conn.close() return True except Exception as e: # pylint: disable=broad-except - return "Could not remove the role: {0}".format(e) + return "Could not remove the role: {}".format(e) def login_exists(login, domain="", **kwargs): @@ -323,13 +318,13 @@ def login_exists(login, domain="", **kwargs): salt minion mssql.login_exists 'LOGIN' """ if domain: - login = "{0}\\{1}".format(domain, login) + login = "{}\\{}".format(domain, login) try: # We should get one, and only one row return ( len( tsql_query( - query="SELECT name FROM sys.syslogins WHERE name='{0}'".format( + query="SELECT name FROM sys.syslogins WHERE name='{}'".format( login ), **kwargs @@ -339,7 +334,7 @@ def login_exists(login, domain="", **kwargs): ) except Exception as e: # pylint: disable=broad-except - return "Could not find the login: {0}".format(e) + return "Could not find the login: {}".format(e) def login_create( @@ -375,21 +370,19 @@ def login_create( if login_exists(login, new_login_domain, **kwargs): return False if new_login_domain: - login = "{0}\\{1}".format(new_login_domain, login) + login = "{}\\{}".format(new_login_domain, login) if not new_login_roles: new_login_roles = [] if not new_login_options: new_login_options = [] - sql = "CREATE LOGIN [{0}] ".format(login) + sql = "CREATE LOGIN [{}] ".format(login) if new_login_domain: sql += " FROM WINDOWS " - elif isinstance(new_login_password, six.integer_types): - new_login_options.insert( - 0, "PASSWORD=0x{0:x} HASHED".format(new_login_password) - ) + elif isinstance(new_login_password, int): + new_login_options.insert(0, "PASSWORD=0x{:x} HASHED".format(new_login_password)) else: # Plain test password - new_login_options.insert(0, "PASSWORD=N'{0}'".format(new_login_password)) + new_login_options.insert(0, "PASSWORD=N'{}'".format(new_login_password)) if new_login_options: sql += " WITH " + ", ".join(new_login_options) conn = None @@ -401,10 +394,10 @@ def login_create( conn.cursor().execute(sql) for role in new_login_roles: conn.cursor().execute( - "ALTER SERVER ROLE [{0}] ADD MEMBER [{1}]".format(role, login) + "ALTER SERVER ROLE [{}] ADD MEMBER [{}]".format(role, login) ) except Exception as e: # pylint: disable=broad-except - return "Could not create the login: {0}".format(e) + return "Could not create the login: {}".format(e) finally: if conn: conn.autocommit(False) @@ -426,12 +419,12 @@ def login_remove(login, **kwargs): conn = _get_connection(**kwargs) conn.autocommit(True) cur = conn.cursor() - cur.execute("DROP LOGIN [{0}]".format(login)) + cur.execute("DROP LOGIN [{}]".format(login)) conn.autocommit(False) conn.close() return True except Exception as e: # pylint: disable=broad-except - return "Could not remove the login: {0}".format(e) + return "Could not remove the login: {}".format(e) def user_exists(username, domain="", database=None, **kwargs): @@ -446,14 +439,14 @@ def user_exists(username, domain="", database=None, **kwargs): salt minion mssql.user_exists 'USERNAME' [database='DBNAME'] """ if domain: - username = "{0}\\{1}".format(domain, username) + username = "{}\\{}".format(domain, username) if database: kwargs["database"] = database # We should get one, and only one row return ( len( tsql_query( - query="SELECT name FROM sysusers WHERE name='{0}'".format(username), + query="SELECT name FROM sysusers WHERE name='{}'".format(username), **kwargs ) ) @@ -498,10 +491,10 @@ def user_create( if domain and not login: return "domain cannot be set without login" if user_exists(username, domain, **kwargs): - return "User {0} already exists".format(username) + return "User {} already exists".format(username) if domain: - username = "{0}\\{1}".format(domain, username) - login = "{0}\\{1}".format(domain, login) if login else login + username = "{}\\{}".format(domain, username) + login = "{}\\{}".format(domain, login) if login else login if database: kwargs["database"] = database if not roles: @@ -509,12 +502,12 @@ def user_create( if not options: options = [] - sql = "CREATE USER [{0}] ".format(username) + sql = "CREATE USER [{}] ".format(username) if login: # If the login does not exist, user creation will throw # if not login_exists(name, **kwargs): # return False - sql += " FOR LOGIN [{0}]".format(login) + sql += " FOR LOGIN [{}]".format(login) else: # Plain test password sql += " WITHOUT LOGIN" if options: @@ -528,10 +521,10 @@ def user_create( conn.cursor().execute(sql) for role in roles: conn.cursor().execute( - "ALTER ROLE [{0}] ADD MEMBER [{1}]".format(role, username) + "ALTER ROLE [{}] ADD MEMBER [{}]".format(role, username) ) except Exception as e: # pylint: disable=broad-except - return "Could not create the user: {0}".format(e) + return "Could not create the user: {}".format(e) finally: if conn: conn.autocommit(False) @@ -556,9 +549,9 @@ def user_remove(username, **kwargs): conn = _get_connection(**kwargs) conn.autocommit(True) cur = conn.cursor() - cur.execute("DROP USER {0}".format(username)) + cur.execute("DROP USER {}".format(username)) conn.autocommit(False) conn.close() return True except Exception as e: # pylint: disable=broad-except - return "Could not remove the user: {0}".format(e) + return "Could not remove the user: {}".format(e) diff --git a/salt/modules/msteams.py b/salt/modules/msteams.py index 2b64e55e3ae..c85a186ce99 100644 --- a/salt/modules/msteams.py +++ b/salt/modules/msteams.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Module for sending messages to MS Teams @@ -13,15 +12,9 @@ Module for sending messages to MS Teams msteams: hook_url: https://outlook.office.com/webhook/837 """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import logging -# Import 3rd-party libs -import salt.ext.six.moves.http_client # pylint: disable=import-error,no-name-in-module,redefined-builtin - -# Import Salt libs import salt.utils.json from salt.exceptions import SaltInvocationError diff --git a/salt/modules/munin.py b/salt/modules/munin.py index dc1fe4de590..ced668011f0 100644 --- a/salt/modules/munin.py +++ b/salt/modules/munin.py @@ -1,19 +1,13 @@ -# -*- coding: utf-8 -*- """ Run munin plugins/checks from salt and format the output as data. """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import os import stat import salt.utils.files import salt.utils.stringutils -# Import salt libs -from salt.ext import six - PLUGINDIR = "/etc/munin/plugins/" @@ -47,7 +41,7 @@ def run(plugins): """ all_plugins = list_plugins() - if isinstance(plugins, six.string_types): + if isinstance(plugins, str): plugins = plugins.split(",") data = {} @@ -56,7 +50,7 @@ def run(plugins): continue data[plugin] = {} muninout = __salt__["cmd.run"]( - "munin-run {0}".format(plugin), python_shell=False + "munin-run {}".format(plugin), python_shell=False ) for line in muninout.split("\n"): if "value" in line: # This skips multigraph lines, etc diff --git a/salt/modules/nagios.py b/salt/modules/nagios.py index dc1d5b0c9c2..20801f6da95 100644 --- a/salt/modules/nagios.py +++ b/salt/modules/nagios.py @@ -1,18 +1,12 @@ -# -*- coding: utf-8 -*- """ Run nagios plugins/checks from salt and get the return as data. """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import logging import os import stat -# Import 3rd-party libs -from salt.ext import six - log = logging.getLogger(__name__) PLUGINDIR = "/usr/lib/nagios/plugins/" @@ -39,7 +33,7 @@ def _execute_cmd(plugin, args="", run_type="cmd.retcode"): all_plugins = list_plugins() if plugin in all_plugins: data = __salt__[run_type]( - "{0}{1} {2}".format(PLUGINDIR, plugin, args), python_shell=False + "{}{} {}".format(PLUGINDIR, plugin, args), python_shell=False ) return data @@ -70,7 +64,7 @@ def _execute_pillar(pillar_name, run_type): # Check if is a dict to get the arguments # in command if not set the arguments to empty string if isinstance(command, dict): - plugin = next(six.iterkeys(command)) + plugin = next(iter(command.keys())) args = command[plugin] else: plugin = command @@ -171,7 +165,7 @@ def retcode_pillar(pillar_name): # Check if is a dict to get the arguments # in command if not set the arguments to empty string if isinstance(command, dict): - plugin = next(six.iterkeys(command)) + plugin = next(iter(command.keys())) args = command[plugin] else: plugin = command diff --git a/salt/modules/nagios_rpc.py b/salt/modules/nagios_rpc.py index 6fc13c1bf0a..0f7969dbf38 100644 --- a/salt/modules/nagios_rpc.py +++ b/salt/modules/nagios_rpc.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Check Host & Service status from Nagios via JSON RPC. @@ -6,19 +5,13 @@ Check Host & Service status from Nagios via JSON RPC. """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals +import http.client import logging -# Import Salt libs -# pylint: disable=import-error,no-name-in-module,redefined-builtin -import salt.ext.six.moves.http_client import salt.utils.http from salt.exceptions import CommandExecutionError -# pylint: enable=import-error,no-name-in-module - log = logging.getLogger(__name__) @@ -94,18 +87,18 @@ def _status_query(query, hostname, enumerate=None, service=None): ret["result"] = False return ret - if result.get("status", None) == salt.ext.six.moves.http_client.OK: + if result.get("status", None) == http.client.OK: try: ret["json_data"] = result["dict"] ret["result"] = True except ValueError: ret["error"] = "Please ensure Nagios is running." - elif result.get("status", None) == salt.ext.six.moves.http_client.UNAUTHORIZED: + elif result.get("status", None) == http.client.UNAUTHORIZED: ret["error"] = "Authentication failed. Please check the configuration." - elif result.get("status", None) == salt.ext.six.moves.http_client.NOT_FOUND: - ret["error"] = "URL {0} was not found.".format(config["url"]) + elif result.get("status", None) == http.client.NOT_FOUND: + ret["error"] = "URL {} was not found.".format(config["url"]) else: - ret["error"] = "Results: {0}".format(result.text) + ret["error"] = "Results: {}".format(result.text) return ret diff --git a/salt/modules/namecheap_domains.py b/salt/modules/namecheap_domains.py index b30abe8f34d..7ba19fd1048 100644 --- a/salt/modules/namecheap_domains.py +++ b/salt/modules/namecheap_domains.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Namecheap Domain Management @@ -26,13 +25,9 @@ file, or in the Pillar data. #Sandbox url #namecheap.url: https://api.sandbox.namecheap.xml.response """ -from __future__ import absolute_import, print_function, unicode_literals import logging -# Import 3rd-party libs -from salt.ext import six - CAN_USE_NAMECHEAP = True try: @@ -306,7 +301,7 @@ def create(domain_name, years, **kwargs): ] opts = salt.utils.namecheap.get_opts("namecheap.domains.create") opts["DomainName"] = domain_name - opts["Years"] = six.text_type(years) + opts["Years"] = str(years) def add_to_opts(opts_dict, kwargs, value, suffix, prefices): for prefix in prefices: @@ -314,7 +309,7 @@ def create(domain_name, years, **kwargs): if nextkey not in kwargs: opts_dict[nextkey] = value - for key, value in six.iteritems(kwargs): + for key, value in kwargs.items(): if key.startswith("Registrant"): add_to_opts( opts, diff --git a/salt/modules/namecheap_domains_dns.py b/salt/modules/namecheap_domains_dns.py index ae3cd142066..ef6789ec778 100644 --- a/salt/modules/namecheap_domains_dns.py +++ b/salt/modules/namecheap_domains_dns.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Namecheap DNS Management @@ -27,11 +26,6 @@ file, or in the Pillar data. #namecheap.url: https://api.sandbox.namecheap.xml.response """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - -# Import Salt libs -from salt.ext import six CAN_USE_NAMECHEAP = True @@ -155,7 +149,7 @@ def set_hosts(sld, tld, hosts): opts["TLD"] = tld i = 1 for hostrecord in hosts: - str_i = six.text_type(i) + str_i = str(i) opts["HostName" + str_i] = hostrecord["hostname"] opts["RecordType" + str_i] = hostrecord["recordtype"] opts["Address" + str_i] = hostrecord["address"] diff --git a/salt/modules/namecheap_domains_ns.py b/salt/modules/namecheap_domains_ns.py index e606e420245..b3ebe18910c 100644 --- a/salt/modules/namecheap_domains_ns.py +++ b/salt/modules/namecheap_domains_ns.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Namecheap Nameserver Management @@ -26,7 +25,6 @@ file, or in the Pillar data. #Sandbox url #namecheap.url: https://api.sandbox.namecheap.xml.response """ -from __future__ import absolute_import, print_function, unicode_literals CAN_USE_NAMECHEAP = True diff --git a/salt/modules/namecheap_ssl.py b/salt/modules/namecheap_ssl.py index 43233b172c4..27f27b1ddd5 100644 --- a/salt/modules/namecheap_ssl.py +++ b/salt/modules/namecheap_ssl.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Namecheap SSL Certificate Management @@ -26,18 +25,12 @@ file, or in the Pillar data. #Sandbox url #namecheap.url: https://api.sandbox.namecheap.xml.response """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import logging -# Import Salt libs import salt.utils.files import salt.utils.stringutils -# Import 3rd-party libs -from salt.ext import six - try: import salt.utils.namecheap @@ -291,7 +284,7 @@ def __get_certificates( if http_dc_validation: opts["HTTPDCValidation"] = "True" - for key, value in six.iteritems(kwargs): + for key, value in kwargs.items(): opts[key] = value response_xml = salt.utils.namecheap.post_request(opts) @@ -419,12 +412,12 @@ def renew(years, certificate_id, certificate_type, promotion_code=None): raise Exception("Invalid option for certificate_type=" + certificate_type) if years < 1 or years > 5: - log.error("Invalid option for years=%s", six.text_type(years)) - raise Exception("Invalid option for years=" + six.text_type(years)) + log.error("Invalid option for years=%s", str(years)) + raise Exception("Invalid option for years=" + str(years)) opts = salt.utils.namecheap.get_opts("namecheap.ssl.renew") - opts["Years"] = six.text_type(years) - opts["CertificateID"] = six.text_type(certificate_id) + opts["Years"] = str(years) + opts["CertificateID"] = str(certificate_id) opts["SSLType"] = certificate_type if promotion_code is not None: opts["PromotionCode"] = promotion_code @@ -598,8 +591,8 @@ def create(years, certificate_type, promotion_code=None, sans_to_add=None): raise Exception("Invalid option for certificate_type=" + certificate_type) if years < 1 or years > 5: - log.error("Invalid option for years=%s", six.text_type(years)) - raise Exception("Invalid option for years=" + six.text_type(years)) + log.error("Invalid option for years=%s", str(years)) + raise Exception("Invalid option for years=" + str(years)) opts = salt.utils.namecheap.get_opts("namecheap.ssl.create") @@ -767,7 +760,7 @@ def get_list(**kwargs): salt 'my-minion' namecheap_ssl.get_list Processing """ opts = salt.utils.namecheap.get_opts("namecheap.ssl.getList") - for key, value in six.iteritems(kwargs): + for key, value in kwargs.items(): opts[key] = value response_xml = salt.utils.namecheap.get_request(opts) diff --git a/salt/modules/namecheap_users.py b/salt/modules/namecheap_users.py index c26b30e6a2c..5affa948456 100644 --- a/salt/modules/namecheap_users.py +++ b/salt/modules/namecheap_users.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Namecheap User Management @@ -26,7 +25,6 @@ file, or in the Pillar data. #Sandbox url #namecheap.url: https://api.sandbox.namecheap.xml.response """ -from __future__ import absolute_import, print_function, unicode_literals CAN_USE_NAMECHEAP = True diff --git a/salt/modules/netbsdservice.py b/salt/modules/netbsdservice.py index 6a77e0f196d..7b36be1a214 100644 --- a/salt/modules/netbsdservice.py +++ b/salt/modules/netbsdservice.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ The service module for NetBSD @@ -8,12 +7,9 @@ The service module for NetBSD *'service.start' is not available*), see :ref:`here `. """ -from __future__ import absolute_import, print_function, unicode_literals import fnmatch import glob - -# Import python libs import os import re @@ -45,7 +41,7 @@ def start(name): salt '*' service.start """ - cmd = "/etc/rc.d/{0} onestart".format(name) + cmd = "/etc/rc.d/{} onestart".format(name) return not __salt__["cmd.retcode"](cmd) @@ -59,7 +55,7 @@ def stop(name): salt '*' service.stop """ - cmd = "/etc/rc.d/{0} onestop".format(name) + cmd = "/etc/rc.d/{} onestop".format(name) return not __salt__["cmd.retcode"](cmd) @@ -73,7 +69,7 @@ def restart(name): salt '*' service.restart """ - cmd = "/etc/rc.d/{0} onerestart".format(name) + cmd = "/etc/rc.d/{} onerestart".format(name) return not __salt__["cmd.retcode"](cmd) @@ -87,7 +83,7 @@ def reload_(name): salt '*' service.reload """ - cmd = "/etc/rc.d/{0} onereload".format(name) + cmd = "/etc/rc.d/{} onereload".format(name) return not __salt__["cmd.retcode"](cmd) @@ -101,7 +97,7 @@ def force_reload(name): salt '*' service.force_reload """ - cmd = "/etc/rc.d/{0} forcereload".format(name) + cmd = "/etc/rc.d/{} forcereload".format(name) return not __salt__["cmd.retcode"](cmd) @@ -138,7 +134,7 @@ def status(name, sig=None): services = [name] results = {} for service in services: - cmd = "/etc/rc.d/{0} onestatus".format(service) + cmd = "/etc/rc.d/{} onestatus".format(service) results[service] = not __salt__["cmd.retcode"](cmd, ignore_retcode=True) if contains_globbing: return results @@ -150,9 +146,9 @@ def _get_svc(rcd, service_status): Returns a unique service status """ ena = None - lines = __salt__["cmd.run"]("{0} rcvar".format(rcd)).splitlines() + lines = __salt__["cmd.run"]("{} rcvar".format(rcd)).splitlines() for rcvar in lines: - if rcvar.startswith("$") and "={0}".format(service_status) in rcvar: + if rcvar.startswith("$") and "={}".format(service_status) in rcvar: ena = "yes" elif rcvar.startswith("#"): svc = rcvar.split(" ", 1)[1] @@ -170,7 +166,7 @@ def _get_svc_list(service_status): """ prefix = "/etc/rc.d/" ret = set() - lines = glob.glob("{0}*".format(prefix)) + lines = glob.glob("{}*".format(prefix)) for line in lines: svc = _get_svc(line, service_status) if svc is not None: @@ -253,9 +249,9 @@ def _rcconf_status(name, service_status): can be started via /etc/rc.d/ """ rcconf = "/etc/rc.conf" - rxname = "^{0}=.*".format(name) - newstatus = "{0}={1}".format(name, service_status) - ret = __salt__["cmd.retcode"]("grep '{0}' {1}".format(rxname, rcconf)) + rxname = "^{}=.*".format(name) + newstatus = "{}={}".format(name, service_status) + ret = __salt__["cmd.retcode"]("grep '{}' {}".format(rxname, rcconf)) if ret == 0: # service found in rc.conf, modify its status __salt__["file.replace"](rcconf, rxname, newstatus) else: @@ -300,7 +296,7 @@ def enabled(name, **kwargs): salt '*' service.enabled """ - return _get_svc("/etc/rc.d/{0}".format(name), "YES") + return _get_svc("/etc/rc.d/{}".format(name), "YES") def disabled(name): @@ -313,7 +309,7 @@ def disabled(name): salt '*' service.disabled """ - return _get_svc("/etc/rc.d/{0}".format(name), "NO") + return _get_svc("/etc/rc.d/{}".format(name), "NO") # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 diff --git a/salt/modules/neutronng.py b/salt/modules/neutronng.py index 07f0f1f0ddb..5595e1989cc 100644 --- a/salt/modules/neutronng.py +++ b/salt/modules/neutronng.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Neutron module for interacting with OpenStack Neutron @@ -26,7 +25,6 @@ Example configuration identity_api_version: 3 """ -from __future__ import absolute_import, print_function, unicode_literals HAS_SHADE = False try: diff --git a/salt/modules/nginx.py b/salt/modules/nginx.py index accc7c40642..b684df5f6ff 100644 --- a/salt/modules/nginx.py +++ b/salt/modules/nginx.py @@ -3,10 +3,10 @@ Support for nginx """ import re +import urllib.request import salt.utils.decorators as decorators import salt.utils.path -from salt.ext.six.moves.urllib.request import urlopen as _urlopen # Cache the output of running which('nginx') so this module @@ -148,7 +148,7 @@ def status(url="http://127.0.0.1/status"): salt '*' nginx.status """ - resp = _urlopen(url) + resp = urllib.request.urlopen(url) status_data = resp.read() resp.close() diff --git a/salt/modules/nilrt_ip.py b/salt/modules/nilrt_ip.py index efba3a330af..55162a39f7f 100644 --- a/salt/modules/nilrt_ip.py +++ b/salt/modules/nilrt_ip.py @@ -3,6 +3,7 @@ The networking module for NI Linux Real-Time distro """ +import configparser import logging import os import re @@ -11,7 +12,6 @@ import time import salt.exceptions import salt.utils.files import salt.utils.validate.net -from salt.ext.six.moves import configparser try: import pyconnman diff --git a/salt/modules/nix.py b/salt/modules/nix.py index da3e0eaf39d..afe6a49f54b 100644 --- a/salt/modules/nix.py +++ b/salt/modules/nix.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Work with Nix packages ====================== @@ -19,7 +18,6 @@ For more information on nix, see the `nix documentation`_. .. _`nix-daemon`: https://nixos.org/nix/manual/#ssec-multi-user """ -from __future__ import absolute_import, print_function, unicode_literals import itertools import logging @@ -27,7 +25,6 @@ import os import salt.utils.itertools import salt.utils.path -from salt.ext.six.moves import zip logger = logging.getLogger(__name__) @@ -37,7 +34,7 @@ def __virtual__(): This only works if we have access to nix-env """ nixhome = os.path.join( - os.path.expanduser("~{0}".format(__opts__["user"])), ".nix-profile/bin/" + os.path.expanduser("~{}".format(__opts__["user"])), ".nix-profile/bin/" ) if salt.utils.path.which( os.path.join(nixhome, "nix-env") @@ -55,7 +52,7 @@ def _run(cmd): Just a convenience function for ``__salt__['cmd.run_all'](cmd)`` """ return __salt__["cmd.run_all"]( - cmd, env={"HOME": os.path.expanduser("~{0}".format(__opts__["user"]))} + cmd, env={"HOME": os.path.expanduser("~{}".format(__opts__["user"]))} ) @@ -65,7 +62,7 @@ def _nix_env(): only show changes. """ nixhome = os.path.join( - os.path.expanduser("~{0}".format(__opts__["user"])), ".nix-profile/bin/" + os.path.expanduser("~{}".format(__opts__["user"])), ".nix-profile/bin/" ) return [os.path.join(nixhome, "nix-env")] @@ -75,7 +72,7 @@ def _nix_collect_garbage(): Make sure we get the right nix-store, too. """ nixhome = os.path.join( - os.path.expanduser("~{0}".format(__opts__["user"])), ".nix-profile/bin/" + os.path.expanduser("~{}".format(__opts__["user"])), ".nix-profile/bin/" ) return [os.path.join(nixhome, "nix-collect-garbage")] diff --git a/salt/modules/nova.py b/salt/modules/nova.py index 260f2d8337b..658b752bad8 100644 --- a/salt/modules/nova.py +++ b/salt/modules/nova.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Module for handling OpenStack Nova calls @@ -68,9 +67,7 @@ Module for handling OpenStack Nova calls keystoneauth to search for the certificates on its own. (defaults to True) """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import logging # Get logging started diff --git a/salt/modules/omapi.py b/salt/modules/omapi.py index ef3f454909b..c63d94d3dae 100644 --- a/salt/modules/omapi.py +++ b/salt/modules/omapi.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ This module interacts with an ISC DHCP Server via OMAPI. server_ip and server_port params may be set in the minion @@ -12,13 +11,10 @@ config or pillar: :depends: pypureomapi Python module """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import logging import struct -# Import salt libs import salt.utils.stringutils log = logging.getLogger(__name__) @@ -91,9 +87,9 @@ def add_host(mac, name=None, ip=None, ddns=False, group=None, supersede_host=Fal if group: msg.obj.append((b"group", salt.utils.stringutils.to_bytes(group))) if supersede_host: - statements += 'option host-name "{0}"; '.format(name) + statements += 'option host-name "{}"; '.format(name) if ddns and name: - statements += 'ddns-hostname "{0}"; '.format(name) + statements += 'ddns-hostname "{}"; '.format(name) if statements: msg.obj.append((b"statements", salt.utils.stringutils.to_bytes(statements))) response = o.query_server(msg) diff --git a/salt/modules/openbsdrcctl_service.py b/salt/modules/openbsdrcctl_service.py index 83909a16c7f..4ee17d0a4b4 100644 --- a/salt/modules/openbsdrcctl_service.py +++ b/salt/modules/openbsdrcctl_service.py @@ -1,15 +1,10 @@ -# -*- coding: utf-8 -*- """ The rcctl service module for OpenBSD """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import os import salt.utils.decorators as decorators - -# Import salt libs import salt.utils.path from salt.exceptions import CommandNotFoundError @@ -61,7 +56,7 @@ def available(name): salt '*' service.available sshd """ - cmd = "{0} get {1}".format(_cmd(), name) + cmd = "{} get {}".format(_cmd(), name) if __salt__["cmd.retcode"](cmd) == 2: return False return True @@ -93,7 +88,7 @@ def get_all(): """ ret = [] service = _cmd() - for svc in __salt__["cmd.run"]("{0} ls all".format(service)).splitlines(): + for svc in __salt__["cmd.run"]("{} ls all".format(service)).splitlines(): ret.append(svc) return sorted(ret) @@ -110,7 +105,7 @@ def get_disabled(): """ ret = [] service = _cmd() - for svc in __salt__["cmd.run"]("{0} ls off".format(service)).splitlines(): + for svc in __salt__["cmd.run"]("{} ls off".format(service)).splitlines(): ret.append(svc) return sorted(ret) @@ -127,7 +122,7 @@ def get_enabled(): """ ret = [] service = _cmd() - for svc in __salt__["cmd.run"]("{0} ls on".format(service)).splitlines(): + for svc in __salt__["cmd.run"]("{} ls on".format(service)).splitlines(): ret.append(svc) return sorted(ret) @@ -142,7 +137,7 @@ def start(name): salt '*' service.start """ - cmd = "{0} -f start {1}".format(_cmd(), name) + cmd = "{} -f start {}".format(_cmd(), name) return not __salt__["cmd.retcode"](cmd) @@ -156,7 +151,7 @@ def stop(name): salt '*' service.stop """ - cmd = "{0} stop {1}".format(_cmd(), name) + cmd = "{} stop {}".format(_cmd(), name) return not __salt__["cmd.retcode"](cmd) @@ -170,7 +165,7 @@ def restart(name): salt '*' service.restart """ - cmd = "{0} -f restart {1}".format(_cmd(), name) + cmd = "{} -f restart {}".format(_cmd(), name) return not __salt__["cmd.retcode"](cmd) @@ -184,7 +179,7 @@ def reload_(name): salt '*' service.reload """ - cmd = "{0} reload {1}".format(_cmd(), name) + cmd = "{} reload {}".format(_cmd(), name) return not __salt__["cmd.retcode"](cmd) @@ -202,7 +197,7 @@ def status(name, sig=None): if sig: return bool(__salt__["status.pid"](sig)) - cmd = "{0} check {1}".format(_cmd(), name) + cmd = "{} check {}".format(_cmd(), name) return not __salt__["cmd.retcode"](cmd) @@ -222,14 +217,14 @@ def enable(name, **kwargs): salt '*' service.enable salt '*' service.enable flags= """ - stat_cmd = "{0} set {1} status on".format(_cmd(), name) + stat_cmd = "{} set {} status on".format(_cmd(), name) stat_retcode = __salt__["cmd.retcode"](stat_cmd) flag_retcode = None # only (re)set flags for services that have an rc.d(8) script - if os.path.exists("/etc/rc.d/{0}".format(name)): + if os.path.exists("/etc/rc.d/{}".format(name)): flags = _get_flags(**kwargs) - flag_cmd = "{0} set {1} flags {2}".format(_cmd(), name, flags) + flag_cmd = "{} set {} flags {}".format(_cmd(), name, flags) flag_retcode = __salt__["cmd.retcode"](flag_cmd) return not any([stat_retcode, flag_retcode]) @@ -245,7 +240,7 @@ def disable(name, **kwargs): salt '*' service.disable """ - cmd = "{0} set {1} status off".format(_cmd(), name) + cmd = "{} set {} status off".format(_cmd(), name) return not __salt__["cmd.retcode"](cmd) @@ -259,7 +254,7 @@ def disabled(name): salt '*' service.disabled """ - cmd = "{0} get {1} status".format(_cmd(), name) + cmd = "{} get {} status".format(_cmd(), name) return not __salt__["cmd.retcode"](cmd) == 0 @@ -278,17 +273,17 @@ def enabled(name, **kwargs): salt '*' service.enabled salt '*' service.enabled flags= """ - cmd = "{0} get {1} status".format(_cmd(), name) + cmd = "{} get {} status".format(_cmd(), name) if not __salt__["cmd.retcode"](cmd): # also consider a service disabled if the current flags are different # than the configured ones so we have a chance to update them flags = _get_flags(**kwargs) - cur_flags = __salt__["cmd.run_stdout"]("{0} get {1} flags".format(_cmd(), name)) + cur_flags = __salt__["cmd.run_stdout"]("{} get {} flags".format(_cmd(), name)) if format(flags) == format(cur_flags): return True if not flags: def_flags = __salt__["cmd.run_stdout"]( - "{0} getdef {1} flags".format(_cmd(), name) + "{} getdef {} flags".format(_cmd(), name) ) if format(cur_flags) == format(def_flags): return True diff --git a/salt/modules/openbsdservice.py b/salt/modules/openbsdservice.py index 49bf938c10a..b68d217b448 100644 --- a/salt/modules/openbsdservice.py +++ b/salt/modules/openbsdservice.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ The service module for OpenBSD @@ -9,22 +8,15 @@ The service module for OpenBSD `. """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import fnmatch import logging import os import re -# Import Salt libs import salt.utils.data import salt.utils.files -# Import 3rd-party libs -from salt.ext import six -from salt.ext.six.moves import map # pylint: disable=import-error,redefined-builtin - log = logging.getLogger(__name__) # XXX enable/disable support would be nice @@ -64,7 +56,7 @@ def start(name): salt '*' service.start """ - cmd = "/etc/rc.d/{0} -f start".format(name) + cmd = "/etc/rc.d/{} -f start".format(name) return not __salt__["cmd.retcode"](cmd) @@ -78,7 +70,7 @@ def stop(name): salt '*' service.stop """ - cmd = "/etc/rc.d/{0} -f stop".format(name) + cmd = "/etc/rc.d/{} -f stop".format(name) return not __salt__["cmd.retcode"](cmd) @@ -92,7 +84,7 @@ def restart(name): salt '*' service.restart """ - cmd = "/etc/rc.d/{0} -f restart".format(name) + cmd = "/etc/rc.d/{} -f restart".format(name) return not __salt__["cmd.retcode"](cmd) @@ -129,7 +121,7 @@ def status(name, sig=None): services = [name] results = {} for service in services: - cmd = "/etc/rc.d/{0} -f check".format(service) + cmd = "/etc/rc.d/{} -f check".format(service) results[service] = not __salt__["cmd.retcode"](cmd, ignore_retcode=True) if contains_globbing: return results @@ -148,7 +140,7 @@ def reload_(name): salt '*' service.reload """ - cmd = "/etc/rc.d/{0} -f reload".format(name) + cmd = "/etc/rc.d/{} -f reload".format(name) return not __salt__["cmd.retcode"](cmd) @@ -173,7 +165,7 @@ def _get_rc(): # to know what are the system enabled daemons with salt.utils.files.fopen("/etc/rc", "r") as handle: lines = salt.utils.data.decode(handle.readlines()) - except IOError: + except OSError: log.error("Unable to read /etc/rc") else: for line in lines: @@ -228,7 +220,7 @@ def available(name): salt '*' service.available sshd """ - path = "/etc/rc.d/{0}".format(name) + path = "/etc/rc.d/{}".format(name) return os.path.isfile(path) and os.access(path, os.X_OK) @@ -284,7 +276,7 @@ def get_enabled(): salt '*' service.get_enabled """ services = [] - for daemon, is_enabled in six.iteritems(_get_rc()): + for daemon, is_enabled in _get_rc().items(): if is_enabled: services.append(daemon) return sorted(set(get_all()) & set(services)) @@ -318,7 +310,7 @@ def get_disabled(): salt '*' service.get_disabled """ services = [] - for daemon, is_enabled in six.iteritems(_get_rc()): + for daemon, is_enabled in _get_rc().items(): if not is_enabled: services.append(daemon) return sorted(set(get_all()) & set(services)) diff --git a/salt/modules/openscap.py b/salt/modules/openscap.py index 6f8ff4a76db..770c8e7c043 100644 --- a/salt/modules/openscap.py +++ b/salt/modules/openscap.py @@ -1,20 +1,14 @@ -# -*- coding: utf-8 -*- """ Module for OpenSCAP Management """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import shlex import shutil import tempfile from subprocess import PIPE, Popen -# Import Salt libs -from salt.ext import six - ArgumentParser = object try: @@ -44,7 +38,7 @@ def __virtual__(): class _ArgumentParser(ArgumentParser): def __init__(self, action=None, *args, **kwargs): - super(_ArgumentParser, self).__init__(*args, prog="oscap", **kwargs) + super().__init__(*args, prog="oscap", **kwargs) self.add_argument("action", choices=["eval"]) add_arg = None for params, kwparams in _XCCDF_MAP["eval"]["parser_arguments"]: @@ -91,7 +85,7 @@ def xccdf(params): args, argv = _ArgumentParser(action=action).parse_known_args(args=params) except Exception as err: # pylint: disable=broad-except success = False - error = six.text_type(err) + error = str(err) if success: cmd = _XCCDF_MAP[action]["cmd_pattern"].format(args.profile, policy) diff --git a/salt/modules/openstack_config.py b/salt/modules/openstack_config.py index 96df508fc2b..277f32af063 100644 --- a/salt/modules/openstack_config.py +++ b/salt/modules/openstack_config.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Modify, retrieve, or delete values from OpenStack configuration files. @@ -8,17 +7,12 @@ Modify, retrieve, or delete values from OpenStack configuration files. :platform: linux """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import shlex import salt.exceptions import salt.utils.decorators.path -# Import Salt libs -from salt.ext import six - try: import pipes @@ -75,10 +69,10 @@ def set_(filename, section, parameter, value): filename = _quote(filename) section = _quote(section) parameter = _quote(parameter) - value = _quote(six.text_type(value)) + value = _quote(str(value)) result = __salt__["cmd.run_all"]( - "openstack-config --set {0} {1} {2} {3}".format( + "openstack-config --set {} {} {} {}".format( filename, section, parameter, value ), python_shell=False, @@ -117,7 +111,7 @@ def get(filename, section, parameter): parameter = _quote(parameter) result = __salt__["cmd.run_all"]( - "openstack-config --get {0} {1} {2}".format(filename, section, parameter), + "openstack-config --get {} {} {}".format(filename, section, parameter), python_shell=False, ) @@ -153,7 +147,7 @@ def delete(filename, section, parameter): parameter = _quote(parameter) result = __salt__["cmd.run_all"]( - "openstack-config --del {0} {1} {2}".format(filename, section, parameter), + "openstack-config --del {} {} {}".format(filename, section, parameter), python_shell=False, ) diff --git a/salt/modules/openstack_mng.py b/salt/modules/openstack_mng.py index 07f0a292564..0c218bc2cb3 100644 --- a/salt/modules/openstack_mng.py +++ b/salt/modules/openstack_mng.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Module for OpenStack Management @@ -7,13 +6,10 @@ Module for OpenStack Management :depends: openstack-utils :platform: linux """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import logging import os.path -# Import salt libs import salt.utils.files import salt.utils.stringutils diff --git a/salt/modules/opsgenie.py b/salt/modules/opsgenie.py index 1d8a29a4796..93f0f296a4b 100644 --- a/salt/modules/opsgenie.py +++ b/salt/modules/opsgenie.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Module for sending data to OpsGenie @@ -20,14 +19,10 @@ Module for sending data to OpsGenie reason: {{ data['data']['reason'] }} action_type: Create """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import logging import requests - -# Import Salt libs import salt.exceptions import salt.utils.json diff --git a/salt/modules/panos.py b/salt/modules/panos.py index a1d1ea5f67c..2d18958d649 100644 --- a/salt/modules/panos.py +++ b/salt/modules/panos.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Module to provide Palo Alto compatibility to Salt @@ -28,16 +27,12 @@ through the XML API or through a brokered connection to Panorama. """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals import logging import time import salt.proxy.panos import salt.utils.platform - -# Import Salt Libs from salt.exceptions import CommandExecutionError log = logging.getLogger(__name__) @@ -194,7 +189,7 @@ def deactivate_license(key_name=None): if not __proxy__["panos.is_required_version"](_required_version): return ( False, - "The panos device requires version {0} or greater for this command.".format( + "The panos device requires version {} or greater for this command.".format( _required_version ), ) @@ -204,7 +199,7 @@ def deactivate_license(key_name=None): else: query = { "type": "op", - "cmd": "{0}" + "cmd": "{}" "".format(key_name), } @@ -230,9 +225,7 @@ def delete_license(key_name=None): else: query = { "type": "op", - "cmd": "{0}".format( - key_name - ), + "cmd": "{}".format(key_name), } return __proxy__["panos.call"](query) @@ -285,17 +278,13 @@ def download_software_file(filename=None, synch=False): query = { "type": "op", "cmd": "" - "{0}".format( - filename - ), + "{}".format(filename), } else: query = { "type": "op", "cmd": "yes" - "{0}".format( - filename - ), + "{}".format(filename), } return _get_job_results(query) @@ -328,7 +317,7 @@ def download_software_version(version=None, synch=False): query = { "type": "op", "cmd": "" - "{0}".format( + "{}".format( version ), } @@ -336,7 +325,7 @@ def download_software_version(version=None, synch=False): query = { "type": "op", "cmd": "yes" - "{0}".format( + "{}".format( version ), } @@ -367,7 +356,7 @@ def fetch_license(auth_code=None): else: query = { "type": "op", - "cmd": "{0}" + "cmd": "{}" "".format(auth_code), } @@ -394,8 +383,8 @@ def get_address(address=None, vsys="1"): query = { "type": "config", "action": "get", - "xpath": "/config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys{0}']/" - "address/entry[@name='{1}']".format(vsys, address), + "xpath": "/config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys{}']/" + "address/entry[@name='{}']".format(vsys, address), } return __proxy__["panos.call"](query) @@ -421,8 +410,8 @@ def get_address_group(addressgroup=None, vsys="1"): query = { "type": "config", "action": "get", - "xpath": "/config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys{0}']/" - "address-group/entry[@name='{1}']".format(vsys, addressgroup), + "xpath": "/config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys{}']/" + "address-group/entry[@name='{}']".format(vsys, addressgroup), } return __proxy__["panos.call"](query) @@ -762,9 +751,7 @@ def get_interface_counters(name="all"): """ query = { "type": "op", - "cmd": "{0}".format( - name - ), + "cmd": "{}".format(name), } return __proxy__["panos.call"](query) @@ -787,7 +774,7 @@ def get_interfaces(name="all"): """ query = { "type": "op", - "cmd": "{0}".format(name), + "cmd": "{}".format(name), } return __proxy__["panos.call"](query) @@ -810,7 +797,7 @@ def get_job(jid=None): if not jid: raise CommandExecutionError("ID option must not be none.") - query = {"type": "op", "cmd": "{0}".format(jid)} + query = {"type": "op", "cmd": "{}".format(jid)} return __proxy__["panos.call"](query) @@ -1159,9 +1146,7 @@ def get_predefined_application(application=None): query = { "type": "config", "action": "get", - "xpath": "/config/predefined/application/entry[@name='{0}']".format( - application - ), + "xpath": "/config/predefined/application/entry[@name='{}']".format(application), } return __proxy__["panos.call"](query) @@ -1186,8 +1171,8 @@ def get_security_rule(rulename=None, vsys="1"): query = { "type": "config", "action": "get", - "xpath": "/config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys{0}']/" - "rulebase/security/rules/entry[@name='{1}']".format(vsys, rulename), + "xpath": "/config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys{}']/" + "rulebase/security/rules/entry[@name='{}']".format(vsys, rulename), } return __proxy__["panos.call"](query) @@ -1213,8 +1198,8 @@ def get_service(service=None, vsys="1"): query = { "type": "config", "action": "get", - "xpath": "/config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys{0}']/" - "service/entry[@name='{1}']".format(vsys, service), + "xpath": "/config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys{}']/" + "service/entry[@name='{}']".format(vsys, service), } return __proxy__["panos.call"](query) @@ -1240,8 +1225,8 @@ def get_service_group(servicegroup=None, vsys="1"): query = { "type": "config", "action": "get", - "xpath": "/config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys{0}']/" - "service-group/entry[@name='{1}']".format(vsys, servicegroup), + "xpath": "/config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys{}']/" + "service-group/entry[@name='{}']".format(vsys, servicegroup), } return __proxy__["panos.call"](query) @@ -1385,7 +1370,7 @@ def get_system_state(mask=None): if mask: query = { "type": "op", - "cmd": "{0}".format( + "cmd": "{}".format( mask ), } @@ -1411,7 +1396,7 @@ def get_uncommitted_changes(): if not __proxy__["panos.is_required_version"](_required_version): return ( False, - "The panos device requires version {0} or greater for this command.".format( + "The panos device requires version {} or greater for this command.".format( _required_version ), ) @@ -1493,8 +1478,8 @@ def get_zone(zone="", vsys="1"): query = { "type": "config", "action": "get", - "xpath": "/config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys{0}']/" - "zone/entry[@name='{1}']".format(vsys, zone), + "xpath": "/config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys{}']/" + "zone/entry[@name='{}']".format(vsys, zone), } return __proxy__["panos.call"](query) @@ -1517,7 +1502,7 @@ def get_zones(vsys="1"): query = { "type": "config", "action": "get", - "xpath": "/config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys{0}']/" + "xpath": "/config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys{}']/" "zone".format(vsys), } @@ -1564,7 +1549,7 @@ def install_antivirus( query = { "type": "op", "cmd": "" - "{0}{1}" + "{}{}" "latest".format( c, s ), @@ -1573,8 +1558,8 @@ def install_antivirus( query = { "type": "op", "cmd": "" - "{0}{1}" - "{2}".format( + "{}{}" + "{}".format( c, s, version ), } @@ -1621,9 +1606,7 @@ def install_software(version=None): query = { "type": "op", "cmd": "" - "{0}".format( - version - ), + "{}".format(version), } return _get_job_results(query) @@ -1722,7 +1705,7 @@ def resolve_address(address=None, vsys=None): if not __proxy__["panos.is_required_version"](_required_version): return ( False, - "The panos device requires version {0} or greater for this command.".format( + "The panos device requires version {} or greater for this command.".format( _required_version ), ) @@ -1733,14 +1716,14 @@ def resolve_address(address=None, vsys=None): if not vsys: query = { "type": "op", - "cmd": "
{0}
".format( + "cmd": "
{}
".format( address ), } else: query = { "type": "op", - "cmd": "{0}
{1}
" + "cmd": "{}
{}
" "
".format(vsys, address), } @@ -1766,7 +1749,7 @@ def save_device_config(filename=None): query = { "type": "op", - "cmd": "{0}".format(filename), + "cmd": "{}".format(filename), } return __proxy__["panos.call"](query) @@ -1816,7 +1799,7 @@ def set_authentication_profile(profile=None, deploy=False): "action": "set", "xpath": "/config/devices/entry[@name='localhost.localdomain']/deviceconfig/system/" "authentication-profile", - "element": "{0}".format( + "element": "{}".format( profile ), } @@ -1856,7 +1839,7 @@ def set_hostname(hostname=None, deploy=False): "type": "config", "action": "set", "xpath": "/config/devices/entry[@name='localhost.localdomain']/deviceconfig/system", - "element": "{0}".format(hostname), + "element": "{}".format(hostname), } ret.update(__proxy__["panos.call"](query)) @@ -1900,7 +1883,7 @@ def set_management_icmp(enabled=True, deploy=False): "type": "config", "action": "set", "xpath": "/config/devices/entry[@name='localhost.localdomain']/deviceconfig/system/service", - "element": "{0}".format(value), + "element": "{}".format(value), } ret.update(__proxy__["panos.call"](query)) @@ -1944,7 +1927,7 @@ def set_management_http(enabled=True, deploy=False): "type": "config", "action": "set", "xpath": "/config/devices/entry[@name='localhost.localdomain']/deviceconfig/system/service", - "element": "{0}".format(value), + "element": "{}".format(value), } ret.update(__proxy__["panos.call"](query)) @@ -1988,7 +1971,7 @@ def set_management_https(enabled=True, deploy=False): "type": "config", "action": "set", "xpath": "/config/devices/entry[@name='localhost.localdomain']/deviceconfig/system/service", - "element": "{0}".format(value), + "element": "{}".format(value), } ret.update(__proxy__["panos.call"](query)) @@ -2032,7 +2015,7 @@ def set_management_ocsp(enabled=True, deploy=False): "type": "config", "action": "set", "xpath": "/config/devices/entry[@name='localhost.localdomain']/deviceconfig/system/service", - "element": "{0}".format(value), + "element": "{}".format(value), } ret.update(__proxy__["panos.call"](query)) @@ -2076,7 +2059,7 @@ def set_management_snmp(enabled=True, deploy=False): "type": "config", "action": "set", "xpath": "/config/devices/entry[@name='localhost.localdomain']/deviceconfig/system/service", - "element": "{0}".format(value), + "element": "{}".format(value), } ret.update(__proxy__["panos.call"](query)) @@ -2120,7 +2103,7 @@ def set_management_ssh(enabled=True, deploy=False): "type": "config", "action": "set", "xpath": "/config/devices/entry[@name='localhost.localdomain']/deviceconfig/system/service", - "element": "{0}".format(value), + "element": "{}".format(value), } ret.update(__proxy__["panos.call"](query)) @@ -2164,7 +2147,7 @@ def set_management_telnet(enabled=True, deploy=False): "type": "config", "action": "set", "xpath": "/config/devices/entry[@name='localhost.localdomain']/deviceconfig/system/service", - "element": "{0}".format(value), + "element": "{}".format(value), } ret.update(__proxy__["panos.call"](query)) @@ -2338,7 +2321,7 @@ def set_ntp_servers(primary_server=None, secondary_server=None, deploy=False): "action": "set", "xpath": "/config/devices/entry[@name='localhost.localdomain']/deviceconfig/system/ntp-servers/" "primary-ntp-server", - "element": "{0}".format( + "element": "{}".format( primary_server ), } @@ -2350,7 +2333,7 @@ def set_ntp_servers(primary_server=None, secondary_server=None, deploy=False): "action": "set", "xpath": "/config/devices/entry[@name='localhost.localdomain']/deviceconfig/system/ntp-servers/" "secondary-ntp-server", - "element": "{0}".format( + "element": "{}".format( secondary_server ), } @@ -2390,7 +2373,7 @@ def set_permitted_ip(address=None, deploy=False): "type": "config", "action": "set", "xpath": "/config/devices/entry[@name='localhost.localdomain']/deviceconfig/system/permitted-ip", - "element": "".format(address), + "element": "".format(address), } ret.update(__proxy__["panos.call"](query)) @@ -2428,7 +2411,7 @@ def set_timezone(tz=None, deploy=False): "type": "config", "action": "set", "xpath": "/config/devices/entry[@name='localhost.localdomain']/deviceconfig/system/timezone", - "element": "{0}".format(tz), + "element": "{}".format(tz), } ret.update(__proxy__["panos.call"](query)) @@ -2478,10 +2461,10 @@ def test_fib_route(ip=None, vr="vr1"): xpath = "" if ip: - xpath += "{0}".format(ip) + xpath += "{}".format(ip) if vr: - xpath += "{0}".format(vr) + xpath += "{}".format(vr) xpath += "" @@ -2537,35 +2520,35 @@ def test_security_policy( xpath = "" if sourcezone: - xpath += "{0}".format(sourcezone) + xpath += "{}".format(sourcezone) if destinationzone: - xpath += "{0}".format(destinationzone) + xpath += "{}".format(destinationzone) if source: - xpath += "{0}".format(source) + xpath += "{}".format(source) if destination: - xpath += "{0}".format(destination) + xpath += "{}".format(destination) if protocol: - xpath += "{0}".format(protocol) + xpath += "{}".format(protocol) if port: - xpath += "{0}".format(port) + xpath += "{}".format(port) if application: - xpath += "{0}".format(application) + xpath += "{}".format(application) if category: - xpath += "{0}".format(category) + xpath += "{}".format(category) if allrules: xpath += "yes" xpath += "" - query = {"type": "op", "vsys": "vsys{0}".format(vsys), "cmd": xpath} + query = {"type": "op", "vsys": "vsys{}".format(vsys), "cmd": xpath} return __proxy__["panos.call"](query) @@ -2589,7 +2572,7 @@ def unlock_admin(username=None): query = { "type": "op", - "cmd": "{0}" + "cmd": "{}" "".format(username), } diff --git a/salt/modules/parallels.py b/salt/modules/parallels.py index 6a020354f06..4697fe17370 100644 --- a/salt/modules/parallels.py +++ b/salt/modules/parallels.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage Parallels Desktop VMs with ``prlctl`` and ``prlsrvctl``. Only some of the prlctl commands implemented so far. Of those that have been implemented, @@ -21,23 +20,16 @@ necessary): .. versionadded:: 2016.3.0 """ -from __future__ import absolute_import, print_function, unicode_literals import logging - -# Import python libs import re import shlex -# Import salt libs import salt.utils.data import salt.utils.path import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError -# Import 3rd party libs -from salt.ext import six - __virtualname__ = "parallels" __func_alias__ = { "exec_": "exec", @@ -53,13 +45,13 @@ def _normalize_args(args): """ Return args as a list of strings """ - if isinstance(args, six.string_types): + if isinstance(args, str): return shlex.split(args) if isinstance(args, (tuple, list)): - return [six.text_type(arg) for arg in args] + return [str(arg) for arg in args] else: - return [six.text_type(args)] + return [str(args)] def _find_guids(guid_string): @@ -285,7 +277,7 @@ def exists(name, runas=None): """ vm_info = list_vms(name, info=True, runas=runas).splitlines() for info_line in vm_info: - if "Name: {0}".format(name) in info_line: + if "Name: {}".format(name) in info_line: return True return False @@ -461,7 +453,7 @@ def snapshot_id_to_name(name, snap_id, strict=False, runas=None): name = salt.utils.data.decode(name) if not re.match(GUID_REGEX, snap_id): raise SaltInvocationError( - 'Snapshot ID "{0}" is not a GUID'.format(salt.utils.data.decode(snap_id)) + 'Snapshot ID "{}" is not a GUID'.format(salt.utils.data.decode(snap_id)) ) # Get the snapshot information of the snapshot having the requested ID @@ -470,7 +462,7 @@ def snapshot_id_to_name(name, snap_id, strict=False, runas=None): # Parallels desktop returned no information for snap_id if not info: raise SaltInvocationError( - 'No snapshots for VM "{0}" have ID "{1}"'.format(name, snap_id) + 'No snapshots for VM "{}" have ID "{}"'.format(name, snap_id) ) # Try to interpret the information @@ -497,8 +489,8 @@ def snapshot_id_to_name(name, snap_id, strict=False, runas=None): # Raise or return the result if not snap_name and strict: raise SaltInvocationError( - 'Could not find a snapshot name for snapshot ID "{0}" of VM ' - '"{1}"'.format(snap_id, name) + 'Could not find a snapshot name for snapshot ID "{}" of VM ' + '"{}"'.format(snap_id, name) ) return salt.utils.data.decode(snap_name) @@ -547,12 +539,12 @@ def snapshot_name_to_id(name, snap_name, strict=False, runas=None): # non-singular names if len(named_ids) == 0: raise SaltInvocationError( - 'No snapshots for VM "{0}" have name "{1}"'.format(name, snap_name) + 'No snapshots for VM "{}" have name "{}"'.format(name, snap_name) ) elif len(named_ids) == 1: return named_ids[0] else: - multi_msg = 'Multiple snapshots for VM "{0}" have name ' '"{1}"'.format( + multi_msg = 'Multiple snapshots for VM "{}" have name ' '"{}"'.format( name, snap_name ) if strict: @@ -638,7 +630,7 @@ def list_snapshots(name, snap_name=None, tree=False, names=False, runas=None): snap_ids = _find_guids(res) # Try to find the snapshot names - ret = "{0:<38} {1}\n".format("Snapshot ID", "Snapshot Name") + ret = "{:<38} {}\n".format("Snapshot ID", "Snapshot Name") for snap_id in snap_ids: snap_name = snapshot_id_to_name(name, snap_id, runas=runas) ret += "{{{0}}} {1}\n".format(snap_id, salt.utils.data.decode(snap_name)) @@ -724,7 +716,7 @@ def delete_snapshot(name, snap_name, runas=None, all=False): # Validate VM and snapshot names name = salt.utils.data.decode(name) snap_ids = _validate_snap_name(name, snap_name, strict=strict, runas=runas) - if isinstance(snap_ids, six.string_types): + if isinstance(snap_ids, str): snap_ids = [snap_ids] # Delete snapshot(s) diff --git a/salt/modules/pcs.py b/salt/modules/pcs.py index bf7711436df..d31026d133d 100644 --- a/salt/modules/pcs.py +++ b/salt/modules/pcs.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Configure a Pacemaker/Corosync cluster with PCS =============================================== @@ -10,11 +9,8 @@ Pacemaker/Cororsync conifguration system (PCS) .. versionadded:: 2016.3.0 """ -from __future__ import absolute_import, print_function, unicode_literals -# Import salt libs import salt.utils.path -from salt.ext import six def __virtual__(): @@ -48,10 +44,10 @@ def item_show( """ cmd = ["pcs"] - if isinstance(cibfile, six.string_types): + if isinstance(cibfile, str): cmd += ["-f", cibfile] - if isinstance(item, six.string_types): + if isinstance(item, str): cmd += [item] elif isinstance(item, (list, tuple)): cmd += item @@ -60,12 +56,12 @@ def item_show( if item in ["constraint"]: cmd += [item_type] - if isinstance(show, six.string_types): + if isinstance(show, str): cmd += [show] elif isinstance(show, (list, tuple)): cmd += show - if isinstance(item_id, six.string_types): + if isinstance(item_id, str): cmd += [item_id] if isinstance(extra_args, (list, tuple)): @@ -100,20 +96,20 @@ def item_create( use cibfile instead of the live CIB """ cmd = ["pcs"] - if isinstance(cibfile, six.string_types): + if isinstance(cibfile, str): cmd += ["-f", cibfile] - if isinstance(item, six.string_types): + if isinstance(item, str): cmd += [item] elif isinstance(item, (list, tuple)): cmd += item # constraint command follows a different order if item in ["constraint"]: - if isinstance(item_type, six.string_types): + if isinstance(item_type, str): cmd += [item_type] - if isinstance(create, six.string_types): + if isinstance(create, str): cmd += [create] elif isinstance(create, (list, tuple)): cmd += create @@ -122,13 +118,13 @@ def item_create( # constraint command follows a different order if item not in ["constraint"]: cmd += [item_id] - if isinstance(item_type, six.string_types): + if isinstance(item_type, str): cmd += [item_type] if isinstance(extra_args, (list, tuple)): # constraint command needs item_id in format 'id= 0: @@ -212,7 +207,7 @@ def create(login, password, password_hashed=False, machine_account=False): # NOTE: --create requires a password, even if blank res = __salt__["cmd.run_all"]( cmd="pdbedit --create --user {login} -t {machine}".format( - login=_quote_args(login), + login=shlex.quote(login), machine="--machine" if machine_account else "", ), stdin="{password}\n{password}\n".format(password=password), @@ -228,7 +223,7 @@ def create(login, password, password_hashed=False, machine_account=False): if user["nt hash"] != password_hash: res = __salt__["cmd.run_all"]( "pdbedit --modify --user {login} --set-nt-hash={nthash}".format( - login=_quote_args(login), nthash=_quote_args(password_hash) + login=shlex.quote(login), nthash=shlex.quote(password_hash) ), ) @@ -386,7 +381,7 @@ def modify( for change in changes: cmds.append( "{flag}{value}".format( - flag=flags[change], value=_quote_args(changes[change]), + flag=flags[change], value=shlex.quote(changes[change]), ) ) if reset_login_hours: @@ -396,7 +391,7 @@ def modify( res = __salt__["cmd.run_all"]( "pdbedit --modify --user {login} {changes}".format( - login=_quote_args(login), changes=" ".join(cmds), + login=shlex.quote(login), changes=" ".join(cmds), ), ) diff --git a/salt/modules/pecl.py b/salt/modules/pecl.py index 546dfed7fb0..9ab9b6c9225 100644 --- a/salt/modules/pecl.py +++ b/salt/modules/pecl.py @@ -1,21 +1,13 @@ -# -*- coding: utf-8 -*- """ Manage PHP pecl extensions. """ -from __future__ import absolute_import, print_function, unicode_literals import logging - -# Import python libs import re -# Import salt libs import salt.utils.data import salt.utils.path -# Import 3rd-party libs -from salt.ext import six - try: from shlex import quote as _cmd_quote # pylint: disable=E0611 except ImportError: @@ -43,7 +35,7 @@ def _pecl(command, defaults=False): """ Execute the command passed with pecl """ - cmdline = "pecl {0}".format(command) + cmdline = "pecl {}".format(command) if salt.utils.data.is_true(defaults): cmdline = "yes " "''" + " | " + cmdline @@ -79,17 +71,17 @@ def install(pecls, defaults=False, force=False, preferred_state="stable"): salt '*' pecl.install fuse """ - if isinstance(pecls, six.string_types): + if isinstance(pecls, str): pecls = [pecls] - preferred_state = "-d preferred_state={0}".format(_cmd_quote(preferred_state)) + preferred_state = "-d preferred_state={}".format(_cmd_quote(preferred_state)) if force: return _pecl( - "{0} install -f {1}".format(preferred_state, _cmd_quote(" ".join(pecls))), + "{} install -f {}".format(preferred_state, _cmd_quote(" ".join(pecls))), defaults=defaults, ) else: _pecl( - "{0} install {1}".format(preferred_state, _cmd_quote(" ".join(pecls))), + "{} install {}".format(preferred_state, _cmd_quote(" ".join(pecls))), defaults=defaults, ) if not isinstance(pecls, list): @@ -102,7 +94,7 @@ def install(pecls, defaults=False, force=False, preferred_state="stable"): channel = None installed_pecls = list_(channel) for pecl in installed_pecls: - installed_pecl_with_version = "{0}-{1}".format( + installed_pecl_with_version = "{}-{}".format( pecl, installed_pecls.get(pecl)[0] ) if pecl in installed_pecl_with_version: @@ -125,9 +117,9 @@ def uninstall(pecls): salt '*' pecl.uninstall fuse """ - if isinstance(pecls, six.string_types): + if isinstance(pecls, str): pecls = [pecls] - return _pecl("uninstall {0}".format(_cmd_quote(" ".join(pecls)))) + return _pecl("uninstall {}".format(_cmd_quote(" ".join(pecls)))) def update(pecls): @@ -143,9 +135,9 @@ def update(pecls): salt '*' pecl.update fuse """ - if isinstance(pecls, six.string_types): + if isinstance(pecls, str): pecls = [pecls] - return _pecl("install -U {0}".format(_cmd_quote(" ".join(pecls)))) + return _pecl("install -U {}".format(_cmd_quote(" ".join(pecls)))) def list_(channel=None): @@ -162,7 +154,7 @@ def list_(channel=None): pecls = {} command = "list" if channel: - command = "{0} -c {1}".format(command, _cmd_quote(channel)) + command = "{} -c {}".format(command, _cmd_quote(channel)) lines = _pecl(command).splitlines() lines = (l for l in lines if pecl_channel_pat.match(l)) diff --git a/salt/modules/peeringdb.py b/salt/modules/peeringdb.py index 8c654c39a8e..6a77a35fa03 100644 --- a/salt/modules/peeringdb.py +++ b/salt/modules/peeringdb.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ PeeringDB Module ================ @@ -25,9 +24,7 @@ Configuration (in the opts or Pillar): username: salt password: 5@1t """ -from __future__ import absolute_import -# Import python libs import logging # Import salt modules diff --git a/salt/modules/philips_hue.py b/salt/modules/philips_hue.py index ee8bf2c7c87..f7a7705c242 100644 --- a/salt/modules/philips_hue.py +++ b/salt/modules/philips_hue.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright 2015 SUSE LLC # @@ -20,7 +19,6 @@ Philips HUE lamps module for proxy. .. versionadded:: 2015.8.3 """ -from __future__ import absolute_import, print_function, unicode_literals import sys diff --git a/salt/modules/powerpath.py b/salt/modules/powerpath.py index c68edc24ab2..4ef2a5402d2 100644 --- a/salt/modules/powerpath.py +++ b/salt/modules/powerpath.py @@ -1,13 +1,10 @@ -# -*- coding: utf-8 -*- """ powerpath support. Assumes RedHat """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import os import re @@ -89,7 +86,7 @@ def add_license(key): result["output"] = "PowerPath is not installed" return result - cmd = "/sbin/emcpreg -add {0}".format(key) + cmd = "/sbin/emcpreg -add {}".format(key) ret = __salt__["cmd.run_all"](cmd, python_shell=True) result["retcode"] = ret["retcode"] @@ -113,7 +110,7 @@ def remove_license(key): result["output"] = "PowerPath is not installed" return result - cmd = "/sbin/emcpreg -remove {0}".format(key) + cmd = "/sbin/emcpreg -remove {}".format(key) ret = __salt__["cmd.run_all"](cmd, python_shell=True) result["retcode"] = ret["retcode"] diff --git a/salt/modules/purefa.py b/salt/modules/purefa.py index 998c4a567ea..f2fc4e16bac 100644 --- a/salt/modules/purefa.py +++ b/salt/modules/purefa.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - ## # Copyright 2017 Pure Storage Inc # @@ -51,8 +49,6 @@ Installation Prerequisites """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import os import platform @@ -60,9 +56,6 @@ from datetime import datetime from salt.exceptions import CommandExecutionError -# Import Salt libs -from salt.ext import six - # Import 3rd party modules try: import purestorage @@ -241,7 +234,7 @@ def snap_create(name, suffix=None): """ array = _get_system() if suffix is None: - suffix = "snap-" + six.text_type( + suffix = "snap-" + str( (datetime.utcnow() - datetime(1970, 1, 1, 0, 0, 0, 0)).total_seconds() ) suffix = suffix.replace(".", "") diff --git a/salt/modules/pushbullet.py b/salt/modules/pushbullet.py index f933f423b6d..b716e667d04 100644 --- a/salt/modules/pushbullet.py +++ b/salt/modules/pushbullet.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Module for sending messages to Pushbullet (https://www.pushbullet.com) @@ -22,8 +21,6 @@ For example: """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import logging @@ -47,7 +44,7 @@ def __virtual__(): return True -class _SaltPushbullet(object): +class _SaltPushbullet: def __init__(self, device_name): api_key = __salt__["config.get"]("pushbullet.api_key") or __salt__[ "config.get" diff --git a/salt/modules/pushover_notify.py b/salt/modules/pushover_notify.py index 162319d7575..43f2f237009 100644 --- a/salt/modules/pushover_notify.py +++ b/salt/modules/pushover_notify.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Module for sending messages to Pushover (https://www.pushover.net) @@ -16,23 +15,13 @@ Module for sending messages to Pushover (https://www.pushover.net) token: abAHuZyCLtdH8P4zhmFZmgUHUsv1ei8 """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import logging +import urllib.parse import salt.utils.pushover - -# Import salt libs from salt.exceptions import SaltInvocationError -# Import 3rd-party libs -# pylint: disable=import-error,no-name-in-module,redefined-builtin -from salt.ext.six.moves.urllib.parse import urlencode as _urlencode - -# pylint: enable=import-error,no-name-in-module,redefined-builtin - - log = logging.getLogger(__name__) __virtualname__ = "pushover" @@ -123,7 +112,7 @@ def post_message( function="message", method="POST", header_dict={"Content-Type": "application/x-www-form-urlencoded"}, - data=_urlencode(parameters), + data=urllib.parse.urlencode(parameters), opts=__opts__, ) diff --git a/salt/modules/qemu_img.py b/salt/modules/qemu_img.py index ad2b4e3c779..30f8a1f48fa 100644 --- a/salt/modules/qemu_img.py +++ b/salt/modules/qemu_img.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Qemu-img Command Wrapper ======================== @@ -7,12 +6,9 @@ The qemu img command is wrapped for specific functions :depends: qemu-img """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import os -# Import salt libs import salt.utils.path @@ -45,8 +41,7 @@ def make_image(location, size, fmt): if not os.path.isdir(os.path.dirname(location)): return "" if not __salt__["cmd.retcode"]( - "qemu-img create -f {0} {1} {2}M".format(fmt, location, size), - python_shell=False, + "qemu-img create -f {} {} {}M".format(fmt, location, size), python_shell=False, ): return location return "" diff --git a/salt/modules/rallydev.py b/salt/modules/rallydev.py index c9108c9d199..72bcdf8adb5 100644 --- a/salt/modules/rallydev.py +++ b/salt/modules/rallydev.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Support for RallyDev @@ -13,15 +12,11 @@ Requires a ``username`` and a ``password`` in ``/etc/salt/minion``: password: 123pass """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import logging import salt.utils.http import salt.utils.json - -# Import salt libs from salt.exceptions import SaltInvocationError log = logging.getLogger(__name__) @@ -84,7 +79,7 @@ def _query( path += action if command: - path += "/{0}".format(command) + path += "/{}".format(command) log.debug("RallyDev URL: %s", path) diff --git a/salt/modules/random_org.py b/salt/modules/random_org.py index 1741c17865a..3fc3d8084ca 100644 --- a/salt/modules/random_org.py +++ b/salt/modules/random_org.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Module for retrieving random information from Random.org @@ -16,26 +15,13 @@ Module for retrieving random information from Random.org api_key: 7be1402d-5719-5bd3-a306-3def9f135da5 api_version: 1 """ - -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - +import http.client import logging +import urllib.request -import salt.ext.six.moves.http_client - -# Import salt libs import salt.utils.http import salt.utils.json -# Import 3rd-party libs -# pylint: disable=import-error,no-name-in-module,redefined-builtin -from salt.ext import six -from salt.ext.six.moves.urllib.parse import urljoin as _urljoin - -# pylint: enable=import-error,no-name-in-module,redefined-builtin - - log = logging.getLogger(__name__) __virtualname__ = "random_org" @@ -65,7 +51,7 @@ def _numeric(n): """ Tell whether an argument is numeric """ - return isinstance(n, six.integer_types + (float,)) + return isinstance(n, (int,) + (float,)) def _query(api_version=None, data=None): @@ -84,7 +70,7 @@ def _query(api_version=None, data=None): ret = {"res": True} api_url = "https://api.random.org/" - base_url = _urljoin(api_url, "json-rpc/" + six.text_type(api_version) + "/invoke") + base_url = urllib.parse.urljoin(api_url, "json-rpc/" + str(api_version) + "/invoke") data = salt.utils.json.dumps(data) @@ -99,14 +85,14 @@ def _query(api_version=None, data=None): opts=__opts__, ) - if result.get("status", None) == salt.ext.six.moves.http_client.OK: + if result.get("status", None) == http.client.OK: _result = result["dict"] if _result.get("result"): return _result.get("result") if _result.get("error"): return _result.get("error") return False - elif result.get("status", None) == salt.ext.six.moves.http_client.NO_CONTENT: + elif result.get("status", None) == http.client.NO_CONTENT: return False else: ret["message"] = result.text if hasattr(result, "text") else "" @@ -145,7 +131,7 @@ def getUsage(api_key=None, api_version=None): return ret if isinstance(api_version, int): - api_version = six.text_type(api_version) + api_version = str(api_version) _function = RANDOM_ORG_FUNCTIONS.get(api_version).get("getUsage").get("method") data = {} @@ -219,7 +205,7 @@ def generateIntegers(api_key=None, api_version=None, **kwargs): for item in ["number", "minimum", "maximum"]: if item not in kwargs: ret["res"] = False - ret["message"] = "Rquired argument, {0} is missing.".format(item) + ret["message"] = "Rquired argument, {} is missing.".format(item) return ret if not _numeric(kwargs["number"]) or not 1 <= kwargs["number"] <= 10000: @@ -262,7 +248,7 @@ def generateIntegers(api_key=None, api_version=None, **kwargs): replacement = kwargs["replacement"] if isinstance(api_version, int): - api_version = six.text_type(api_version) + api_version = str(api_version) _function = ( RANDOM_ORG_FUNCTIONS.get(api_version).get("generateIntegers").get("method") @@ -345,7 +331,7 @@ def generateStrings(api_key=None, api_version=None, **kwargs): for item in ["number", "length", "characters"]: if item not in kwargs: ret["res"] = False - ret["message"] = "Required argument, {0} is missing.".format(item) + ret["message"] = "Required argument, {} is missing.".format(item) return ret if not _numeric(kwargs["number"]) or not 1 <= kwargs["number"] <= 10000: @@ -364,7 +350,7 @@ def generateStrings(api_key=None, api_version=None, **kwargs): return ret if isinstance(api_version, int): - api_version = six.text_type(api_version) + api_version = str(api_version) if "replacement" not in kwargs: replacement = True @@ -435,11 +421,11 @@ def generateUUIDs(api_key=None, api_version=None, **kwargs): for item in ["number"]: if item not in kwargs: ret["res"] = False - ret["message"] = "Required argument, {0} is missing.".format(item) + ret["message"] = "Required argument, {} is missing.".format(item) return ret if isinstance(api_version, int): - api_version = six.text_type(api_version) + api_version = str(api_version) if not _numeric(kwargs["number"]) or not 1 <= kwargs["number"] <= 1000: ret["res"] = False @@ -516,7 +502,7 @@ def generateDecimalFractions(api_key=None, api_version=None, **kwargs): for item in ["number", "decimalPlaces"]: if item not in kwargs: ret["res"] = False - ret["message"] = "Required argument, {0} is missing.".format(item) + ret["message"] = "Required argument, {} is missing.".format(item) return ret if not isinstance(kwargs["number"], int) or not 1 <= kwargs["number"] <= 10000: @@ -535,7 +521,7 @@ def generateDecimalFractions(api_key=None, api_version=None, **kwargs): replacement = kwargs["replacement"] if isinstance(api_version, int): - api_version = six.text_type(api_version) + api_version = str(api_version) _function = ( RANDOM_ORG_FUNCTIONS.get(api_version) @@ -610,7 +596,7 @@ def generateGaussians(api_key=None, api_version=None, **kwargs): for item in ["number", "mean", "standardDeviation", "significantDigits"]: if item not in kwargs: ret["res"] = False - ret["message"] = "Required argument, {0} is missing.".format(item) + ret["message"] = "Required argument, {} is missing.".format(item) return ret if not _numeric(kwargs["number"]) or not 1 <= kwargs["number"] <= 10000: @@ -642,7 +628,7 @@ def generateGaussians(api_key=None, api_version=None, **kwargs): return ret if isinstance(api_version, int): - api_version = six.text_type(api_version) + api_version = str(api_version) _function = ( RANDOM_ORG_FUNCTIONS.get(api_version).get("generateGaussians").get("method") @@ -710,7 +696,7 @@ def generateBlobs(api_key=None, api_version=None, **kwargs): for item in ["number", "size"]: if item not in kwargs: ret["res"] = False - ret["message"] = "Required argument, {0} is missing.".format(item) + ret["message"] = "Required argument, {} is missing.".format(item) return ret if not _numeric(kwargs["number"]) or not 1 <= kwargs["number"] <= 100: @@ -738,7 +724,7 @@ def generateBlobs(api_key=None, api_version=None, **kwargs): _format = "base64" if isinstance(api_version, int): - api_version = six.text_type(api_version) + api_version = str(api_version) _function = RANDOM_ORG_FUNCTIONS.get(api_version).get("generateBlobs").get("method") data = {} diff --git a/salt/modules/rbenv.py b/salt/modules/rbenv.py index a9bb67ee632..3f3c8350887 100644 --- a/salt/modules/rbenv.py +++ b/salt/modules/rbenv.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage ruby installations with rbenv. rbenv is supported on Linux and macOS. rbenv doesn't work on Windows (and isn't really necessary on Windows as there is @@ -10,23 +9,17 @@ http://misheska.com/blog/2013/06/15/using-rbenv-to-manage-multiple-versions-of-r .. versionadded:: 0.16.0 """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import logging import os import re -# Import Salt libs import salt.utils.args import salt.utils.data import salt.utils.path import salt.utils.platform from salt.exceptions import SaltInvocationError -# Import 3rd-party libs -from salt.ext import six - # Set up logger log = logging.getLogger(__name__) @@ -69,7 +62,7 @@ def _parse_env(env): if not isinstance(env, dict): env = {} - for bad_env_key in (x for x, y in six.iteritems(env) if y is None): + for bad_env_key in (x for x, y in env.items() if y is None): log.error( "Environment variable '%s' passed without a value. " "Setting value to an empty string", @@ -82,7 +75,7 @@ def _parse_env(env): def _rbenv_bin(runas=None): path = _rbenv_path(runas) - return "{0}/bin/rbenv".format(path) + return "{}/bin/rbenv".format(path) def _rbenv_path(runas=None): @@ -90,7 +83,7 @@ def _rbenv_path(runas=None): if runas in (None, "root"): path = __salt__["config.option"]("rbenv.root") or "/usr/local/rbenv" else: - path = __salt__["config.option"]("rbenv.root") or "~{0}/.rbenv".format(runas) + path = __salt__["config.option"]("rbenv.root") or "~{}/.rbenv".format(runas) return os.path.expanduser(path) @@ -126,7 +119,7 @@ def _install_rbenv(path, runas=None): def _install_ruby_build(path, runas=None): - path = "{0}/plugins/ruby-build".format(path) + path = "{}/plugins/ruby-build".format(path) if os.path.isdir(path): return True @@ -147,7 +140,7 @@ def _update_rbenv(path, runas=None): def _update_ruby_build(path, runas=None): - path = "{0}/plugins/ruby-build".format(path) + path = "{}/plugins/ruby-build".format(path) if not os.path.isdir(path): return False @@ -388,7 +381,7 @@ def do(cmdline, runas=None, env=None): # and 3. The code below first normalizes all path components to unicode to # stitch them together, and then converts the result back to a str type. env[ - str("PATH") + "PATH" ] = salt.utils.stringutils.to_str( # future lint: disable=blacklisted-function os.pathsep.join( ( @@ -401,7 +394,7 @@ def do(cmdline, runas=None, env=None): try: cmdline = salt.utils.args.shlex_split(cmdline) except AttributeError: - cmdauth = salt.utils.args.shlex_split(six.text_type(cmdline)) + cmdauth = salt.utils.args.shlex_split(str(cmdline)) result = __salt__["cmd.run_all"](cmdline, runas=runas, env=env, python_shell=False) @@ -432,7 +425,7 @@ def do_with_ruby(ruby, cmdline, runas=None): try: cmdline = salt.utils.args.shlex_split(cmdline) except AttributeError: - cmdline = salt.utils.args.shlex_split(six.text_type(cmdline)) + cmdline = salt.utils.args.shlex_split(str(cmdline)) env = {} if ruby: diff --git a/salt/modules/riak.py b/salt/modules/riak.py index e006fa96969..197d8689971 100644 --- a/salt/modules/riak.py +++ b/salt/modules/riak.py @@ -1,10 +1,7 @@ -# -*- coding: utf-8 -*- """ Riak Salt Module """ -from __future__ import absolute_import, print_function, unicode_literals -# Import salt libs import salt.utils.path @@ -24,7 +21,7 @@ def __execute_cmd(name, cmd): """ Execute Riak commands """ - return __salt__["cmd.run_all"]("{0} {1}".format(salt.utils.path.which(name), cmd)) + return __salt__["cmd.run_all"]("{} {}".format(salt.utils.path.which(name), cmd)) def start(): @@ -92,7 +89,7 @@ def cluster_join(username, hostname): """ ret = {"comment": "", "success": False} - cmd = __execute_cmd("riak-admin", "cluster join {0}@{1}".format(username, hostname)) + cmd = __execute_cmd("riak-admin", "cluster join {}@{}".format(username, hostname)) if cmd["retcode"] != 0: ret["comment"] = cmd["stdout"] @@ -120,9 +117,7 @@ def cluster_leave(username, hostname): """ ret = {"comment": "", "success": False} - cmd = __execute_cmd( - "riak-admin", "cluster leave {0}@{1}".format(username, hostname) - ) + cmd = __execute_cmd("riak-admin", "cluster leave {}@{}".format(username, hostname)) if cmd["retcode"] != 0: ret["comment"] = cmd["stdout"] diff --git a/salt/modules/rvm.py b/salt/modules/rvm.py index a6063d7ff84..28669a26511 100644 --- a/salt/modules/rvm.py +++ b/salt/modules/rvm.py @@ -1,22 +1,14 @@ -# -*- coding: utf-8 -*- """ Manage ruby installations and gemsets with RVM, the Ruby Version Manager. """ -from __future__ import absolute_import, print_function, unicode_literals import logging import os - -# Import python libs import re -# Import salt libs import salt.utils.args from salt.exceptions import CommandExecutionError -# Import 3rd party libs -from salt.ext import six - log = logging.getLogger(__name__) # Don't shadow built-in's. @@ -29,8 +21,8 @@ __opts__ = { def _get_rvm_location(runas=None): if runas: - runas_home = os.path.expanduser("~{0}".format(runas)) - rvmpath = "{0}/.rvm/bin/rvm".format(runas_home) + runas_home = os.path.expanduser("~{}".format(runas)) + rvmpath = "{}/.rvm/bin/rvm".format(runas_home) if os.path.exists(rvmpath): return [rvmpath] return ["/usr/local/rvm/bin/rvm"] @@ -460,5 +452,5 @@ def do(ruby, command, runas=None, cwd=None, env=None): # pylint: disable=C0103 try: command = salt.utils.args.shlex_split(command) except AttributeError: - command = salt.utils.args.shlex_split(six.text_type(command)) + command = salt.utils.args.shlex_split(str(command)) return _rvm_do(ruby, command, runas=runas, cwd=cwd, env=env) diff --git a/salt/modules/s6.py b/salt/modules/s6.py index 5e24a2fa6bc..23edface5a5 100644 --- a/salt/modules/s6.py +++ b/salt/modules/s6.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ s6 service module @@ -16,13 +15,10 @@ Note that the ``enabled`` argument is not available with this provider. :codeauthor: Marek Skrobacki """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import os import re -# Import salt libs from salt.exceptions import CommandExecutionError __func_alias__ = {"reload_": "reload"} @@ -44,7 +40,7 @@ def _service_path(name): """ if not SERVICE_DIR: raise CommandExecutionError("Could not find service directory.") - return "{0}/{1}".format(SERVICE_DIR, name) + return "{}/{}".format(SERVICE_DIR, name) def start(name): @@ -57,7 +53,7 @@ def start(name): salt '*' s6.start """ - cmd = "s6-svc -u {0}".format(_service_path(name)) + cmd = "s6-svc -u {}".format(_service_path(name)) return not __salt__["cmd.retcode"](cmd) @@ -71,7 +67,7 @@ def stop(name): salt '*' s6.stop """ - cmd = "s6-svc -d {0}".format(_service_path(name)) + cmd = "s6-svc -d {}".format(_service_path(name)) return not __salt__["cmd.retcode"](cmd) @@ -85,7 +81,7 @@ def term(name): salt '*' s6.term """ - cmd = "s6-svc -t {0}".format(_service_path(name)) + cmd = "s6-svc -t {}".format(_service_path(name)) return not __salt__["cmd.retcode"](cmd) @@ -99,7 +95,7 @@ def reload_(name): salt '*' s6.reload """ - cmd = "s6-svc -h {0}".format(_service_path(name)) + cmd = "s6-svc -h {}".format(_service_path(name)) return not __salt__["cmd.retcode"](cmd) @@ -113,7 +109,7 @@ def restart(name): salt '*' s6.restart """ - cmd = "s6-svc -t {0}".format(_service_path(name)) + cmd = "s6-svc -t {}".format(_service_path(name)) return not __salt__["cmd.retcode"](cmd) @@ -140,7 +136,7 @@ def status(name, sig=None): salt '*' s6.status """ - cmd = "s6-svstat {0}".format(_service_path(name)) + cmd = "s6-svstat {}".format(_service_path(name)) out = __salt__["cmd.run_stdout"](cmd) try: pid = re.search(r"up \(pid (\d+)\)", out).group(1) diff --git a/salt/modules/sensehat.py b/salt/modules/sensehat.py index 4ab605ed0ac..9d98c022b9e 100644 --- a/salt/modules/sensehat.py +++ b/salt/modules/sensehat.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Module for controlling the LED matrix or reading environment data on the SenseHat of a Raspberry Pi. @@ -20,7 +19,6 @@ Example: """ -from __future__ import absolute_import, print_function, unicode_literals import logging diff --git a/salt/modules/sensors.py b/salt/modules/sensors.py index 14e2e426644..b96c3a32a4c 100644 --- a/salt/modules/sensors.py +++ b/salt/modules/sensors.py @@ -1,15 +1,11 @@ -# -*- coding: utf-8 -*- """ Read lm-sensors .. versionadded:: 2014.1.3 """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import logging -# import Salt libs import salt.utils.path log = logging.getLogger(__name__) @@ -46,7 +42,7 @@ def sense(chip, fahrenheit=False): if fahrenheit is True: extra_args = "-f" sensors = __salt__["cmd.run"]( - "/usr/bin/sensors {0} {1}".format(chip, extra_args), python_shell=False + "/usr/bin/sensors {} {}".format(chip, extra_args), python_shell=False ).splitlines() ret = {} for sensor in sensors: diff --git a/salt/modules/serverdensity_device.py b/salt/modules/serverdensity_device.py index 42e26791f77..27a4c0b0a32 100644 --- a/salt/modules/serverdensity_device.py +++ b/salt/modules/serverdensity_device.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Wrapper around Server Density API ================================= @@ -6,21 +5,14 @@ Wrapper around Server Density API .. versionadded:: 2014.7.0 """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import logging import os import tempfile -# Import Salt libs import salt.utils.json from salt.exceptions import CommandExecutionError -# Import 3rd-party libs -from salt.ext import six -from salt.ext.six.moves import map - try: import requests @@ -57,14 +49,14 @@ def get_sd_auth(val, sd_auth_pillar_name="serverdensity"): if not sd_pillar: log.error("Could not load %s pillar", sd_auth_pillar_name) raise CommandExecutionError( - "{0} pillar is required for authentication".format(sd_auth_pillar_name) + "{} pillar is required for authentication".format(sd_auth_pillar_name) ) try: return sd_pillar[val] except KeyError: log.error("Could not find value %s in pillar", val) - raise CommandExecutionError("{0} value was not found in pillar".format(val)) + raise CommandExecutionError("{} value was not found in pillar".format(val)) def _clean_salt_variables(params, variable_prefix="__"): @@ -106,7 +98,7 @@ def create(name, **params): except ValueError: log.error("Could not parse API Response content: %s", api_response.content) raise CommandExecutionError( - "Failed to create, API Response: {0}".format(api_response) + "Failed to create, API Response: {}".format(api_response) ) else: return None @@ -137,7 +129,7 @@ def delete(device_id): except ValueError: log.error("Could not parse API Response content: %s", api_response.content) raise CommandExecutionError( - "Failed to create, API Response: {0}".format(api_response) + "Failed to create, API Response: {}".format(api_response) ) else: return None @@ -170,11 +162,11 @@ def ls(**params): endpoint = "resources" # Convert all ints to strings: - for key, val in six.iteritems(params): - params[key] = six.text_type(val) + for key, val in params.items(): + params[key] = str(val) api_response = requests.get( - "https://api.serverdensity.io/inventory/{0}".format(endpoint), + "https://api.serverdensity.io/inventory/{}".format(endpoint), params={ "token": get_sd_auth("api_token"), "filter": salt.utils.json.dumps(params), @@ -191,9 +183,7 @@ def ls(**params): api_response.content, ) raise CommandExecutionError( - "Failed to create, Server Density API Response: {0}".format( - api_response - ) + "Failed to create, Server Density API Response: {}".format(api_response) ) else: return None @@ -231,7 +221,7 @@ def update(device_id, **params): api_response.content, ) raise CommandExecutionError( - "Failed to create, API Response: {0}".format(api_response) + "Failed to create, API Response: {}".format(api_response) ) else: return None @@ -266,9 +256,9 @@ def install_agent(agent_key, agent_version=1): account = get_sd_auth(account_field) __salt__["cmd.run"]( - cmd="curl -L {0} -o {1}".format(url, install_filename), cwd=work_dir + cmd="curl -L {} -o {}".format(url, install_filename), cwd=work_dir ) - __salt__["cmd.run"](cmd="chmod +x {0}".format(install_filename), cwd=work_dir) + __salt__["cmd.run"](cmd="chmod +x {}".format(install_filename), cwd=work_dir) return __salt__["cmd.run"]( cmd="{filename} -a {account} -k {agent_key}".format( diff --git a/salt/modules/servicenow.py b/salt/modules/servicenow.py index 457e22647f2..345bbddc054 100644 --- a/salt/modules/servicenow.py +++ b/salt/modules/servicenow.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Module for execution of ServiceNow CI (configuration items) @@ -19,14 +18,9 @@ Module for execution of ServiceNow CI (configuration items) username: '' password: '' """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import logging -# Import third party libs -from salt.ext import six - HAS_LIBS = False try: from servicenow_rest.api import Client @@ -143,9 +137,9 @@ def non_structured_query(table, query=None, **kwargs): # try and assemble a query by keyword query_parts = [] for key, value in kwargs.items(): - query_parts.append("{0}={1}".format(key, value)) + query_parts.append("{}={}".format(key, value)) query = "^".join(query_parts) - query = six.text_type(query) + query = str(query) response = client.get(query) return response diff --git a/salt/modules/slsutil.py b/salt/modules/slsutil.py index 687c2ffb701..8f00ed10ce0 100644 --- a/salt/modules/slsutil.py +++ b/salt/modules/slsutil.py @@ -1,15 +1,11 @@ -# -*- coding: utf-8 -*- """ Utility functions for use with or in SLS files """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import os import textwrap -# Import Salt libs import salt.exceptions import salt.loader import salt.template @@ -191,12 +187,12 @@ def _get_serialize_fn(serializer, fn_name): if not fns: raise salt.exceptions.CommandExecutionError( - "Serializer '{0}' not found.".format(serializer) + "Serializer '{}' not found.".format(serializer) ) if not fn: raise salt.exceptions.CommandExecutionError( - "Serializer '{0}' does not implement {1}.".format(serializer, fn_name) + "Serializer '{}' does not implement {}.".format(serializer, fn_name) ) return fn diff --git a/salt/modules/smartos_imgadm.py b/salt/modules/smartos_imgadm.py index 05c9b1ddfa0..6346fc63b1c 100644 --- a/salt/modules/smartos_imgadm.py +++ b/salt/modules/smartos_imgadm.py @@ -1,13 +1,9 @@ -# -*- coding: utf-8 -*- """ Module for running imgadm command on SmartOS """ -from __future__ import absolute_import, print_function, unicode_literals -# Import Python libs import logging -# Import Salt libs import salt.utils.json import salt.utils.path import salt.utils.platform @@ -33,9 +29,7 @@ def __virtual__(): return __virtualname__ return ( False, - "{0} module can only be loaded on SmartOS compute nodes".format( - __virtualname__ - ), + "{} module can only be loaded on SmartOS compute nodes".format(__virtualname__), ) @@ -120,7 +114,7 @@ def _is_uuid(uuid): Example: e69a0918-055d-11e5-8912-e3ceb6df4cf8 """ - if uuid and list((len(x) for x in uuid.split("-"))) == [8, 4, 4, 4, 12]: + if uuid and list(len(x) for x in uuid.split("-")) == [8, 4, 4, 4, 12]: return True return False @@ -183,7 +177,7 @@ def update_installed(uuid=""): salt '*' imgadm.update [uuid] """ - cmd = "imgadm update {0}".format(uuid).rstrip() + cmd = "imgadm update {}".format(uuid).rstrip() __salt__["cmd.run"](cmd) return {} @@ -279,7 +273,7 @@ def show(uuid): ret = {} if _is_uuid(uuid) or _is_docker_uuid(uuid): - cmd = "imgadm show {0}".format(uuid) + cmd = "imgadm show {}".format(uuid) res = __salt__["cmd.run_all"](cmd, python_shell=False) retcode = res["retcode"] if retcode != 0: @@ -312,7 +306,7 @@ def get(uuid): uuid = docker_to_uuid(uuid) if _is_uuid(uuid): - cmd = "imgadm get {0}".format(uuid) + cmd = "imgadm get {}".format(uuid) res = __salt__["cmd.run_all"](cmd, python_shell=False) retcode = res["retcode"] if retcode != 0: @@ -341,7 +335,7 @@ def import_image(uuid, verbose=False): salt '*' imgadm.import e42f8c84-bbea-11e2-b920-078fab2aab1f [verbose=True] """ ret = {} - cmd = "imgadm import {0}".format(uuid) + cmd = "imgadm import {}".format(uuid) res = __salt__["cmd.run_all"](cmd, python_shell=False) retcode = res["retcode"] if retcode != 0: @@ -367,7 +361,7 @@ def delete(uuid): salt '*' imgadm.delete e42f8c84-bbea-11e2-b920-078fab2aab1f """ ret = {} - cmd = "imgadm delete {0}".format(uuid) + cmd = "imgadm delete {}".format(uuid) res = __salt__["cmd.run_all"](cmd, python_shell=False) retcode = res["retcode"] if retcode != 0: @@ -465,7 +459,7 @@ def source_delete(source): salt '*' imgadm.source_delete https://updates.joyent.com """ ret = {} - cmd = "imgadm sources -d {0}".format(source) + cmd = "imgadm sources -d {}".format(source) res = __salt__["cmd.run_all"](cmd) retcode = res["retcode"] if retcode != 0: @@ -500,7 +494,7 @@ def source_add(source, source_type="imgapi"): if source_type not in ["imgapi", "docker"]: log.warning("Possible unsupported imgage source type specified!") - cmd = "imgadm sources -a {0} -t {1}".format(source, source_type) + cmd = "imgadm sources -a {} -t {}".format(source, source_type) res = __salt__["cmd.run_all"](cmd) retcode = res["retcode"] if retcode != 0: diff --git a/salt/modules/smartos_nictagadm.py b/salt/modules/smartos_nictagadm.py index 0c7c78ec529..e2991be6708 100644 --- a/salt/modules/smartos_nictagadm.py +++ b/salt/modules/smartos_nictagadm.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Module for running nictagadm command on SmartOS :maintainer: Jorge Schrauwen @@ -9,12 +8,9 @@ Module for running nictagadm command on SmartOS .. versionadded:: 2016.11.0 """ -from __future__ import absolute_import, print_function, unicode_literals -# Import Python libs import logging -# Import Salt libs import salt.utils.path import salt.utils.platform @@ -39,9 +35,7 @@ def __virtual__(): return __virtualname__ return ( False, - "{0} module can only be loaded on SmartOS compute nodes".format( - __virtualname__ - ), + "{} module can only be loaded on SmartOS compute nodes".format(__virtualname__), ) @@ -59,7 +53,7 @@ def list_nictags(include_etherstubs=True): salt '*' nictagadm.list """ ret = {} - cmd = 'nictagadm list -d "|" -p{0}'.format(" -L" if not include_etherstubs else "") + cmd = 'nictagadm list -d "|" -p{}'.format(" -L" if not include_etherstubs else "") res = __salt__["cmd.run_all"](cmd) retcode = res["retcode"] if retcode != 0: @@ -92,7 +86,7 @@ def vms(nictag): salt '*' nictagadm.vms admin """ ret = {} - cmd = "nictagadm vms {0}".format(nictag) + cmd = "nictagadm vms {}".format(nictag) res = __salt__["cmd.run_all"](cmd) retcode = res["retcode"] if retcode != 0: @@ -123,7 +117,7 @@ def exists(*nictag, **kwargs): if not nictag: return {"Error": "Please provide at least one nictag to check."} - cmd = "nictagadm exists -l {0}".format(" ".join(nictag)) + cmd = "nictagadm exists -l {}".format(" ".join(nictag)) res = __salt__["cmd.run_all"](cmd) if not kwargs.get("verbose", False): @@ -163,13 +157,13 @@ def add(name, mac, mtu=1500): res = __salt__["cmd.run_all"](cmd) # dladm prints '00' as '0', so account for that. if mac.replace("00", "0") not in res["stdout"].splitlines(): - return {"Error": "{0} is not present on this system.".format(mac)} + return {"Error": "{} is not present on this system.".format(mac)} if mac == "etherstub": - cmd = "nictagadm add -l {0}".format(name) + cmd = "nictagadm add -l {}".format(name) res = __salt__["cmd.run_all"](cmd) else: - cmd = "nictagadm add -p mtu={0},mac={1} {2}".format(mtu, mac, name) + cmd = "nictagadm add -p mtu={},mac={} {}".format(mtu, mac, name) res = __salt__["cmd.run_all"](cmd) if res["retcode"] == 0: @@ -202,7 +196,7 @@ def update(name, mac=None, mtu=None): ret = {} if name not in list_nictags(): - return {"Error": "nictag {0} does not exists.".format(name)} + return {"Error": "nictag {} does not exists.".format(name)} if not mtu and not mac: return {"Error": "please provide either mac or/and mtu."} if mtu: @@ -216,16 +210,16 @@ def update(name, mac=None, mtu=None): res = __salt__["cmd.run_all"](cmd) # dladm prints '00' as '0', so account for that. if mac.replace("00", "0") not in res["stdout"].splitlines(): - return {"Error": "{0} is not present on this system.".format(mac)} + return {"Error": "{} is not present on this system.".format(mac)} if mac and mtu: - properties = "mtu={0},mac={1}".format(mtu, mac) + properties = "mtu={},mac={}".format(mtu, mac) elif mac: - properties = "mac={0}".format(mac) if mac else "" + properties = "mac={}".format(mac) if mac else "" elif mtu: - properties = "mtu={0}".format(mtu) if mtu else "" + properties = "mtu={}".format(mtu) if mtu else "" - cmd = "nictagadm update -p {0} {1}".format(properties, name) + cmd = "nictagadm update -p {} {}".format(properties, name) res = __salt__["cmd.run_all"](cmd) if res["retcode"] == 0: @@ -258,7 +252,7 @@ def delete(name, force=False): if name not in list_nictags(): return True - cmd = "nictagadm delete {0}{1}".format("-f " if force else "", name) + cmd = "nictagadm delete {}{}".format("-f " if force else "", name) res = __salt__["cmd.run_all"](cmd) if res["retcode"] == 0: diff --git a/salt/modules/smartos_virt.py b/salt/modules/smartos_virt.py index d69f6b17198..6ce67b86aa6 100644 --- a/salt/modules/smartos_virt.py +++ b/salt/modules/smartos_virt.py @@ -1,13 +1,9 @@ -# -*- coding: utf-8 -*- """ virst compatibility module for managing VMs on SmartOS """ -from __future__ import absolute_import, print_function, unicode_literals -# Import Python libs import logging -# Import Salt libs import salt.utils.path import salt.utils.platform from salt.exceptions import CommandExecutionError @@ -26,9 +22,7 @@ def __virtual__(): return __virtualname__ return ( False, - "{0} module can only be loaded on SmartOS compute nodes".format( - __virtualname__ - ), + "{} module can only be loaded on SmartOS compute nodes".format(__virtualname__), ) diff --git a/salt/modules/smartos_vmadm.py b/salt/modules/smartos_vmadm.py index cc2126fdab2..4b3d0877acb 100644 --- a/salt/modules/smartos_vmadm.py +++ b/salt/modules/smartos_vmadm.py @@ -1,23 +1,16 @@ -# -*- coding: utf-8 -*- """ Module for running vmadm command on SmartOS """ -from __future__ import absolute_import, print_function, unicode_literals -# Import Python libs import logging import os -# Import Salt libs import salt.utils.args import salt.utils.files import salt.utils.json import salt.utils.path import salt.utils.platform import salt.utils.stringutils - -# Import 3rd-party libs -from salt.ext import six from salt.utils.odict import OrderedDict try: @@ -47,9 +40,7 @@ def __virtual__(): return __virtualname__ return ( False, - "{0} module can only be loaded on SmartOS compute nodes".format( - __virtualname__ - ), + "{} module can only be loaded on SmartOS compute nodes".format(__virtualname__), ) @@ -69,7 +60,7 @@ def _create_update_from_file(mode="create", uuid=None, path=None): """ ret = {} if not os.path.isfile(path) or path is None: - ret["Error"] = "File ({0}) does not exists!".format(path) + ret["Error"] = "File ({}) does not exists!".format(path) return ret # vmadm validate create|update [-f ] cmd = "vmadm validate {mode} {brand} -f {path}".format( @@ -183,7 +174,7 @@ def start(vm, options=None, key="uuid"): if key not in ["uuid", "alias", "hostname"]: ret["Error"] = "Key must be either uuid, alias or hostname" return ret - vm = lookup("{0}={1}".format(key, vm), one=True) + vm = lookup("{}={}".format(key, vm), one=True) if "Error" in vm: return vm # vmadm start [option=value ...] @@ -222,7 +213,7 @@ def stop(vm, force=False, key="uuid"): if key not in ["uuid", "alias", "hostname"]: ret["Error"] = "Key must be either uuid, alias or hostname" return ret - vm = lookup("{0}={1}".format(key, vm), one=True) + vm = lookup("{}={}".format(key, vm), one=True) if "Error" in vm: return vm # vmadm stop [-F] @@ -259,7 +250,7 @@ def reboot(vm, force=False, key="uuid"): if key not in ["uuid", "alias", "hostname"]: ret["Error"] = "Key must be either uuid, alias or hostname" return ret - vm = lookup("{0}={1}".format(key, vm), one=True) + vm = lookup("{}={}".format(key, vm), one=True) if "Error" in vm: return vm # vmadm reboot [-F] @@ -298,8 +289,8 @@ def list_vms(search=None, sort=None, order="uuid,type,ram,state,alias", keyed=Tr ret = {} # vmadm list [-p] [-H] [-o field,...] [-s field,...] [field=value ...] cmd = "vmadm list -p -H {order} {sort} {search}".format( - order="-o {0}".format(order) if order else "", - sort="-s {0}".format(sort) if sort else "", + order="-o {}".format(order) if order else "", + sort="-s {}".format(sort) if sort else "", search=search if search else "", ) res = __salt__["cmd.run_all"](cmd) @@ -353,7 +344,7 @@ def lookup(search=None, order=None, one=False): # vmadm lookup [-j|-1] [-o field,...] [field=value ...] cmd = "vmadm lookup {one} {order} {search}".format( one="-1" if one else "-j", - order="-o {0}".format(order) if order else "", + order="-o {}".format(order) if order else "", search=search if search else "", ) res = __salt__["cmd.run_all"](cmd) @@ -398,7 +389,7 @@ def sysrq(vm, action="nmi", key="uuid"): if action not in ["nmi", "screenshot"]: ret["Error"] = "Action must be either nmi or screenshot" return ret - vm = lookup("{0}={1}".format(key, vm), one=True) + vm = lookup("{}={}".format(key, vm), one=True) if "Error" in vm: return vm # vmadm sysrq @@ -431,11 +422,11 @@ def delete(vm, key="uuid"): if key not in ["uuid", "alias", "hostname"]: ret["Error"] = "Key must be either uuid, alias or hostname" return ret - vm = lookup("{0}={1}".format(key, vm), one=True) + vm = lookup("{}={}".format(key, vm), one=True) if "Error" in vm: return vm # vmadm delete - cmd = "vmadm delete {0}".format(vm) + cmd = "vmadm delete {}".format(vm) res = __salt__["cmd.run_all"](cmd) retcode = res["retcode"] if retcode != 0: @@ -464,11 +455,11 @@ def get(vm, key="uuid"): if key not in ["uuid", "alias", "hostname"]: ret["Error"] = "Key must be either uuid, alias or hostname" return ret - vm = lookup("{0}={1}".format(key, vm), one=True) + vm = lookup("{}={}".format(key, vm), one=True) if "Error" in vm: return vm # vmadm get - cmd = "vmadm get {0}".format(vm) + cmd = "vmadm get {}".format(vm) res = __salt__["cmd.run_all"](cmd) retcode = res["retcode"] if retcode != 0: @@ -515,7 +506,7 @@ def info(vm, info_type="all", key="uuid"): if key not in ["uuid", "alias", "hostname"]: ret["Error"] = "Key must be either uuid, alias or hostname" return ret - vm = lookup("{0}={1}".format(key, vm), one=True) + vm = lookup("{}={}".format(key, vm), one=True) if "Error" in vm: return vm # vmadm info [type,...] @@ -553,7 +544,7 @@ def create_snapshot(vm, name, key="uuid"): if key not in ["uuid", "alias", "hostname"]: ret["Error"] = "Key must be either uuid, alias or hostname" return ret - vm = lookup("{0}={1}".format(key, vm), one=True) + vm = lookup("{}={}".format(key, vm), one=True) if "Error" in vm: return vm vmobj = get(vm) @@ -601,7 +592,7 @@ def delete_snapshot(vm, name, key="uuid"): if key not in ["uuid", "alias", "hostname"]: ret["Error"] = "Key must be either uuid, alias or hostname" return ret - vm = lookup("{0}={1}".format(key, vm), one=True) + vm = lookup("{}={}".format(key, vm), one=True) if "Error" in vm: return vm vmobj = get(vm) @@ -646,7 +637,7 @@ def rollback_snapshot(vm, name, key="uuid"): if key not in ["uuid", "alias", "hostname"]: ret["Error"] = "Key must be either uuid, alias or hostname" return ret - vm = lookup("{0}={1}".format(key, vm), one=True) + vm = lookup("{}={}".format(key, vm), one=True) if "Error" in vm: return vm vmobj = get(vm) @@ -688,14 +679,14 @@ def reprovision(vm, image, key="uuid"): if key not in ["uuid", "alias", "hostname"]: ret["Error"] = "Key must be either uuid, alias or hostname" return ret - vm = lookup("{0}={1}".format(key, vm), one=True) + vm = lookup("{}={}".format(key, vm), one=True) if "Error" in vm: return vm if image not in __salt__["imgadm.list"](): - ret["Error"] = "Image ({0}) is not present on this host".format(image) + ret["Error"] = "Image ({}) is not present on this host".format(image) return ret # vmadm reprovision [-f ] - cmd = six.text_type("echo {image} | vmadm reprovision {uuid}").format( + cmd = "echo {image} | vmadm reprovision {uuid}".format( uuid=salt.utils.stringutils.to_unicode(vm), image=_quote_args(salt.utils.json.dumps({"image_uuid": image})), ) @@ -727,7 +718,7 @@ def create(from_file=None, **kwargs): # prepare vmcfg vmcfg = {} kwargs = salt.utils.args.clean_kwargs(**kwargs) - for k, v in six.iteritems(kwargs): + for k, v in kwargs.items(): vmcfg[k] = v if from_file: @@ -761,13 +752,13 @@ def update(vm, from_file=None, key="uuid", **kwargs): # prepare vmcfg vmcfg = {} kwargs = salt.utils.args.clean_kwargs(**kwargs) - for k, v in six.iteritems(kwargs): + for k, v in kwargs.items(): vmcfg[k] = v if key not in ["uuid", "alias", "hostname"]: ret["Error"] = "Key must be either uuid, alias or hostname" return ret - uuid = lookup("{0}={1}".format(key, vm), one=True) + uuid = lookup("{}={}".format(key, vm), one=True) if "Error" in uuid: return uuid @@ -802,12 +793,12 @@ def send(vm, target, key="uuid"): if not os.path.isdir(target): ret["Error"] = "Target must be a directory or host" return ret - vm = lookup("{0}={1}".format(key, vm), one=True) + vm = lookup("{}={}".format(key, vm), one=True) if "Error" in vm: return vm # vmadm send [target] cmd = "vmadm send {uuid} > {target}".format( - uuid=vm, target=os.path.join(target, "{0}.vmdata".format(vm)) + uuid=vm, target=os.path.join(target, "{}.vmdata".format(vm)) ) res = __salt__["cmd.run_all"](cmd, python_shell=True) retcode = res["retcode"] @@ -824,7 +815,7 @@ def send(vm, target, key="uuid"): name = name[-1] cmd = "zfs send {dataset} > {target}".format( dataset=dataset, - target=os.path.join(target, "{0}-{1}.zfsds".format(vm, name)), + target=os.path.join(target, "{}-{}.zfsds".format(vm, name)), ) res = __salt__["cmd.run_all"](cmd, python_shell=True) retcode = res["retcode"] @@ -853,12 +844,12 @@ def receive(uuid, source): if not os.path.isdir(source): ret["Error"] = "Source must be a directory or host" return ret - if not os.path.exists(os.path.join(source, "{0}.vmdata".format(uuid))): - ret["Error"] = "Unknow vm with uuid in {0}".format(source) + if not os.path.exists(os.path.join(source, "{}.vmdata".format(uuid))): + ret["Error"] = "Unknow vm with uuid in {}".format(source) return ret # vmadm receive cmd = "vmadm receive < {source}".format( - source=os.path.join(source, "{0}.vmdata".format(uuid)) + source=os.path.join(source, "{}.vmdata".format(uuid)) ) res = __salt__["cmd.run_all"](cmd, python_shell=True) retcode = res["retcode"] @@ -875,14 +866,14 @@ def receive(uuid, source): name = name[-1] cmd = "zfs receive {dataset} < {source}".format( dataset=dataset, - source=os.path.join(source, "{0}-{1}.zfsds".format(uuid, name)), + source=os.path.join(source, "{}-{}.zfsds".format(uuid, name)), ) res = __salt__["cmd.run_all"](cmd, python_shell=True) retcode = res["retcode"] if retcode != 0: ret["Error"] = res["stderr"] if "stderr" in res else _exit_status(retcode) return ret - cmd = "vmadm install {0}".format(uuid) + cmd = "vmadm install {}".format(uuid) res = __salt__["cmd.run_all"](cmd, python_shell=True) retcode = res["retcode"] if retcode != 0 and not res["stderr"].endswith("datasets"): diff --git a/salt/modules/solr.py b/salt/modules/solr.py index 044349d03eb..b71ca9ad23a 100644 --- a/salt/modules/solr.py +++ b/salt/modules/solr.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Apache Solr Salt Module @@ -59,31 +58,13 @@ verbose : True Get verbose output """ -# Import python Libs -from __future__ import absolute_import, print_function, unicode_literals import os +import urllib.request -# Import salt libs import salt.utils.json import salt.utils.path -# Import 3rd-party libs -# pylint: disable=no-name-in-module,import-error -from salt.ext import six -from salt.ext.six.moves.urllib.request import ( - HTTPBasicAuthHandler as _HTTPBasicAuthHandler, -) -from salt.ext.six.moves.urllib.request import ( - HTTPDigestAuthHandler as _HTTPDigestAuthHandler, -) -from salt.ext.six.moves.urllib.request import build_opener as _build_opener -from salt.ext.six.moves.urllib.request import install_opener as _install_opener -from salt.ext.six.moves.urllib.request import urlopen as _urlopen - -# pylint: enable=no-name-in-module,import-error - - # ######################### PRIVATE METHODS ############################## @@ -121,7 +102,7 @@ def _get_none_or_value(value): elif not value: return value # if it's a string, and it's not empty check for none - elif isinstance(value, six.string_types): + elif isinstance(value, str): if value.lower() == "none": return None return value @@ -224,18 +205,18 @@ def _format_url(handler, host=None, core_name=None, extra=None): baseurl = __salt__["config.option"]("solr.baseurl") if _get_none_or_value(core_name) is None: if extra is None or len(extra) == 0: - return "http://{0}:{1}{2}/{3}?wt=json".format(host, port, baseurl, handler) + return "http://{}:{}{}/{}?wt=json".format(host, port, baseurl, handler) else: - return "http://{0}:{1}{2}/{3}?wt=json&{4}".format( + return "http://{}:{}{}/{}?wt=json&{}".format( host, port, baseurl, handler, "&".join(extra) ) else: if extra is None or len(extra) == 0: - return "http://{0}:{1}{2}/{3}/{4}?wt=json".format( + return "http://{}:{}{}/{}/{}?wt=json".format( host, port, baseurl, core_name, handler ) else: - return "http://{0}:{1}{2}/{3}/{4}?wt=json&{5}".format( + return "http://{}:{}{}/{}/{}?wt=json&{}".format( host, port, baseurl, core_name, handler, "&".join(extra) ) @@ -249,11 +230,11 @@ def _auth(url): realm = __salt__["config.get"]("solr.auth_realm", "Solr") if user and password: - basic = _HTTPBasicAuthHandler() + basic = urllib.request.HTTPBasicAuthHandler() basic.add_password(realm=realm, uri=url, user=user, passwd=password) - digest = _HTTPDigestAuthHandler() + digest = urllib.request.HTTPDigestAuthHandler() digest.add_password(realm=realm, uri=url, user=user, passwd=password) - _install_opener(_build_opener(basic, digest)) + urllib.request.install_opener(urllib.request.build_opener(basic, digest)) def _http_request(url, request_timeout=None): @@ -276,10 +257,10 @@ def _http_request(url, request_timeout=None): request_timeout = __salt__["config.option"]("solr.request_timeout") kwargs = {} if request_timeout is None else {"timeout": request_timeout} - data = salt.utils.json.load(_urlopen(url, **kwargs)) + data = salt.utils.json.load(urllib.request.urlopen(url, **kwargs)) return _get_return_dict(True, data, []) except Exception as err: # pylint: disable=broad-except - return _get_return_dict(False, {}, ["{0} : {1}".format(url, err)]) + return _get_return_dict(False, {}, ["{} : {}".format(url, err)]) def _replication_request(command, host=None, core_name=None, params=None): @@ -305,7 +286,7 @@ def _replication_request(command, host=None, core_name=None, params=None): {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} """ params = [] if params is None else params - extra = ["command={0}".format(command)] + params + extra = ["command={}".format(command)] + params url = _format_url("replication", host=host, core_name=core_name, extra=extra) return _http_request(url) @@ -330,7 +311,7 @@ def _get_admin_info(command, host=None, core_name=None): {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} """ - url = _format_url("admin/{0}".format(command), host, core_name=core_name) + url = _format_url("admin/{}".format(command), host, core_name=core_name) resp = _http_request(url) return resp @@ -365,9 +346,9 @@ def _merge_options(options): defaults = __salt__["config.option"]("solr.dih.import_options") if isinstance(options, dict): defaults.update(options) - for key, val in six.iteritems(defaults): + for key, val in defaults.items(): if isinstance(val, bool): - defaults[key] = six.text_type(val).lower() + defaults[key] = str(val).lower() return defaults @@ -409,10 +390,10 @@ def _pre_index_check(handler, host=None, core_name=None): warn = ["An indexing process is already running."] return _get_return_dict(True, warnings=warn) if status != "idle": - errors = ['Unknown status: "{0}"'.format(status)] + errors = ['Unknown status: "{}"'.format(status)] return _get_return_dict(False, data=resp["data"], errors=errors) else: - errors = ["Status check failed. Response details: {0}".format(resp)] + errors = ["Status check failed. Response details: {}".format(resp)] return _get_return_dict(False, data=resp["data"], errors=errors) return resp @@ -440,10 +421,10 @@ def _find_value(ret_dict, key, path=None): if path is None: path = key else: - path = "{0}:{1}".format(path, key) + path = "{}:{}".format(path, key) ret = [] - for ikey, val in six.iteritems(ret_dict): + for ikey, val in ret_dict.items(): if ikey == key: ret.append({path: val}) if isinstance(val, list): @@ -679,7 +660,7 @@ def is_replication_enabled(host=None, core_name=None): # check for errors on the slave if "ERROR" in slave: success = False - err = "{0}: {1} - {2}".format(core, slave["ERROR"], master_url) + err = "{}: {} - {}".format(core, slave["ERROR"], master_url) resp["errors"].append(err) # if there is an error return everything data = slave if core is None else {core: {"data": slave}} @@ -758,7 +739,7 @@ def match_index_versions(host=None, core_name=None): if "ERROR" in slave: error = slave["ERROR"] success = False - err = "{0}: {1} - {2}".format(core, error, master_url) + err = "{}: {} - {}".format(core, error, master_url) resp["errors"].append(err) # if there was an error return the entire response so the # alterer can get what it wants @@ -883,8 +864,8 @@ def backup(host=None, core_name=None, append_core_to_path=False): params = [] if path is not None: path = path + name if append_core_to_path else path - params.append("&location={0}".format(path + name)) - params.append("&numberToKeep={0}".format(num_backups)) + params.append("&location={}".format(path + name)) + params.append("&numberToKeep={}".format(num_backups)) resp = _replication_request( "backup", host=host, core_name=name, params=params ) @@ -900,8 +881,8 @@ def backup(host=None, core_name=None, append_core_to_path=False): if append_core_to_path: path += core_name if path is not None: - params = ["location={0}".format(path)] - params.append("&numberToKeep={0}".format(num_backups)) + params = ["location={}".format(path)] + params.append("&numberToKeep={}".format(num_backups)) resp = _replication_request( "backup", host=host, core_name=core_name, params=params ) @@ -1026,12 +1007,10 @@ def signal(signal=None): # Give a friendly error message for invalid signals # TODO: Fix this logic to be reusable and used by apache.signal if signal not in valid_signals: - msg = valid_signals[:-1] + ("or {0}".format(valid_signals[-1]),) - return "{0} is an invalid signal. Try: one of: {1}".format( - signal, ", ".join(msg) - ) + msg = valid_signals[:-1] + ("or {}".format(valid_signals[-1]),) + return "{} is an invalid signal. Try: one of: {}".format(signal, ", ".join(msg)) - cmd = "{0} {1}".format(__opts__["solr.init_script"], signal) + cmd = "{} {}".format(__opts__["solr.init_script"], signal) __salt__["cmd.run"](cmd, python_shell=False) @@ -1078,7 +1057,7 @@ def reload_core(host=None, core_name=None): ret, success, data, resp["errors"], resp["warnings"] ) return ret - extra = ["action=RELOAD", "core={0}".format(core_name)] + extra = ["action=RELOAD", "core={}".format(core_name)] url = _format_url("admin/cores", host=host, core_name=None, extra=extra) return _http_request(url) @@ -1119,7 +1098,7 @@ def core_status(host=None, core_name=None): ret, success, data, resp["errors"], resp["warnings"] ) return ret - extra = ["action=STATUS", "core={0}".format(core_name)] + extra = ["action=STATUS", "core={}".format(core_name)] url = _format_url("admin/cores", host=host, core_name=None, extra=extra) return _http_request(url) @@ -1260,8 +1239,8 @@ def full_import(handler, host=None, core_name=None, options=None, extra=None): errors = ["Failed to set the replication status on the master."] return _get_return_dict(False, errors=errors) params = ["command=full-import"] - for key, val in six.iteritems(options): - params.append("&{0}={1}".format(key, val)) + for key, val in options.items(): + params.append("&{}={}".format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) @@ -1313,8 +1292,8 @@ def delta_import(handler, host=None, core_name=None, options=None, extra=None): errors = ["Failed to set the replication status on the master."] return _get_return_dict(False, errors=errors) params = ["command=delta-import"] - for key, val in six.iteritems(options): - params.append("{0}={1}".format(key, val)) + for key, val in options.items(): + params.append("{}={}".format(key, val)) url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) diff --git a/salt/modules/solrcloud.py b/salt/modules/solrcloud.py index 208b2d8f39f..1526544b0c7 100644 --- a/salt/modules/solrcloud.py +++ b/salt/modules/solrcloud.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Module for solrcloud configuration @@ -6,16 +5,12 @@ Module for solrcloud configuration For now, module is limited to http-exposed API. It doesn't implement config upload via Solr zkCli """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import logging import salt.utils.http as http from salt.exceptions import SaltInvocationError -from salt.ext import six -# Import salt libs log = logging.getLogger(__name__) """ @@ -83,7 +78,7 @@ def _query(url, solr_url="http://localhost:8983/solr/", **kwargs): """ - if not isinstance(solr_url, six.string_types): + if not isinstance(solr_url, str): raise ValueError("solr_url must be a string") if solr_url[-1:] != "/": @@ -102,7 +97,7 @@ def _query(url, solr_url="http://localhost:8983/solr/", **kwargs): else: raise SaltInvocationError( "Got a {status} error when calling {solr_url}{url} : {error}".format( - status=six.text_type(query_result["status"]), + status=str(query_result["status"]), solr_url=solr_url, url=url, error=query_result["error"], @@ -121,7 +116,7 @@ def _validate_core_properties(properties): props_string = "" - for prop_name, prop_value in six.iteritems(properties): + for prop_name, prop_value in properties.items(): if prop_name in BOOL_PROPS_LIST: if not isinstance(prop_value, bool): raise ValueError('Option "' + prop_name + '" value must be an boolean') @@ -134,7 +129,7 @@ def _validate_core_properties(properties): + ("true" if prop_value else "false") ) elif prop_name in STRING_PROPS_LIST: - if not isinstance(prop_value, six.string_types): + if not isinstance(prop_value, str): raise ValueError( 'In option "properties", core property "' + prop_name @@ -145,11 +140,7 @@ def _validate_core_properties(properties): else: props_string = ( - props_string - + "&property." - + six.text_type(prop_name) - + "=" - + six.text_type(prop_value) + props_string + "&property." + str(prop_name) + "=" + str(prop_value) ) return props_string @@ -164,19 +155,19 @@ def _validate_collection_options(options): options_string = "" - for option_name, option_value in six.iteritems(options): + for option_name, option_value in options.items(): if option_name in STRING_OPTIONS_LIST: - if not isinstance(option_value, six.string_types): + if not isinstance(option_value, str): raise ValueError('Option "' + option_name + '" value must be a string') options_string = options_string + "&" + option_name + "=" + option_value elif option_name in INT_OPTIONS_LIST: - if not isinstance(option_value, six.integer_types): + if not isinstance(option_value, int): raise ValueError('Option "' + option_name + '" value must be an int') options_string = ( - options_string + "&" + option_name + "=" + six.text_type(option_value) + options_string + "&" + option_name + "=" + str(option_value) ) elif option_name in BOOL_OPTIONS_LIST: @@ -260,7 +251,7 @@ def alias_exists(alias_name, **kwargs): salt '*' solrcloud.alias_exists my_alias """ - if not isinstance(alias_name, six.string_types): + if not isinstance(alias_name, str): raise ValueError("Alias name must be a string") cluster = cluster_status(**kwargs) @@ -282,12 +273,12 @@ def alias_get_collections(alias_name, **kwargs): salt '*' solrcloud.alias_get my_alias """ - if not isinstance(alias_name, six.string_types): + if not isinstance(alias_name, str): raise ValueError("Alias name must be a string") collection_aliases = [ (k_v[0], k_v[1]["aliases"]) - for k_v in six.iteritems(cluster_status(**kwargs)["collections"]) + for k_v in cluster_status(**kwargs)["collections"].items() if "aliases" in k_v[1] ] aliases = [ @@ -317,7 +308,7 @@ def alias_set_collections(alias_name, collections=None, **kwargs): ) for collection in collections: - if not isinstance(collection, six.string_types): + if not isinstance(collection, str): raise ValueError("Collection name must be a string") return _query( @@ -384,7 +375,7 @@ def collection_exists(collection_name, **kwargs): """ - if not isinstance(collection_name, six.string_types): + if not isinstance(collection_name, str): raise ValueError("Collection name must be a string") return collection_name in collection_list(**kwargs) @@ -408,7 +399,7 @@ def collection_backup(collection_name, location, backup_name=None, **kwargs): raise ValueError("Collection doesn't exists") if backup_name is not None: - backup_name = "&name={0}".format(backup_name) + backup_name = "&name={}".format(backup_name) else: backup_name = "" diff --git a/salt/modules/statuspage.py b/salt/modules/statuspage.py index ff589b73c3b..0a38e84102b 100644 --- a/salt/modules/statuspage.py +++ b/salt/modules/statuspage.py @@ -19,7 +19,6 @@ In the minion configuration file, the following block is required: """ -# import python std lib import logging # import third party diff --git a/salt/modules/suse_apache.py b/salt/modules/suse_apache.py index 885c0d7840a..7c599b34a83 100644 --- a/salt/modules/suse_apache.py +++ b/salt/modules/suse_apache.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Support for Apache @@ -6,12 +5,9 @@ Please note: The functions in here are SUSE-specific. Placing them in this separate file will allow them to load only on SUSE systems, while still loading under the ``apache`` namespace. """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import logging -# Import salt libs import salt.utils.path log = logging.getLogger(__name__) @@ -77,9 +73,9 @@ def a2enmod(mod): ret["Mod"] = mod if status == 1: - ret["Status"] = "Mod {0} Not found".format(mod) + ret["Status"] = "Mod {} Not found".format(mod) elif status == 0: - ret["Status"] = "Mod {0} enabled".format(mod) + ret["Status"] = "Mod {} enabled".format(mod) else: ret["Status"] = status @@ -108,9 +104,9 @@ def a2dismod(mod): ret["Mod"] = mod if status == 256: - ret["Status"] = "Mod {0} Not found".format(mod) + ret["Status"] = "Mod {} Not found".format(mod) elif status == 0: - ret["Status"] = "Mod {0} disabled".format(mod) + ret["Status"] = "Mod {} disabled".format(mod) else: ret["Status"] = status diff --git a/salt/modules/svn.py b/salt/modules/svn.py index e3bde722c31..2b6304a9b17 100644 --- a/salt/modules/svn.py +++ b/salt/modules/svn.py @@ -1,17 +1,12 @@ -# -*- coding: utf-8 -*- """ Subversion SCM """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import re -# Import salt libs import salt.utils.args import salt.utils.path from salt.exceptions import CommandExecutionError -from salt.ext import six _INI_RE = re.compile(r"^([^:]+):\s+(\S.*)$", re.M) @@ -458,6 +453,6 @@ def export( revision_args = "-r" opts += ( revision_args, - six.text_type(revision), + str(revision), ) return _run_svn("export", cwd, user, username, password, opts) diff --git a/salt/modules/swift.py b/salt/modules/swift.py index ef50870831a..4ffc79ccf3f 100644 --- a/salt/modules/swift.py +++ b/salt/modules/swift.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Module for handling OpenStack Swift calls Author: Anthony Stanton @@ -45,12 +44,9 @@ Inspired by the S3 and Nova modules NOTE: For Rackspace cloud files setting keystone.auth_version = 1 is recommended. """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import logging -# Import salt libs import salt.utils.openstack.swift as suos # Get logging started diff --git a/salt/modules/sysbench.py b/salt/modules/sysbench.py index 473a0f84c46..d46240f5f37 100644 --- a/salt/modules/sysbench.py +++ b/salt/modules/sysbench.py @@ -1,16 +1,13 @@ -# -*- coding: utf-8 -*- """ The 'sysbench' module is used to analyze the performance of the minions, right from the master! It measures various system parameters such as CPU, Memory, File I/O, Threads and Mutex. """ -from __future__ import absolute_import, print_function, unicode_literals import re import salt.utils.path -from salt.ext.six.moves import zip def __virtual__(): @@ -81,7 +78,7 @@ def cpu(): # Test beings! for primes in max_primes: - key = "Prime numbers limit: {0}".format(primes) + key = "Prime numbers limit: {}".format(primes) run_command = test_command.format(primes) result = __salt__["cmd.run"](run_command) ret_val[key] = _parser(result) @@ -112,7 +109,7 @@ def threads(): # Test begins! for yields, locks in zip(thread_yields, thread_locks): - key = "Yields: {0} Locks: {1}".format(yields, locks) + key = "Yields: {} Locks: {}".format(yields, locks) run_command = test_command.format(yields, locks) result = __salt__["cmd.run"](run_command) ret_val[key] = _parser(result) @@ -151,7 +148,7 @@ def mutex(): # Test begins! for num, locks, loops in zip(mutex_num, mutex_locks, mutex_loops): - key = "Mutex: {0} Locks: {1} Loops: {2}".format(num, locks, loops) + key = "Mutex: {} Locks: {} Loops: {}".format(num, locks, loops) run_command = test_command.format(num, locks, loops) result = __salt__["cmd.run"](run_command) ret_val[key] = _parser(result) @@ -189,7 +186,7 @@ def memory(): # Test begins! for oper in memory_oper: for scope in memory_scope: - key = "Operation: {0} Scope: {1}".format(oper, scope) + key = "Operation: {} Scope: {}".format(oper, scope) run_command = test_command.format(oper, scope) result = __salt__["cmd.run"](run_command) ret_val[key] = _parser(result) @@ -230,7 +227,7 @@ def fileio(): # Test begins! for mode in test_modes: - key = "Mode: {0}".format(mode) + key = "Mode: {}".format(mode) # Prepare phase run_command = (test_command + "prepare").format(mode) diff --git a/salt/modules/system_profiler.py b/salt/modules/system_profiler.py index f9062a64844..5cbb4998a8c 100644 --- a/salt/modules/system_profiler.py +++ b/salt/modules/system_profiler.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ System Profiler Module @@ -9,13 +8,11 @@ information about package receipts and installed applications. """ -from __future__ import absolute_import, print_function, unicode_literals import plistlib import subprocess import salt.utils.path -from salt.ext import six PROFILER_BINARY = "/usr/sbin/system_profiler" @@ -47,10 +44,7 @@ def _call_system_profiler(datatype): ) (sysprofresults, sysprof_stderr) = p.communicate(input=None) - if six.PY2: - plist = plistlib.readPlistFromString(sysprofresults) - else: - plist = plistlib.readPlistFromBytes(sysprofresults) + plist = plistlib.readPlistFromBytes(sysprofresults) try: apps = plist[0]["_items"] @@ -89,7 +83,7 @@ def receipts(): ) if "info" in details: try: - details["info"] = "{0}: {1}".format( + details["info"] = "{}: {}".format( details["info"][0], details["info"][1].strftime("%Y-%m-%d %H:%M:%S") ) except (IndexError, AttributeError): @@ -135,7 +129,7 @@ def applications(): ) if "info" in details: try: - details["info"] = "{0}: {1}".format( + details["info"] = "{}: {}".format( details["info"][0], details["info"][1].strftime("%Y-%m-%d %H:%M:%S") ) except (IndexError, AttributeError): diff --git a/salt/modules/testinframod.py b/salt/modules/testinframod.py index 3316fa7e944..e952a6e169e 100644 --- a/salt/modules/testinframod.py +++ b/salt/modules/testinframod.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ This module exposes the functionality of the TestInfra library for use with SaltStack in order to verify the state of your minions. @@ -7,7 +6,6 @@ module dynamically generates wrappers for the various resources by iterating over the values in the ``__all__`` variable exposed by the testinfra.modules namespace. """ -from __future__ import absolute_import, print_function, unicode_literals import inspect import logging @@ -81,15 +79,15 @@ def _get_method_result(module_, module_instance, method_name, method_arg=None): method_obj = getattr(module_instance, method_name) except AttributeError: raise InvalidArgumentError( - "The {0} module does not have any " - "property or method named {1}".format(module_, method_name) + "The {} module does not have any " + "property or method named {}".format(module_, method_name) ) if isinstance(method_obj, property): return method_obj.fget(module_instance) elif isinstance(method_obj, (types.MethodType, types.FunctionType)): if not method_arg: raise InvalidArgumentError( - "{0} is a method of the {1} module. An " + "{} is a method of the {} module. An " "argument dict is required.".format(method_name, module_) ) try: @@ -97,12 +95,12 @@ def _get_method_result(module_, module_instance, method_name, method_arg=None): except KeyError: raise InvalidArgumentError( "The argument dict supplied has no " - 'key named "parameter": {0}'.format(method_arg) + 'key named "parameter": {}'.format(method_arg) ) except AttributeError: raise InvalidArgumentError( - "The {0} module does not have any " - "property or method named {1}".format(module_, method_name) + "The {} module does not have any " + "property or method named {}".format(module_, method_name) ) else: return method_obj @@ -135,7 +133,7 @@ def _apply_assertion(expected, result): comparison = re.search else: raise InvalidArgumentError( - "Comparison {0} is not a valid " + "Comparison {} is not a valid " "selection.".format(expected.get("comparison")) ) except KeyError: @@ -147,7 +145,7 @@ def _apply_assertion(expected, result): raise return comparison(expected["expected"], result) else: - raise TypeError("Expected bool or dict but received {0}".format(type(expected))) + raise TypeError("Expected bool or dict but received {}".format(type(expected))) # This does not currently generate documentation from the underlying modules diff --git a/salt/modules/tomcat.py b/salt/modules/tomcat.py index 56c0caa94d5..ab3f00ee45f 100644 --- a/salt/modules/tomcat.py +++ b/salt/modules/tomcat.py @@ -66,26 +66,12 @@ import logging import os import re import tempfile +import urllib.parse +import urllib.request import salt.utils.data import salt.utils.stringutils -# pylint: disable=no-name-in-module,import-error -from salt.ext.six import string_types as _string_types -from salt.ext.six.moves.urllib.parse import urlencode as _urlencode -from salt.ext.six.moves.urllib.request import ( - HTTPBasicAuthHandler as _HTTPBasicAuthHandler, -) -from salt.ext.six.moves.urllib.request import ( - HTTPDigestAuthHandler as _HTTPDigestAuthHandler, -) -from salt.ext.six.moves.urllib.request import build_opener as _build_opener -from salt.ext.six.moves.urllib.request import install_opener as _install_opener -from salt.ext.six.moves.urllib.request import urlopen as _urlopen - -# pylint: enable=no-name-in-module,import-error - - log = logging.getLogger(__name__) __func_alias__ = {"reload_": "reload"} @@ -157,15 +143,15 @@ def _auth(uri): if user is False or password is False: return False - basic = _HTTPBasicAuthHandler() + basic = urllib.request.HTTPBasicAuthHandler() basic.add_password( realm="Tomcat Manager Application", uri=uri, user=user, passwd=password ) - digest = _HTTPDigestAuthHandler() + digest = urllib.request.HTTPDigestAuthHandler() digest.add_password( realm="Tomcat Manager Application", uri=uri, user=user, passwd=password ) - return _build_opener(basic, digest) + return urllib.request.build_opener(basic, digest) def extract_war_version(war): @@ -230,19 +216,21 @@ def _wget(cmd, opts=None, url="http://localhost:8080/manager", timeout=180): url += "text/{}".format(cmd) url6 += "{}".format(cmd) if opts: - url += "?{}".format(_urlencode(opts)) - url6 += "?{}".format(_urlencode(opts)) + url += "?{}".format(urllib.parse.urlencode(opts)) + url6 += "?{}".format(urllib.parse.urlencode(opts)) # Make the HTTP request - _install_opener(auth) + urllib.request.install_opener(auth) try: # Trying tomcat >= 7 url - ret["msg"] = _urlopen(url, timeout=timeout).read().splitlines() + ret["msg"] = urllib.request.urlopen(url, timeout=timeout).read().splitlines() except Exception: # pylint: disable=broad-except try: # Trying tomcat6 url - ret["msg"] = _urlopen(url6, timeout=timeout).read().splitlines() + ret["msg"] = ( + urllib.request.urlopen(url6, timeout=timeout).read().splitlines() + ) except Exception: # pylint: disable=broad-except ret["msg"] = "Failed to create HTTP request" @@ -609,7 +597,7 @@ def deploy_war( # Set it to defined version or attempt extract version = extract_war_version(war) if version is True else version - if isinstance(version, _string_types): + if isinstance(version, str): # Only pass version to Tomcat if not undefined opts["version"] = version diff --git a/salt/modules/trafficserver.py b/salt/modules/trafficserver.py index 7691bff2e99..a66489dfe4e 100644 --- a/salt/modules/trafficserver.py +++ b/salt/modules/trafficserver.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Apache Traffic Server execution module. @@ -7,13 +6,10 @@ Apache Traffic Server execution module. ``traffic_ctl`` is used to execute individual Traffic Server commands and to script multiple commands in a shell. """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import logging import subprocess -# Import salt libs import salt.utils.path import salt.utils.stringutils diff --git a/salt/modules/travisci.py b/salt/modules/travisci.py index bd28e797e57..b746d3b028a 100644 --- a/salt/modules/travisci.py +++ b/salt/modules/travisci.py @@ -1,23 +1,12 @@ -# -*- coding: utf-8 -*- """ Commands for working with travisci. :depends: pyOpenSSL >= 16.0.0 """ - -# Import python libraries -from __future__ import absolute_import, print_function, unicode_literals - import base64 +import urllib.parse -# Import Salt libraries import salt.utils.json - -# Import 3rd party libraries -from salt.ext import six -from salt.ext.six.moves.urllib.parse import ( # pylint: disable=import-error,no-name-in-module - parse_qs, -) from salt.utils.versions import LooseVersion as _LooseVersion try: @@ -37,7 +26,7 @@ def __virtual__(): if HAS_OPENSSL is False: return ( False, - "The travisci module was unable to be loaded: Install pyOpenssl >= {0}".format( + "The travisci module was unable to be loaded: Install pyOpenssl >= {}".format( OPENSSL_MIN_VER ), ) @@ -46,7 +35,7 @@ def __virtual__(): if cur_version < min_version: return ( False, - "The travisci module was unable to be loaded: Install pyOpenssl >= {0}".format( + "The travisci module was unable to be loaded: Install pyOpenssl >= {}".format( OPENSSL_MIN_VER ), ) @@ -86,10 +75,10 @@ def verify_webhook(signature, body): signature = base64.b64decode(signature) # parse the urlencoded payload from travis - payload = salt.utils.json.loads(parse_qs(body)["payload"][0]) + payload = salt.utils.json.loads(urllib.parse.parse_qs(body)["payload"][0]) try: - OpenSSL.crypto.verify(certificate, signature, payload, six.text_type("sha1")) + OpenSSL.crypto.verify(certificate, signature, payload, "sha1") except OpenSSL.crypto.Error: return False return True diff --git a/salt/modules/tuned.py b/salt/modules/tuned.py index 70e86961b52..ee590709b7a 100644 --- a/salt/modules/tuned.py +++ b/salt/modules/tuned.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Interface to Red Hat tuned-adm module @@ -8,12 +7,9 @@ Interface to Red Hat tuned-adm module :platform: Linux """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import re -# Import Salt libs import salt.utils.path __func_alias__ = { @@ -81,7 +77,7 @@ def active(): return "none" pattern = re.compile(r"""(?PCurrent active profile:) (?P\w+.*)""") match = re.match(pattern, result["stdout"]) - return "{0}".format(match.group("profile")) + return "{}".format(match.group("profile")) def off(): @@ -114,7 +110,7 @@ def profile(profile_name): """ # run tuned-adm with the profile specified - result = __salt__["cmd.retcode"]("tuned-adm profile {0}".format(profile_name)) + result = __salt__["cmd.retcode"]("tuned-adm profile {}".format(profile_name)) if int(result) != 0: return False - return "{0}".format(profile_name) + return "{}".format(profile_name) diff --git a/salt/modules/twilio_notify.py b/salt/modules/twilio_notify.py index 87c68af3cc2..0332c31c7ab 100644 --- a/salt/modules/twilio_notify.py +++ b/salt/modules/twilio_notify.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Module for notifications via Twilio @@ -19,13 +18,9 @@ Module for notifications via Twilio twilio.account_sid: AC32a3c83990934481addd5ce1659f04d2 twilio.auth_token: mytoken """ -from __future__ import absolute_import, print_function, unicode_literals import logging -# import 3rd party libs -from salt.ext import six - HAS_LIBS = False try: import twilio @@ -105,7 +100,7 @@ def send_sms(profile, body, to, from_): ret["message"]["status"] = message.status ret["message"]["num_segments"] = message.num_segments ret["message"]["body"] = message.body - ret["message"]["date_sent"] = six.text_type(message.date_sent) - ret["message"]["date_created"] = six.text_type(message.date_created) + ret["message"]["date_sent"] = str(message.date_sent) + ret["message"]["date_created"] = str(message.date_created) log.info(ret) return ret diff --git a/salt/modules/uptime.py b/salt/modules/uptime.py index c57bfe76260..8e40717fa8a 100644 --- a/salt/modules/uptime.py +++ b/salt/modules/uptime.py @@ -1,15 +1,11 @@ -# -*- coding: utf-8 -*- """ Wrapper around uptime API ========================= """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals import logging -# Import Salt libs from salt.exceptions import CommandExecutionError try: @@ -47,15 +43,15 @@ def create(name, **params): """ if check_exists(name): - msg = "Trying to create check that already exists : {0}".format(name) + msg = "Trying to create check that already exists : {}".format(name) log.error(msg) raise CommandExecutionError(msg) application_url = _get_application_url() log.debug("[uptime] trying PUT request") params.update(url=name) - req = requests.put("{0}/api/checks".format(application_url), data=params) + req = requests.put("{}/api/checks".format(application_url), data=params) if not req.ok: - raise CommandExecutionError("request to uptime failed : {0}".format(req.reason)) + raise CommandExecutionError("request to uptime failed : {}".format(req.reason)) log.debug("[uptime] PUT request successful") return req.json()["_id"] @@ -71,16 +67,16 @@ def delete(name): salt '*' uptime.delete http://example.org """ if not check_exists(name): - msg = "Trying to delete check that doesn't exists : {0}".format(name) + msg = "Trying to delete check that doesn't exists : {}".format(name) log.error(msg) raise CommandExecutionError(msg) application_url = _get_application_url() log.debug("[uptime] trying DELETE request") - jcontent = requests.get("{0}/api/checks".format(application_url)).json() + jcontent = requests.get("{}/api/checks".format(application_url)).json() url_id = [x["_id"] for x in jcontent if x["url"] == name][0] - req = requests.delete("{0}/api/checks/{1}".format(application_url, url_id)) + req = requests.delete("{}/api/checks/{}".format(application_url, url_id)) if not req.ok: - raise CommandExecutionError("request to uptime failed : {0}".format(req.reason)) + raise CommandExecutionError("request to uptime failed : {}".format(req.reason)) log.debug("[uptime] DELETE request successful") return True @@ -110,7 +106,7 @@ def checks_list(): """ application_url = _get_application_url() log.debug("[uptime] get checks") - jcontent = requests.get("{0}/api/checks".format(application_url)).json() + jcontent = requests.get("{}/api/checks".format(application_url)).json() return [x["url"] for x in jcontent] diff --git a/salt/modules/uwsgi.py b/salt/modules/uwsgi.py index 7173603b2f0..d02a81945f0 100644 --- a/salt/modules/uwsgi.py +++ b/salt/modules/uwsgi.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ uWSGI stats server https://uwsgi-docs.readthedocs.io/en/latest/StatsServer.html @@ -6,10 +5,7 @@ uWSGI stats server https://uwsgi-docs.readthedocs.io/en/latest/StatsServer.html :maturity: new :platform: all """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals -# Import Salt libs import salt.utils.json import salt.utils.path @@ -43,6 +39,6 @@ def stats(socket): salt '*' uwsgi.stats 127.0.0.1:5050 """ - cmd = ["uwsgi", "--connect-and-read", "{0}".format(socket)] + cmd = ["uwsgi", "--connect-and-read", "{}".format(socket)] out = __salt__["cmd.run"](cmd, python_shell=False) return salt.utils.json.loads(out) diff --git a/salt/modules/varnish.py b/salt/modules/varnish.py index 5ee0e722883..06c09adf423 100644 --- a/salt/modules/varnish.py +++ b/salt/modules/varnish.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Support for Varnish @@ -9,17 +8,12 @@ Support for Varnish These functions are designed to work with all implementations of Varnish from 3.x onwards """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import logging import re import salt.utils.path -# Import salt libs -from salt.ext import six - log = logging.getLogger(__name__) # Define the module's virtual name @@ -127,7 +121,7 @@ def param_set(param, value): salt '*' varnish.param_set param value """ - return _run_varnishadm("param.set", [param, six.text_type(value)])["retcode"] == 0 + return _run_varnishadm("param.set", [param, str(value)])["retcode"] == 0 def param_show(param=None): diff --git a/salt/modules/vbox_guest.py b/salt/modules/vbox_guest.py index 5058a8e1b16..5ccf73ceb21 100644 --- a/salt/modules/vbox_guest.py +++ b/salt/modules/vbox_guest.py @@ -1,10 +1,7 @@ -# -*- coding: utf-8 -*- """ VirtualBox Guest Additions installer """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import contextlib import functools import glob @@ -13,9 +10,6 @@ import os import re import tempfile -# Import Salt libs -from salt.ext import six - log = logging.getLogger(__name__) __virtualname__ = "vbox_guest" _additions_dir_prefix = "VBoxGuestAdditions" @@ -89,7 +83,7 @@ def _return_mount_error(f): try: return f(*args, **kwargs) except OSError as e: - return six.text_type(e) + return str(e) return wrapper @@ -107,7 +101,7 @@ def _additions_install_program_path(mount_point): def _additions_install_opensuse(**kwargs): kernel_type = re.sub(r"^(\d|\.|-)*", "", __grains__.get("kernelrelease", "")) - kernel_devel = "kernel-{0}-devel".format(kernel_type) + kernel_devel = "kernel-{}-devel".format(kernel_type) return __states__["pkg.installed"](None, pkgs=["make", "gcc", kernel_devel]) @@ -151,7 +145,7 @@ def _additions_install_linux(mount_point, **kwargs): return additions_version() elif installer_ret["retcode"] in (127, "127"): return ( - "'{0}' not found on CD. Make sure that VirtualBox Guest " + "'{}' not found on CD. Make sure that VirtualBox Guest " "Additions CD is attached to the CD IDE Controller.".format( os.path.basename(installer_path) ) @@ -196,7 +190,7 @@ def _additions_dir(): if dirs: return dirs[0] else: - raise EnvironmentError("No VirtualBox Guest Additions dirs found!") + raise OSError("No VirtualBox Guest Additions dirs found!") def _additions_remove_linux_run(cmd): @@ -209,7 +203,7 @@ def _additions_remove_linux(**kwargs): return _additions_remove_linux_run( os.path.join(_additions_dir(), "uninstall.sh") ) - except EnvironmentError: + except OSError: return False @@ -281,10 +275,10 @@ def additions_version(): """ try: d = _additions_dir() - except EnvironmentError: + except OSError: return False if d and len(os.listdir(d)) > 0: - return re.sub(r"^{0}-".format(_additions_dir_prefix), "", os.path.basename(d)) + return re.sub(r"^{}-".format(_additions_dir_prefix), "", os.path.basename(d)) return False @@ -325,7 +319,7 @@ def grant_access_to_shared_folders_to(name, users=None): else: return ( "VirtualBox Guest Additions seems to be installed, but " - "group '{0}' not found. Check your installation and fix " + "group '{}' not found. Check your installation and fix " "it. You can uninstall VirtualBox Guest Additions with " "the help of command :py:func:`vbox_guest.additions_remove " " (it has " @@ -336,7 +330,7 @@ def grant_access_to_shared_folders_to(name, users=None): "".format(_shared_folders_group) ) else: - return "Cannot replace members of the '{0}' group." "".format( + return "Cannot replace members of the '{}' group." "".format( _shared_folders_group ) diff --git a/salt/modules/vboxmanage.py b/salt/modules/vboxmanage.py index 6d3eae23478..833b94e9eb4 100644 --- a/salt/modules/vboxmanage.py +++ b/salt/modules/vboxmanage.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Support for VirtualBox using the VBoxManage command @@ -16,7 +15,6 @@ The default for this setting is ``False``. :depends: virtualbox """ -from __future__ import absolute_import, print_function, unicode_literals import logging import os.path @@ -27,16 +25,13 @@ import salt.utils.files import salt.utils.path from salt.exceptions import CommandExecutionError -# Import 3rd-party libs -from salt.ext import six - # pylint: enable=import-error,no-name-in-module LOG = logging.getLogger(__name__) -UUID_RE = re.compile("[^{0}]".format("a-zA-Z0-9._-")) -NAME_RE = re.compile("[^{0}]".format("a-zA-Z0-9._-")) +UUID_RE = re.compile("[^{}]".format("a-zA-Z0-9._-")) +NAME_RE = re.compile("[^{}]".format("a-zA-Z0-9._-")) def __virtual__(): @@ -91,7 +86,7 @@ def list_nodes_min(): salt '*' vboxmanage.list_nodes_min """ ret = {} - cmd = "{0} list vms".format(vboxcmd()) + cmd = "{} list vms".format(vboxcmd()) for line in salt.modules.cmdmod.run(cmd).splitlines(): if not line.strip(): continue @@ -135,7 +130,7 @@ def list_nodes(): "private_ips": [], "public_ips": [], } - ret[node]["size"] = "{0} RAM, {1} CPU".format( + ret[node]["size"] = "{} RAM, {} CPU".format( nodes[node]["Memory size"], nodes[node]["Number of CPUs"], ) return ret @@ -152,7 +147,7 @@ def start(name): salt '*' vboxmanage.start my_vm """ ret = {} - cmd = "{0} startvm {1}".format(vboxcmd(), name) + cmd = "{} startvm {}".format(vboxcmd(), name) ret = salt.modules.cmdmod.run(cmd).splitlines() return ret @@ -167,7 +162,7 @@ def stop(name): salt '*' vboxmanage.stop my_vm """ - cmd = "{0} controlvm {1} poweroff".format(vboxcmd(), name) + cmd = "{} controlvm {} poweroff".format(vboxcmd(), name) ret = salt.modules.cmdmod.run(cmd).splitlines() return ret @@ -184,10 +179,10 @@ def register(filename): """ if not os.path.isfile(filename): raise CommandExecutionError( - "The specified filename ({0}) does not exist.".format(filename) + "The specified filename ({}) does not exist.".format(filename) ) - cmd = "{0} registervm {1}".format(vboxcmd(), filename) + cmd = "{} registervm {}".format(vboxcmd(), filename) ret = salt.modules.cmdmod.run_all(cmd) if ret["retcode"] == 0: return True @@ -207,10 +202,10 @@ def unregister(name, delete=False): nodes = list_nodes_min() if name not in nodes: raise CommandExecutionError( - "The specified VM ({0}) is not registered.".format(name) + "The specified VM ({}) is not registered.".format(name) ) - cmd = "{0} unregistervm {1}".format(vboxcmd(), name) + cmd = "{} unregistervm {}".format(vboxcmd(), name) if delete is True: cmd += " --delete" ret = salt.modules.cmdmod.run_all(cmd) @@ -253,7 +248,7 @@ def create( nodes = list_nodes_min() if name in nodes: raise CommandExecutionError( - "The specified VM ({0}) is already registered.".format(name) + "The specified VM ({}) is already registered.".format(name) ) params = "" @@ -261,13 +256,13 @@ def create( if name: if NAME_RE.search(name): raise CommandExecutionError("New VM name contains invalid characters") - params += " --name {0}".format(name) + params += " --name {}".format(name) if groups: - if isinstance(groups, six.string_types): + if isinstance(groups, str): groups = [groups] if isinstance(groups, list): - params += " --groups {0}".format(",".join(groups)) + params += " --groups {}".format(",".join(groups)) else: raise CommandExecutionError( "groups must be either a string or a list of strings" @@ -276,7 +271,7 @@ def create( ostypes = list_ostypes() if ostype not in ostypes: raise CommandExecutionError( - "The specified OS type ({0}) is not available.".format(name) + "The specified OS type ({}) is not available.".format(name) ) else: params += " --ostype " + ostype @@ -287,16 +282,16 @@ def create( if basefolder: if not os.path.exists(basefolder): raise CommandExecutionError( - "basefolder {0} was not found".format(basefolder) + "basefolder {} was not found".format(basefolder) ) - params += " --basefolder {0}".format(basefolder) + params += " --basefolder {}".format(basefolder) if new_uuid: if NAME_RE.search(new_uuid): raise CommandExecutionError("New UUID contains invalid characters") - params += " --uuid {0}".format(new_uuid) + params += " --uuid {}".format(new_uuid) - cmd = "{0} create {1}".format(vboxcmd(), params) + cmd = "{} create {}".format(vboxcmd(), params) ret = salt.modules.cmdmod.run_all(cmd) if ret["retcode"] == 0: return True @@ -337,13 +332,13 @@ def clonevm( if name: if name not in nodes_names: raise CommandExecutionError( - "The specified VM ({0}) is not registered.".format(name) + "The specified VM ({}) is not registered.".format(name) ) params += " " + name elif uuid: if uuid not in nodes_uuids: raise CommandExecutionError( - "The specified VM ({0}) is not registered.".format(name) + "The specified VM ({}) is not registered.".format(name) ) params += " " + uuid @@ -355,18 +350,16 @@ def clonevm( if snapshot_name: if NAME_RE.search(snapshot_name): raise CommandExecutionError("Snapshot name contains invalid characters") - params += " --snapshot {0}".format(snapshot_name) + params += " --snapshot {}".format(snapshot_name) elif snapshot_uuid: if UUID_RE.search(snapshot_uuid): raise CommandExecutionError("Snapshot name contains invalid characters") - params += " --snapshot {0}".format(snapshot_uuid) + params += " --snapshot {}".format(snapshot_uuid) valid_modes = ("machine", "machineandchildren", "all") if mode and mode not in valid_modes: raise CommandExecutionError( - 'Mode must be one of: {0} (default "machine")'.format( - ", ".join(valid_modes) - ) + 'Mode must be one of: {} (default "machine")'.format(", ".join(valid_modes)) ) else: params += " --mode " + mode @@ -374,7 +367,7 @@ def clonevm( valid_options = ("link", "keepallmacs", "keepnatmacs", "keepdisknames") if options and options not in valid_options: raise CommandExecutionError( - "If specified, options must be one of: {0}".format(", ".join(valid_options)) + "If specified, options must be one of: {}".format(", ".join(valid_options)) ) else: params += " --options " + options @@ -382,13 +375,13 @@ def clonevm( if new_name: if NAME_RE.search(new_name): raise CommandExecutionError("New name contains invalid characters") - params += " --name {0}".format(new_name) + params += " --name {}".format(new_name) if groups: - if isinstance(groups, six.string_types): + if isinstance(groups, str): groups = [groups] if isinstance(groups, list): - params += " --groups {0}".format(",".join(groups)) + params += " --groups {}".format(",".join(groups)) else: raise CommandExecutionError( "groups must be either a string or a list of strings" @@ -397,19 +390,19 @@ def clonevm( if basefolder: if not os.path.exists(basefolder): raise CommandExecutionError( - "basefolder {0} was not found".format(basefolder) + "basefolder {} was not found".format(basefolder) ) - params += " --basefolder {0}".format(basefolder) + params += " --basefolder {}".format(basefolder) if new_uuid: if NAME_RE.search(new_uuid): raise CommandExecutionError("New UUID contains invalid characters") - params += " --uuid {0}".format(new_uuid) + params += " --uuid {}".format(new_uuid) if register is True: params += " --register" - cmd = "{0} clonevm {1}".format(vboxcmd(), name) + cmd = "{} clonevm {}".format(vboxcmd(), name) ret = salt.modules.cmdmod.run_all(cmd) if ret["retcode"] == 0: return True @@ -442,7 +435,7 @@ def clonemedium( params += medium else: raise CommandExecutionError( - "Medium must be one of: {0}.".format(", ".join(valid_mediums)) + "Medium must be one of: {}.".format(", ".join(valid_mediums)) ) if (uuid_in and file_in) or (not uuid_in and not file_in): @@ -461,11 +454,11 @@ def clonemedium( items = list_items(item) if uuid_in not in items: - raise CommandExecutionError("UUID {0} was not found".format(uuid_in)) + raise CommandExecutionError("UUID {} was not found".format(uuid_in)) params += " " + uuid_in elif file_in: if not os.path.exists(file_in): - raise CommandExecutionError("File {0} was not found".format(file_in)) + raise CommandExecutionError("File {} was not found".format(file_in)) params += " " + file_in if (uuid_out and file_out) or (not uuid_out and not file_out): @@ -483,13 +476,13 @@ def clonemedium( os.unlink(file_out) params += " " + file_out except OSError: - raise CommandExecutionError("{0} is not a valid filename".format(file_out)) + raise CommandExecutionError("{} is not a valid filename".format(file_out)) if mformat: valid_mformat = ("VDI", "VMDK", "VHD", "RAW") if mformat not in valid_mformat: raise CommandExecutionError( - "If specified, mformat must be one of: {0}".format( + "If specified, mformat must be one of: {}".format( ", ".join(valid_mformat) ) ) @@ -500,7 +493,7 @@ def clonemedium( if variant and variant not in valid_variant: if not os.path.exists(file_in): raise CommandExecutionError( - "If specified, variant must be one of: {0}".format( + "If specified, variant must be one of: {}".format( ", ".join(valid_variant) ) ) @@ -510,7 +503,7 @@ def clonemedium( if existing: params += " --existing" - cmd = "{0} clonemedium {1}".format(vboxcmd(), params) + cmd = "{} clonemedium {}".format(vboxcmd(), params) ret = salt.modules.cmdmod.run_all(cmd) if ret["retcode"] == 0: return True @@ -584,9 +577,7 @@ def list_items(item, details=False, group_by="UUID"): ) if item not in types: - raise CommandExecutionError( - "Item must be one of: {0}.".format(", ".join(types)) - ) + raise CommandExecutionError("Item must be one of: {}.".format(", ".join(types))) flag = "" if details is True: @@ -595,7 +586,7 @@ def list_items(item, details=False, group_by="UUID"): ret = {} tmp_id = None tmp_dict = {} - cmd = "{0} list{1} {2}".format(vboxcmd(), flag, item) + cmd = "{} list{} {}".format(vboxcmd(), flag, item) for line in salt.modules.cmdmod.run(cmd).splitlines(): if not line.strip(): continue diff --git a/salt/modules/vcenter.py b/salt/modules/vcenter.py index 48ca6ef7100..431229f08bd 100644 --- a/salt/modules/vcenter.py +++ b/salt/modules/vcenter.py @@ -1,10 +1,7 @@ -# -*- coding: utf-8 -*- """ Module used to access the vcenter proxy connection methods """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import logging import salt.utils.platform diff --git a/salt/modules/victorops.py b/salt/modules/victorops.py index ea9cbd35d01..6276c37186d 100644 --- a/salt/modules/victorops.py +++ b/salt/modules/victorops.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Support for VictorOps @@ -12,8 +11,6 @@ Requires an ``api_key`` in ``/etc/salt/minion``: api_key: '280d4699-a817-4719-ba6f-ca56e573e44f' """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import datetime import logging @@ -21,8 +18,6 @@ import time import salt.utils.http import salt.utils.json - -# Import salt libs from salt.exceptions import SaltInvocationError log = logging.getLogger(__name__) @@ -54,10 +49,10 @@ def _query( path = "https://alert.victorops.com/integrations/generic/20131114/" if action: - path += "{0}/".format(action) + path += "{}/".format(action) if api_key: - path += "{0}/".format(api_key) + path += "{}/".format(api_key) if routing_key: path += routing_key @@ -191,7 +186,7 @@ def create_event(message_type=None, routing_key="everybody", **kwargs): data["timestamp"] = int(time.mktime(timestamp.timetuple())) except (TypeError, ValueError): raise SaltInvocationError( - "Date string could not be parsed: {0}, {1}".format( + "Date string could not be parsed: {}, {}".format( kwargs["timestamp"], timestamp_fmt ) ) @@ -206,7 +201,7 @@ def create_event(message_type=None, routing_key="everybody", **kwargs): data["state_start_time"] = int(time.mktime(state_start_time.timetuple())) except (TypeError, ValueError): raise SaltInvocationError( - "Date string could not be parsed: {0}, {1}".format( + "Date string could not be parsed: {}, {}".format( kwargs["state_start_time"], state_start_time_fmt ) ) diff --git a/salt/modules/wordpress.py b/salt/modules/wordpress.py index a6c319421e7..4ebfb3c26c9 100644 --- a/salt/modules/wordpress.py +++ b/salt/modules/wordpress.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ This module is used to manage Wordpress installations @@ -6,13 +5,11 @@ This module is used to manage Wordpress installations """ # Import Python Modules -from __future__ import absolute_import, print_function, unicode_literals import collections # Import Salt Modules import salt.utils.path -from salt.ext.six.moves import map Plugin = collections.namedtuple("Plugin", "name status update versino") @@ -44,7 +41,7 @@ def list_plugins(path, user): salt '*' wordpress.list_plugins /var/www/html apache """ ret = [] - resp = __salt__["cmd.shell"](("wp --path={0} plugin list").format(path), runas=user) + resp = __salt__["cmd.shell"](("wp --path={} plugin list").format(path), runas=user) for line in resp.split("\n")[1:]: ret.append(line.split("\t")) return [plugin.__dict__ for plugin in map(_get_plugins, ret)] @@ -71,7 +68,7 @@ def show_plugin(name, path, user): """ ret = {"name": name} resp = __salt__["cmd.shell"]( - ("wp --path={0} plugin status {1}").format(path, name), runas=user + ("wp --path={} plugin status {}").format(path, name), runas=user ).split("\n") for line in resp: if "Status" in line: @@ -105,7 +102,7 @@ def activate(name, path, user): # already active return None resp = __salt__["cmd.shell"]( - ("wp --path={0} plugin activate {1}").format(path, name), runas=user + ("wp --path={} plugin activate {}").format(path, name), runas=user ) if "Success" in resp: return True @@ -138,7 +135,7 @@ def deactivate(name, path, user): # already inactive return None resp = __salt__["cmd.shell"]( - ("wp --path={0} plugin deactivate {1}").format(path, name), runas=user + ("wp --path={} plugin deactivate {}").format(path, name), runas=user ) if "Success" in resp: return True @@ -164,7 +161,7 @@ def is_installed(path, user=None): salt '*' wordpress.is_installed /var/www/html apache """ retcode = __salt__["cmd.retcode"]( - ("wp --path={0} core is-installed").format(path), runas=user + ("wp --path={} core is-installed").format(path), runas=user ) if retcode == 0: return True @@ -205,12 +202,12 @@ def install(path, user, admin_user, admin_password, admin_email, title, url): """ retcode = __salt__["cmd.retcode"]( ( - "wp --path={0} core install " - '--title="{1}" ' - "--admin_user={2} " - "--admin_password='{3}' " - "--admin_email={4} " - "--url={5}" + "wp --path={} core install " + '--title="{}" ' + "--admin_user={} " + "--admin_password='{}' " + "--admin_email={} " + "--url={}" ).format(path, title, admin_user, admin_password, admin_email, url), runas=user, ) diff --git a/salt/modules/xapi_virt.py b/salt/modules/xapi_virt.py index aee0a79bb96..c2645f3ed33 100644 --- a/salt/modules/xapi_virt.py +++ b/salt/modules/xapi_virt.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ This module (mostly) uses the XenAPI to manage Xen virtual machines. @@ -16,22 +15,16 @@ Useful documentation: . https://github.com/xapi-project/xen-api/tree/master/scripts/examples/python . http://xenbits.xen.org/gitweb/?p=xen.git;a=tree;f=tools/python/xen/xm;hb=HEAD """ -from __future__ import absolute_import, print_function, unicode_literals import contextlib import os - -# Import python libs import sys import salt.modules.cmdmod - -# Import salt libs import salt.utils.files import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError -from salt.ext.six.moves import map, range try: import importlib # pylint: disable=minimum-python-version @@ -57,7 +50,7 @@ def _check_xenapi(): if os.path.isfile(debian_xen_version): # __salt__ is not available in __virtual__ xenversion = salt.modules.cmdmod._run_quiet(debian_xen_version) - xapipath = "/usr/lib/xen-{0}/lib/python".format(xenversion) + xapipath = "/usr/lib/xen-{}/lib/python".format(xenversion) if os.path.isdir(xapipath): sys.path.append(xapipath) @@ -163,7 +156,7 @@ def _get_metrics_record(xapi, rectype, record): Internal, returns metrics record for a rectype """ metrics_id = record["metrics"] - return getattr(xapi, "{0}_metrics".format(rectype)).get_record(metrics_id) + return getattr(xapi, "{}_metrics".format(rectype)).get_record(metrics_id) def _get_val(record, keys): @@ -514,10 +507,10 @@ def vcpu_pin(vm_, vcpu, cpus): if cpus == "all": cpumap = cpu_make_map("0-63") else: - cpumap = cpu_make_map("{0}".format(cpus)) + cpumap = cpu_make_map("{}".format(cpus)) try: - xapi.VM.add_to_VCPUs_params_live(vm_uuid, "cpumap{0}".format(vcpu), cpumap) + xapi.VM.add_to_VCPUs_params_live(vm_uuid, "cpumap{}".format(vcpu), cpumap) return True # VM.add_to_VCPUs_params_live() implementation in xend 4.1+ has # a bug which makes the client call fail. @@ -525,7 +518,7 @@ def vcpu_pin(vm_, vcpu, cpus): # for that particular one, fallback to xm / xl instead. except Exception: # pylint: disable=broad-except return __salt__["cmd.run"]( - "{0} vcpu-pin {1} {2} {3}".format(_get_xtool(), vm_, vcpu, cpus), + "{} vcpu-pin {} {} {}".format(_get_xtool(), vm_, vcpu, cpus), python_shell=False, ) @@ -649,7 +642,7 @@ def start(config_): # On Xen Source, creating a virtual machine using XenAPI is really painful. # XCP / XS make it really easy using xapi.Async.VM.start instead. Anyone? return __salt__["cmd.run"]( - "{0} create {1}".format(_get_xtool(), config_), python_shell=False + "{} create {}".format(_get_xtool(), config_), python_shell=False ) @@ -777,7 +770,7 @@ def is_hyper(): with salt.utils.files.fopen("/proc/modules") as fp_: if "xen_" not in salt.utils.stringutils.to_unicode(fp_.read()): return False - except (OSError, IOError): + except OSError: return False # there must be a smarter way... return "xenstore" in __salt__["cmd.run"](__grains__["ps"]) @@ -823,7 +816,7 @@ def vm_cputime(vm_=None): cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { "cputime": int(cputime), - "cputime_percent": int("{0:.0f}".format(cputime_percent)), + "cputime_percent": int("{:.0f}".format(cputime_percent)), } info = {} diff --git a/salt/modules/xmpp.py b/salt/modules/xmpp.py index 251580a733c..5e058ff1324 100644 --- a/salt/modules/xmpp.py +++ b/salt/modules/xmpp.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Module for Sending Messages via XMPP (a.k.a. Jabber) @@ -35,8 +34,6 @@ Module for Sending Messages via XMPP (a.k.a. Jabber) """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals import logging @@ -48,7 +45,7 @@ try: HAS_LIBS = True except ImportError: - class _ClientXMPP(object): + class _ClientXMPP: """ Fake class in order not to raise errors """ @@ -79,7 +76,7 @@ class SendMsgBot(_ClientXMPP): def __init__(self, jid, password, recipient, msg): # PyLint wrongly reports an error when calling super, hence the above # disable call - super(SendMsgBot, self).__init__(jid, password) + super().__init__(jid, password) self.recipients = [] if recipient is None else [recipient] self.rooms = [] diff --git a/salt/modules/zcbuildout.py b/salt/modules/zcbuildout.py index 2e88a840475..ba25848f783 100644 --- a/salt/modules/zcbuildout.py +++ b/salt/modules/zcbuildout.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of zc.buildout @@ -23,8 +22,6 @@ You have those following methods: * buildout """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import copy import logging @@ -32,26 +29,17 @@ import os import re import sys import traceback +import urllib.request -# Import salt libs import salt.utils.files import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError -# Import 3rd-party libs -# pylint: disable=import-error,no-name-in-module,redefined-builtin -from salt.ext import six -from salt.ext.six.moves import range -from salt.ext.six.moves.urllib.request import urlopen as _urlopen - -# pylint: enable=import-error,no-name-in-module,redefined-builtin - - INVALID_RESPONSE = "We did not get any expectable answer from buildout" VALID_RESPONSE = "" NOTSET = object() -HR = "{0}\n".format("-" * 80) +HR = "{}\n".format("-" * 80) RE_F = re.S | re.M | re.U BASE_STATUS = { "status": None, @@ -127,7 +115,7 @@ def _salt_callback(func, **kwargs): LOG.clear() # before returning, trying to compact the log output for k in ["comment", "out", "outlog"]: - if status[k] and isinstance(status[k], six.string_types): + if status[k] and isinstance(status[k], str): status[k] = "\n".join( [log for log in status[k].split("\n") if log.strip()] ) @@ -137,7 +125,7 @@ def _salt_callback(func, **kwargs): return _call_callback -class _Logger(object): +class _Logger: levels = ("info", "warn", "debug", "error") def __init__(self): @@ -145,7 +133,7 @@ class _Logger(object): self._by_level = {} def _log(self, level, msg): - if not isinstance(msg, six.text_type): + if not isinstance(msg, str): msg = msg.decode("utf-8") if level not in self._by_level: self._by_level[level] = [] @@ -218,10 +206,10 @@ def _set_status(m, comment=INVALID_RESPONSE, status=False, out=None): m["logs_by_level"] = LOG.by_level.copy() outlog, outlog_by_level = "", "" m["comment"] = comment - if out and isinstance(out, six.string_types): + if out and isinstance(out, str): outlog += HR outlog += "OUTPUT:\n" - outlog += "{0}\n".format(salt.utils.stringutils.to_unicode(out)) + outlog += "{}\n".format(salt.utils.stringutils.to_unicode(out)) outlog += HR if m["logs"]: outlog += HR @@ -231,13 +219,13 @@ def _set_status(m, comment=INVALID_RESPONSE, status=False, out=None): outlog_by_level += "Log summary by level:\n" outlog_by_level += HR for level, msg in m["logs"]: - outlog += "\n{0}: {1}\n".format( + outlog += "\n{}: {}\n".format( level.upper(), salt.utils.stringutils.to_unicode(msg) ) for logger in "error", "warn", "info", "debug": logs = m["logs_by_level"].get(logger, []) if logs: - outlog_by_level += "\n{0}:\n".format(logger.upper()) + outlog_by_level += "\n{}:\n".format(logger.upper()) for idx, log in enumerate(logs[:]): logs[idx] = salt.utils.stringutils.to_unicode(log) outlog_by_level += "\n".join(logs) @@ -299,7 +287,7 @@ def _Popen( directory = os.path.abspath(directory) if isinstance(command, list): command = " ".join(command) - LOG.debug("Running {0}".format(command)) # pylint: disable=str-format-in-logging + LOG.debug("Running {}".format(command)) # pylint: disable=str-format-in-logging if not loglevel: loglevel = "debug" ret = __salt__["cmd.run_all"]( @@ -409,7 +397,7 @@ def _get_bootstrap_content(directory="."): os.path.join(os.path.abspath(directory), "bootstrap.py") ) as fic: oldcontent = salt.utils.stringutils.to_unicode(fic.read()) - except (OSError, IOError): + except OSError: oldcontent = "" return oldcontent @@ -442,7 +430,7 @@ def _get_buildout_ver(directory="."): or "--distribute" in bcontent ): buildoutver = 1 - except (OSError, IOError): + except OSError: pass return buildoutver @@ -511,7 +499,7 @@ def upgrade_bootstrap( else: buildout_ver = _get_buildout_ver(directory) booturl = _get_bootstrap_url(directory) - LOG.debug("Using {0}".format(booturl)) # pylint: disable=str-format-in-logging + LOG.debug("Using {}".format(booturl)) # pylint: disable=str-format-in-logging # try to download an up-to-date bootstrap # set defaulttimeout # and add possible content @@ -530,12 +518,12 @@ def upgrade_bootstrap( os.makedirs(dbuild) # only try to download once per buildout checkout with salt.utils.files.fopen( - os.path.join(dbuild, "{0}.updated_bootstrap".format(buildout_ver)) + os.path.join(dbuild, "{}.updated_bootstrap".format(buildout_ver)) ): pass - except (OSError, IOError): + except OSError: LOG.info("Bootstrap updated from repository") - data = _urlopen(booturl).read() + data = urllib.request.urlopen(booturl).read() updated = True dled = True if "socket.setdefaulttimeout" not in data: @@ -549,10 +537,10 @@ def upgrade_bootstrap( fic.write(salt.utils.stringutils.to_str(data)) if dled: with salt.utils.files.fopen( - os.path.join(dbuild, "{0}.updated_bootstrap".format(buildout_ver)), "w" + os.path.join(dbuild, "{}.updated_bootstrap".format(buildout_ver)), "w" ) as afic: afic.write("foo") - except (OSError, IOError): + except OSError: if oldcontent: with salt.utils.files.fopen(b_py, "w") as fic: fic.write(salt.utils.stringutils.to_str(oldcontent)) @@ -702,20 +690,20 @@ def bootstrap( if (test_release is not False) and " --accept-buildout-test-releases" in content: bootstrap_args += " --accept-buildout-test-releases" if config and '"-c"' in content: - bootstrap_args += " -c {0}".format(config) + bootstrap_args += " -c {}".format(config) # be sure that the bootstrap belongs to the running user try: if runas: uid = __salt__["user.info"](runas)["uid"] gid = __salt__["user.info"](runas)["gid"] os.chown("bootstrap.py", uid, gid) - except (IOError, OSError) as exc: + except OSError as exc: # don't block here, try to execute it if can pass _logger.error( - "BUILDOUT bootstrap permissions error:" " {0}".format(exc), + "BUILDOUT bootstrap permissions error:" " {}".format(exc), exc_info=_logger.isEnabledFor(logging.DEBUG), ) - cmd = "{0} bootstrap.py {1}".format(python, bootstrap_args) + cmd = "{} bootstrap.py {}".format(python, bootstrap_args) ret = _Popen( cmd, directory=directory, runas=runas, loglevel=loglevel, env=env, use_vt=use_vt ) @@ -804,11 +792,9 @@ def run_buildout( if parts: for part in parts: LOG.info( - "Installing single part: {0}".format(part) + "Installing single part: {}".format(part) ) # pylint: disable=str-format-in-logging - cmd = "{0} -c {1} {2} install {3}".format( - bcmd, config, " ".join(argv), part - ) + cmd = "{} -c {} {} install {}".format(bcmd, config, " ".join(argv), part) cmds.append(cmd) outputs.append( _Popen( @@ -823,7 +809,7 @@ def run_buildout( ) else: LOG.info("Installing all buildout parts") - cmd = "{0} -c {1} {2}".format(bcmd, config, " ".join(argv)) + cmd = "{} -c {} {}".format(bcmd, config, " ".join(argv)) cmds.append(cmd) outputs.append( _Popen( @@ -860,24 +846,24 @@ def _merge_statuses(statuses): status["out"] += "\n" status["out"] += HR out = salt.utils.stringutils.to_unicode(out) - status["out"] += "{0}\n".format(out) + status["out"] += "{}\n".format(out) status["out"] += HR if comment: if not status["comment"]: status["comment"] = "" - status["comment"] += "\n{0}\n".format( + status["comment"] += "\n{}\n".format( salt.utils.stringutils.to_unicode(comment) ) if outlog: if not status["outlog"]: status["outlog"] = "" outlog = salt.utils.stringutils.to_unicode(outlog) - status["outlog"] += "\n{0}".format(HR) + status["outlog"] += "\n{}".format(HR) status["outlog"] += outlog if outlog_by_level: if not status["outlog_by_level"]: status["outlog_by_level"] = "" - status["outlog_by_level"] += "\n{0}".format(HR) + status["outlog_by_level"] += "\n{}".format(HR) status["outlog_by_level"] += salt.utils.stringutils.to_unicode( outlog_by_level ) @@ -974,7 +960,7 @@ def buildout( salt '*' buildout.buildout /srv/mybuildout """ LOG.info( - "Running buildout in {0} ({1})".format(directory, config) + "Running buildout in {} ({})".format(directory, config) ) # pylint: disable=str-format-in-logging boot_ret = bootstrap( directory, @@ -1015,17 +1001,17 @@ def _check_onlyif_unless(onlyif, unless, directory, runas=None, env=()): status["status"] = False retcode = __salt__["cmd.retcode"] if onlyif is not None: - if not isinstance(onlyif, six.string_types): + if not isinstance(onlyif, str): if not onlyif: _valid(status, "onlyif condition is false") - elif isinstance(onlyif, six.string_types): + elif isinstance(onlyif, str): if retcode(onlyif, cwd=directory, runas=runas, env=env) != 0: _valid(status, "onlyif condition is false") if unless is not None: - if not isinstance(unless, six.string_types): + if not isinstance(unless, str): if unless: _valid(status, "unless condition is true") - elif isinstance(unless, six.string_types): + elif isinstance(unless, str): if ( retcode( unless, cwd=directory, runas=runas, env=env, python_shell=False diff --git a/salt/modules/znc.py b/salt/modules/znc.py index f9feb5ed28b..da03c0fcd77 100644 --- a/salt/modules/znc.py +++ b/salt/modules/znc.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ znc - An advanced IRC bouncer @@ -6,18 +5,14 @@ znc - An advanced IRC bouncer Provides an interface to basic ZNC functionality """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import hashlib import logging import os.path import random import signal -# Import salt libs import salt.utils.path -from salt.ext.six.moves import range log = logging.getLogger(__name__) @@ -73,7 +68,7 @@ def buildmod(*modules): # Check if module files are missing missing = [module for module in modules if not os.path.exists(module)] if missing: - return "Error: The file ({0}) does not exist.".format(", ".join(missing)) + return "Error: The file ({}) does not exist.".format(", ".join(missing)) cmd = ["znc-buildmod"] cmd.extend(modules) diff --git a/salt/modules/zookeeper.py b/salt/modules/zookeeper.py index 7ea1ad96d48..f054fd0ac19 100644 --- a/salt/modules/zookeeper.py +++ b/salt/modules/zookeeper.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Zookeeper Module ~~~~~~~~~~~~~~~~ @@ -64,7 +63,6 @@ Configuration username: daniel password: test """ -from __future__ import absolute_import, print_function, unicode_literals # Import Salt libraries import salt.utils.stringutils diff --git a/salt/modules/zpool.py b/salt/modules/zpool.py index 26e23b28cd8..ead090e4d86 100644 --- a/salt/modules/zpool.py +++ b/salt/modules/zpool.py @@ -19,7 +19,6 @@ import os import salt.utils.decorators import salt.utils.decorators.path import salt.utils.path -from salt.ext.six.moves import zip from salt.utils.odict import OrderedDict log = logging.getLogger(__name__) diff --git a/salt/output/dson.py b/salt/output/dson.py index 94af8b46d8d..7cfaa5a0717 100644 --- a/salt/output/dson.py +++ b/salt/output/dson.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Display return data in DSON format ================================== @@ -12,14 +11,9 @@ This outputter requires `Dogeon`__ (installable via pip) .. __: https://github.com/soasme/dogeon """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import logging -from salt.ext import six - -# Import 3rd-party libs try: import dson except ImportError: @@ -51,7 +45,7 @@ def output(data, **kwargs): # pylint: disable=unused-argument indent = 4 sort_keys = True - elif isinstance(indent, six.integer_types): + elif isinstance(indent, int): if indent < 0: indent = None @@ -63,10 +57,7 @@ def output(data, **kwargs): # pylint: disable=unused-argument except UnicodeDecodeError as exc: log.error("Unable to serialize output to dson") return dson.dumps( - { - "error": "Unable to serialize output to DSON", - "message": six.text_type(exc), - } + {"error": "Unable to serialize output to DSON", "message": str(exc)} ) except TypeError: diff --git a/salt/output/json_out.py b/salt/output/json_out.py index 52bee2967a2..a712d8644d5 100644 --- a/salt/output/json_out.py +++ b/salt/output/json_out.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Display return data in JSON format ================================== @@ -36,17 +35,11 @@ CLI Example: salt '*' foo.bar --out=json """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import logging -# Import Salt libs import salt.utils.json -# Import 3rd-party libs -from salt.ext import six - log = logging.getLogger(__name__) # Define the module's virtual name @@ -89,10 +82,7 @@ def output(data, **kwargs): # pylint: disable=unused-argument except UnicodeDecodeError as exc: log.error("Unable to serialize output to json") return salt.utils.json.dumps( - { - "error": "Unable to serialize output to json", - "message": six.text_type(exc), - } + {"error": "Unable to serialize output to json", "message": str(exc)} ) except TypeError: diff --git a/salt/output/key.py b/salt/output/key.py index b95f591f677..607de0b5152 100644 --- a/salt/output/key.py +++ b/salt/output/key.py @@ -1,13 +1,10 @@ -# -*- coding: utf-8 -*- """ Display salt-key output ======================= The ``salt-key`` command makes use of this outputter to format its output. """ -from __future__ import absolute_import, print_function, unicode_literals -# Import salt libs import salt.output import salt.utils.color import salt.utils.data @@ -40,19 +37,19 @@ def output(data, **kwargs): # pylint: disable=unused-argument } trans = { - pend: "{0}{1}Unaccepted Keys:{2}".format( + pend: "{}{}Unaccepted Keys:{}".format( " " * ident, color["LIGHT_RED"], color["ENDC"] ), - acc: "{0}{1}Accepted Keys:{2}".format( + acc: "{}{}Accepted Keys:{}".format( " " * ident, color["LIGHT_GREEN"], color["ENDC"] ), - den: "{0}{1}Denied Keys:{2}".format( + den: "{}{}Denied Keys:{}".format( " " * ident, color["LIGHT_MAGENTA"], color["ENDC"] ), - rej: "{0}{1}Rejected Keys:{2}".format( + rej: "{}{}Rejected Keys:{}".format( " " * ident, color["LIGHT_BLUE"], color["ENDC"] ), - "local": "{0}{1}Local Keys:{2}".format( + "local": "{}{}Local Keys:{}".format( " " * ident, color["LIGHT_MAGENTA"], color["ENDC"] ), } @@ -69,16 +66,16 @@ def output(data, **kwargs): # pylint: disable=unused-argument } trans = { - pend: "{0}{1}Unaccepted Keys:{2}".format( + pend: "{}{}Unaccepted Keys:{}".format( " " * ident, color["LIGHT_RED"], color["ENDC"] ), - acc: "{0}{1}Accepted Keys:{2}".format( + acc: "{}{}Accepted Keys:{}".format( " " * ident, color["LIGHT_GREEN"], color["ENDC"] ), - rej: "{0}{1}Rejected Keys:{2}".format( + rej: "{}{}Rejected Keys:{}".format( " " * ident, color["LIGHT_BLUE"], color["ENDC"] ), - "local": "{0}{1}Local Keys:{2}".format( + "local": "{}{}Local Keys:{}".format( " " * ident, color["LIGHT_MAGENTA"], color["ENDC"] ), } @@ -86,16 +83,16 @@ def output(data, **kwargs): # pylint: disable=unused-argument ret = "" for status in sorted(data): - ret += "{0}\n".format(trans[status]) + ret += "{}\n".format(trans[status]) for key in sorted(data[status]): key = salt.utils.data.decode(key) skey = salt.output.strip_esc_sequence(key) if strip_colors else key if isinstance(data[status], list): - ret += "{0}{1}{2}{3}\n".format( + ret += "{}{}{}{}\n".format( " " * ident, cmap[status], skey, color["ENDC"] ) if isinstance(data[status], dict): - ret += "{0}{1}{2}: {3}{4}\n".format( + ret += "{}{}{}: {}{}\n".format( " " * ident, cmap[status], skey, data[status][key], color["ENDC"] ) return ret diff --git a/salt/output/nested.py b/salt/output/nested.py index 8c4e5fe7258..413ec9485d9 100644 --- a/salt/output/nested.py +++ b/salt/output/nested.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Recursively display nested data =============================== @@ -23,22 +22,17 @@ Example output:: - Hello - World """ -from __future__ import absolute_import, print_function, unicode_literals from collections.abc import Mapping - -# Import python libs from numbers import Number -# Import salt libs import salt.output import salt.utils.color import salt.utils.odict import salt.utils.stringutils -from salt.ext import six -class NestDisplay(object): +class NestDisplay: """ Manage the nested display contents """ @@ -98,7 +92,7 @@ class NestDisplay(object): out.append( self.ustring(indent, self.LIGHT_YELLOW, repr(ret), prefix=prefix) ) - elif isinstance(ret, six.string_types): + elif isinstance(ret, str): first_line = True for line in ret.splitlines(): line_prefix = " " * len(prefix) if not first_line else prefix @@ -165,6 +159,6 @@ def output(ret, **kwargs): return "\n".join(lines) except UnicodeDecodeError: # output contains binary data that can't be decoded - return str("\n").join( # future lint: disable=blacklisted-function + return "\n".join( # future lint: disable=blacklisted-function [salt.utils.stringutils.to_str(x) for x in lines] ) diff --git a/salt/output/newline_values_only.py b/salt/output/newline_values_only.py index 89eb3e8ecc0..8396a1b7c24 100644 --- a/salt/output/newline_values_only.py +++ b/salt/output/newline_values_only.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Display values only, separated by newlines ========================================== @@ -77,12 +76,6 @@ Output 10 """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals - -# Import 3rd-party libs -from salt.ext import six - def _get_values(data): # This should be able to be improved @@ -93,7 +86,7 @@ def _get_values(data): # This would enable us to toggle # this functionality. values = [] - for _, minion_values in six.iteritems(data): + for _, minion_values in data.items(): if isinstance(minion_values, list): values.extend(minion_values) else: @@ -106,7 +99,7 @@ def _one_level_values(data): def _string_list(a_list): - return [six.text_type(item) for item in a_list] + return [str(item) for item in a_list] def output(data, **kwargs): # pylint: disable=unused-argument diff --git a/salt/output/no_out_quiet.py b/salt/output/no_out_quiet.py index ef6eb23fee3..e06decda2f3 100644 --- a/salt/output/no_out_quiet.py +++ b/salt/output/no_out_quiet.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Display no output ================= diff --git a/salt/output/no_return.py b/salt/output/no_return.py index 893cc26e48f..302afa3ce84 100644 --- a/salt/output/no_return.py +++ b/salt/output/no_return.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Display output for minions that did not return ============================================== @@ -12,16 +11,11 @@ Example output:: virtucentos: Minion did not return """ -from __future__ import absolute_import, print_function, unicode_literals -# Import salt libs import salt.utils.color -# Import 3rd-party libs -from salt.ext import six - -class NestDisplay(object): +class NestDisplay: """ Create generator for nested output """ @@ -35,16 +29,16 @@ class NestDisplay(object): """ Recursively iterate down through data structures to determine output """ - if isinstance(ret, six.string_types): + if isinstance(ret, str): lines = ret.split("\n") for line in lines: - out += "{0}{1}{2}{3}{4}\n".format( + out += "{}{}{}{}{}\n".format( self.colors["RED"], " " * indent, prefix, line, self.colors["ENDC"] ) elif isinstance(ret, dict): for key in sorted(ret): val = ret[key] - out += "{0}{1}{2}{3}{4}:\n".format( + out += "{}{}{}{}{}:\n".format( self.colors["CYAN"], " " * indent, prefix, key, self.colors["ENDC"] ) out = self.display(val, indent + 4, "", out) diff --git a/salt/output/overstatestage.py b/salt/output/overstatestage.py index f6beb1b761a..3f80e0871f6 100644 --- a/salt/output/overstatestage.py +++ b/salt/output/overstatestage.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Display clean output of an overstate stage ========================================== @@ -7,15 +6,9 @@ This outputter is used to display :ref:`Orchestrate Runner ` stages, and should not be called directly. """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals -# Import Salt libs import salt.utils.color -# Import 3rd-party libs -from salt.ext import six - # [{'group2': {'match': ['fedora17-2', 'fedora17-3'], # 'require': ['group1'], # 'sls': ['nginx', 'edit']} @@ -32,10 +25,10 @@ def output(data, **kwargs): # pylint: disable=unused-argument ) ostr = "" for comp in data: - for name, stage in six.iteritems(comp): - ostr += "{0}{1}: {2}\n".format(colors["LIGHT_BLUE"], name, colors["ENDC"]) + for name, stage in comp.items(): + ostr += "{}{}: {}\n".format(colors["LIGHT_BLUE"], name, colors["ENDC"]) for key in sorted(stage): - ostr += " {0}{1}: {2}{3}\n".format( + ostr += " {}{}: {}{}\n".format( colors["LIGHT_BLUE"], key, stage[key], colors["ENDC"] ) return ostr diff --git a/salt/output/pony.py b/salt/output/pony.py index efd24937c50..908b8b29392 100644 --- a/salt/output/pony.py +++ b/salt/output/pony.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- r""" Display Pony output data structure ================================== @@ -47,12 +46,9 @@ CLI Example: salt '*' foo.bar --out=pony """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import subprocess -# Import Salt libs import salt.utils.data import salt.utils.path diff --git a/salt/output/pprint_out.py b/salt/output/pprint_out.py index 3c02da99d9e..f94a7cdc443 100644 --- a/salt/output/pprint_out.py +++ b/salt/output/pprint_out.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Python pretty-print (pprint) ============================ @@ -20,14 +19,9 @@ Example output: 'dictionary': {'abc': 123, 'def': 456}, 'list': ['Hello', 'World']}}} """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import pprint -# Import 3rd-party libs -from salt.ext import six - # Define the module's virtual name __virtualname__ = "pprint" @@ -44,7 +38,7 @@ def output(data, **kwargs): # pylint: disable=unused-argument Print out via pretty print """ if isinstance(data, Exception): - data = six.text_type(data) + data = str(data) if "output_indent" in __opts__ and __opts__["output_indent"] >= 0: return pprint.pformat(data, indent=__opts__["output_indent"]) return pprint.pformat(data) diff --git a/salt/output/profile.py b/salt/output/profile.py index 2bf8a3483cc..d182da565ff 100644 --- a/salt/output/profile.py +++ b/salt/output/profile.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Display profiling data in a table format ======================================== @@ -30,7 +29,6 @@ To get the above appearance, use settings something like these:: out.table.prefix: '' out.table.suffix: '' """ -from __future__ import absolute_import, print_function, unicode_literals import salt.output.table_out as table_out @@ -58,11 +56,11 @@ def _find_durations(data, name_max=60): if len(name) > name_max: name = name[0 : name_max - 3] + "..." - l = len("{0:0.4f}".format(dur)) + l = len("{:0.4f}".format(dur)) if l > ml: ml = l - ret.append([dur, name, "{0}.{1}".format(mod, fun)]) + ret.append([dur, name, "{}.{}".format(mod, fun)]) for row in ret: row[0] = "{0:{w}.4f}".format(row[0], w=ml) diff --git a/salt/output/progress.py b/salt/output/progress.py index f06dece4465..1d00a379cc4 100644 --- a/salt/output/progress.py +++ b/salt/output/progress.py @@ -1,12 +1,8 @@ -# -*- coding: utf-8 -*- """ Display return data as a progress bar """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals -# Import 3rd-party libs try: import progressbar @@ -47,7 +43,7 @@ def progress_iter(progress): progressbar.Timer(), " Returns: [", progressbar.Counter(), - "/{0}]".format(progress["minion_count"]), + "/{}]".format(progress["minion_count"]), ] bar = progressbar.ProgressBar(widgets=widgets, maxval=progress["minion_count"]) bar.start() diff --git a/salt/output/raw.py b/salt/output/raw.py index 6aae14b2c70..77486ffdbdc 100644 --- a/salt/output/raw.py +++ b/salt/output/raw.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Display raw output data structure ================================= @@ -25,20 +24,14 @@ Example output: {'myminion': {'foo': {'list': ['Hello', 'World'], 'bar': 'baz', 'dictionary': {'abc': 123, 'def': 456}}}} """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals -# Import Salt libs import salt.utils.stringutils -# Import 3rd-party libs -from salt.ext import six - def output(data, **kwargs): # pylint: disable=unused-argument """ Rather basic.... """ - if not isinstance(data, six.string_types): - data = six.text_type(data) + if not isinstance(data, str): + data = str(data) return salt.utils.stringutils.to_unicode(data) diff --git a/salt/output/table_out.py b/salt/output/table_out.py index 491b59c53d0..133d094c4c0 100644 --- a/salt/output/table_out.py +++ b/salt/output/table_out.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Display output in a table format ================================= @@ -43,21 +42,14 @@ CLI Example: salt '*' foo.bar --out=table """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import operator from functools import reduce # pylint: disable=redefined-builtin -# Import Salt libs import salt.output import salt.utils.color import salt.utils.data -# Import 3rd-party libs -from salt.ext import six -from salt.ext.six.moves import map, zip # pylint: disable=redefined-builtin - __virtualname__ = "table" @@ -65,15 +57,15 @@ def __virtual__(): return __virtualname__ -class TableDisplay(object): +class TableDisplay: """ Manage the table display content. """ _JUSTIFY_MAP = { - "center": six.text_type.center, - "right": six.text_type.rjust, - "left": six.text_type.ljust, + "center": str.center, + "right": str.rjust, + "left": str.ljust, } def __init__( @@ -163,9 +155,7 @@ class TableDisplay(object): columns = map(lambda *args: args, *reduce(operator.add, logical_rows)) - max_widths = [ - max([len(six.text_type(item)) for item in column]) for column in columns - ] + max_widths = [max([len(str(item)) for item in column]) for column in columns] row_separator = self.row_delimiter * ( len(self.prefix) + len(self.suffix) @@ -187,7 +177,7 @@ class TableDisplay(object): self.prefix + self.delim.join( [ - justify(six.text_type(item), width) + justify(str(item), width) for (item, width) in zip(row, max_widths) ] ) @@ -236,16 +226,15 @@ class TableDisplay(object): temp_rows = [] if not labels: labels = [ - six.text_type(label).replace("_", " ").title() - for label in sorted(rows[0]) + str(label).replace("_", " ").title() for label in sorted(rows[0]) ] for row in rows: temp_row = [] for key in sorted(row): - temp_row.append(six.text_type(row[key])) + temp_row.append(str(row[key])) temp_rows.append(temp_row) rows = temp_rows - elif isinstance(rows[0], six.string_types): + elif isinstance(rows[0], str): rows = [ [row] for row in rows ] # encapsulate each row in a single-element list diff --git a/salt/output/txt.py b/salt/output/txt.py index 9ab2e742391..71d694a2333 100644 --- a/salt/output/txt.py +++ b/salt/output/txt.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Simple text outputter ===================== @@ -12,9 +11,7 @@ CLI Example: salt '*' foo.bar --out=txt """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import pprint @@ -29,14 +26,14 @@ def output(data, **kwargs): # pylint: disable=unused-argument # Don't blow up on non-strings try: for line in value.splitlines(): - ret += "{0}: {1}\n".format(key, line) + ret += "{}: {}\n".format(key, line) except AttributeError: - ret += "{0}: {1}\n".format(key, value) + ret += "{}: {}\n".format(key, value) else: try: ret += data + "\n" except TypeError: # For non-dictionary, non-string data, just use print - ret += "{0}\n".format(pprint.pformat(data)) + ret += "{}\n".format(pprint.pformat(data)) return ret diff --git a/salt/output/virt_query.py b/salt/output/virt_query.py index 5bbd026c45f..d20e6357e60 100644 --- a/salt/output/virt_query.py +++ b/salt/output/virt_query.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ virt.query outputter ==================== @@ -7,12 +6,6 @@ Used to display the output from the :mod:`virt.query ` runner. """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals - -# Import 3rd-party libs -from salt.ext import six - def output(data, **kwargs): # pylint: disable=unused-argument """ @@ -20,34 +13,34 @@ def output(data, **kwargs): # pylint: disable=unused-argument """ out = "" for id_ in data["data"]: - out += "{0}\n".format(id_) + out += "{}\n".format(id_) for vm_ in data["data"][id_]["vm_info"]: - out += " {0}\n".format(vm_) + out += " {}\n".format(vm_) vm_data = data[id_]["vm_info"][vm_] if "cpu" in vm_data: - out += " CPU: {0}\n".format(vm_data["cpu"]) + out += " CPU: {}\n".format(vm_data["cpu"]) if "mem" in vm_data: - out += " Memory: {0}\n".format(vm_data["mem"]) + out += " Memory: {}\n".format(vm_data["mem"]) if "state" in vm_data: - out += " State: {0}\n".format(vm_data["state"]) + out += " State: {}\n".format(vm_data["state"]) if "graphics" in vm_data: if vm_data["graphics"].get("type", "") == "vnc": - out += " Graphics: vnc - {0}:{1}\n".format( + out += " Graphics: vnc - {}:{}\n".format( id_, vm_data["graphics"]["port"] ) if "disks" in vm_data: - for disk, d_data in six.iteritems(vm_data["disks"]): - out += " Disk - {0}:\n".format(disk) - out += " Size: {0}\n".format(d_data["disk size"]) - out += " File: {0}\n".format(d_data["file"]) - out += " File Format: {0}\n".format(d_data["file format"]) + for disk, d_data in vm_data["disks"].items(): + out += " Disk - {}:\n".format(disk) + out += " Size: {}\n".format(d_data["disk size"]) + out += " File: {}\n".format(d_data["file"]) + out += " File Format: {}\n".format(d_data["file format"]) if "nics" in vm_data: for mac in vm_data["nics"]: - out += " Nic - {0}:\n".format(mac) - out += " Source: {0}\n".format( + out += " Nic - {}:\n".format(mac) + out += " Source: {}\n".format( vm_data["nics"][mac]["source"][ - next(six.iterkeys(vm_data["nics"][mac]["source"])) + next(iter(vm_data["nics"][mac]["source"].keys())) ] ) - out += " Type: {0}\n".format(vm_data["nics"][mac]["type"]) + out += " Type: {}\n".format(vm_data["nics"][mac]["type"]) return out diff --git a/salt/output/yaml_out.py b/salt/output/yaml_out.py index 06da2c88310..496f2cfc803 100644 --- a/salt/output/yaml_out.py +++ b/salt/output/yaml_out.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Display return data in YAML format ================================== @@ -27,12 +26,9 @@ CLI Example: - Hello - World """ -from __future__ import absolute_import, print_function, unicode_literals -# Import third party libs import logging -# Import salt libs import salt.utils.yaml # Define the module's virtual name diff --git a/salt/pillar/cmd_json.py b/salt/pillar/cmd_json.py index ad8c4274c4a..11101dbeb7c 100644 --- a/salt/pillar/cmd_json.py +++ b/salt/pillar/cmd_json.py @@ -1,13 +1,9 @@ -# -*- coding: utf-8 -*- """ Execute a command and read the output as JSON. The JSON data is then directly overlaid onto the minion's Pillar data. """ -from __future__ import absolute_import, print_function, unicode_literals -# Import Python libs import logging -# Import Salt libs import salt.utils.json # Don't "fix" the above docstring to put it on two lines, as the sphinx diff --git a/salt/pillar/cmd_yaml.py b/salt/pillar/cmd_yaml.py index fa777fc1a96..6a474a95c2d 100644 --- a/salt/pillar/cmd_yaml.py +++ b/salt/pillar/cmd_yaml.py @@ -1,13 +1,9 @@ -# -*- coding: utf-8 -*- """ Execute a command and read the output as YAML. The YAML data is then directly overlaid onto the minion's Pillar data """ -from __future__ import absolute_import, print_function, unicode_literals -# Import Python libs import logging -# Import Salt party libs import salt.utils.yaml # Don't "fix" the above docstring to put it on two lines, as the sphinx diff --git a/salt/pillar/cmd_yamlex.py b/salt/pillar/cmd_yamlex.py index adafe29db47..18f3d402236 100644 --- a/salt/pillar/cmd_yamlex.py +++ b/salt/pillar/cmd_yamlex.py @@ -1,16 +1,12 @@ -# -*- coding: utf-8 -*- """ Execute a command and read the output as YAMLEX. The YAMLEX data is then directly overlaid onto the minion's Pillar data """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import logging -# Import salt libs from salt.serializers.yamlex import deserialize # Set up logging @@ -25,7 +21,7 @@ def ext_pillar( """ try: command = command.replace("%s", minion_id) - return deserialize(__salt__["cmd.run"]("{0}".format(command))) + return deserialize(__salt__["cmd.run"]("{}".format(command))) except Exception: # pylint: disable=broad-except log.critical("YAML data from %s failed to parse", command) return {} diff --git a/salt/pillar/cobbler.py b/salt/pillar/cobbler.py index c28b981eab0..bcdc34fad83 100644 --- a/salt/pillar/cobbler.py +++ b/salt/pillar/cobbler.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ A module to pull data from Cobbler via its API into the Pillar dictionary @@ -24,12 +23,9 @@ modules. Module Documentation ==================== """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import logging - -import salt.ext.six.moves.xmlrpc_client # pylint: disable=E0611 +import xmlrpc.server __opts__ = { "cobbler.url": "http://localhost/cobbler_api", @@ -52,7 +48,7 @@ def ext_pillar(minion_id, pillar, key=None, only=()): # pylint: disable=W0613 log.info("Querying cobbler at %r for information for %r", url, minion_id) try: - server = salt.ext.six.moves.xmlrpc_client.Server(url, allow_none=True) + server = xmlrpc.client.Server(url, allow_none=True) if user: server.login(user, password) result = server.get_blended_data(None, minion_id) @@ -61,7 +57,7 @@ def ext_pillar(minion_id, pillar, key=None, only=()): # pylint: disable=W0613 return {} if only: - result = dict((k, result[k]) for k in only if k in result) + result = {k: result[k] for k in only if k in result} if key: result = {key: result} diff --git a/salt/pillar/confidant.py b/salt/pillar/confidant.py index 7b7b23816eb..5e8be7954ce 100644 --- a/salt/pillar/confidant.py +++ b/salt/pillar/confidant.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ An external pillar module for getting credentials from confidant. @@ -37,14 +36,10 @@ ext_pillar: Module Documentation ==================== """ -from __future__ import absolute_import, print_function, unicode_literals import copy - -# Import python libs import logging -# Import third party libs try: # pylint: disable=no-name-in-module import confidant.client diff --git a/salt/pillar/consul_pillar.py b/salt/pillar/consul_pillar.py index fd68ee4c0d2..076095fe1a1 100644 --- a/salt/pillar/consul_pillar.py +++ b/salt/pillar/consul_pillar.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Use Consul K/V as a Pillar source with values parsed as YAML @@ -135,9 +134,7 @@ This behavior can be disabled by setting ``expand_keys`` to ``false``. - consul: my_consul_config expand_keys=false """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import logging import re @@ -146,7 +143,6 @@ import salt.utils.yaml from salt.exceptions import CommandExecutionError from salt.utils.dictupdate import update as dict_merge -# Import third party libs try: import consul @@ -186,7 +182,7 @@ def ext_pillar(minion_id, pillar, conf): # pylint: disable=W0613 if minion_id not in minions: return {} - root_re = re.compile("(? """ - - -from __future__ import absolute_import, print_function, unicode_literals - import logging # Set up logging diff --git a/salt/pillar/foreman.py b/salt/pillar/foreman.py index 8d4579f90b3..62ae03072f2 100644 --- a/salt/pillar/foreman.py +++ b/salt/pillar/foreman.py @@ -1,4 +1,3 @@ -# -*- strcoding: utf-8 -*- """ A module to pull data from Foreman via its API into the Pillar dictionary @@ -38,13 +37,9 @@ Further information can be found on `GitHub r""" @@ -18,21 +17,15 @@ This external Pillar source can be configured in the master config file as such: - hg: ssh://hg@example.co/user/repo """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals import copy import hashlib import logging import os -# Import Salt Libs import salt.pillar import salt.utils.stringutils -# Import Third Party Libs -from salt.ext import six - try: import hglib except ImportError: @@ -94,7 +87,7 @@ def update(repo_uri): repo.pull() -class Repo(object): +class Repo: """ Deal with remote hg (mercurial) repository for Pillar """ @@ -104,10 +97,7 @@ class Repo(object): self.repo_uri = repo_uri cachedir = os.path.join(__opts__["cachedir"], "hg_pillar") hash_type = getattr(hashlib, __opts__.get("hash_type", "md5")) - if six.PY2: - repo_hash = hash_type(repo_uri).hexdigest() - else: - repo_hash = hash_type(salt.utils.stringutils.to_bytes(repo_uri)).hexdigest() + repo_hash = hash_type(salt.utils.stringutils.to_bytes(repo_uri)).hexdigest() self.working_dir = os.path.join(cachedir, repo_hash) if not os.path.isdir(self.working_dir): self.repo = hglib.clone(repo_uri, self.working_dir) diff --git a/salt/pillar/hiera.py b/salt/pillar/hiera.py index b98c862d8d2..19e9c78c034 100644 --- a/salt/pillar/hiera.py +++ b/salt/pillar/hiera.py @@ -1,20 +1,13 @@ -# -*- coding: utf-8 -*- """ Use hiera data as a Pillar source """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import logging -# Import salt libs import salt.utils.path import salt.utils.yaml -# Import 3rd-party libs -from salt.ext import six - # Set up logging log = logging.getLogger(__name__) @@ -32,10 +25,10 @@ def ext_pillar( """ Execute hiera and return the data """ - cmd = "hiera -c {0}".format(conf) - for key, val in six.iteritems(__grains__): - if isinstance(val, six.string_types): - cmd += " {0}='{1}'".format(key, val) + cmd = "hiera -c {}".format(conf) + for key, val in __grains__.items(): + if isinstance(val, str): + cmd += " {}='{}'".format(key, val) try: data = salt.utils.yaml.safe_load(__salt__["cmd.run"](cmd)) except Exception: # pylint: disable=broad-except diff --git a/salt/pillar/http_json.py b/salt/pillar/http_json.py index ba3ec4cc6fd..98c8a853232 100644 --- a/salt/pillar/http_json.py +++ b/salt/pillar/http_json.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ A module that adds data to the Pillar structure retrieved by an http request @@ -41,16 +40,10 @@ Module Documentation ==================== """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import logging import re - -from salt.ext import six - -# Import Salt libs -from salt.ext.six.moves.urllib.parse import quote as _quote +import urllib.parse log = logging.getLogger(__name__) @@ -70,7 +63,7 @@ def ext_pillar(minion_id, pillar, url, with_grains=False): # pylint: disable=W0 :rtype: dict """ - url = url.replace("%s", _quote(minion_id)) + url = url.replace("%s", urllib.parse.quote(minion_id)) grain_pattern = r"<(?P.*?)>" @@ -85,8 +78,8 @@ def ext_pillar(minion_id, pillar, url, with_grains=False): # pylint: disable=W0 log.error("Unable to get minion '%s' grain: %s", minion_id, grain_name) return {} - grain_value = _quote(six.text_type(grain_value)) - url = re.sub("<{0}>".format(grain_name), grain_value, url) + grain_value = urllib.parse.quote(str(grain_value)) + url = re.sub("<{}>".format(grain_name), grain_value, url) log.debug("Getting url: %s", url) data = __salt__["http.query"](url=url, decode=True, decode_type="json") diff --git a/salt/pillar/http_yaml.py b/salt/pillar/http_yaml.py index 7b4565585e5..72a7910382c 100644 --- a/salt/pillar/http_yaml.py +++ b/salt/pillar/http_yaml.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ A module that adds data to the Pillar structure retrieved by an http request @@ -40,17 +39,9 @@ in <> brackets) in the url in order to populate pillar data based on the grain v Module Documentation ==================== """ - -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals - import logging import re - -from salt.ext import six - -# Import Salt libs -from salt.ext.six.moves.urllib.parse import quote as _quote +import urllib.parse log = logging.getLogger(__name__) @@ -70,7 +61,7 @@ def ext_pillar(minion_id, pillar, url, with_grains=False): # pylint: disable=W0 :rtype: dict """ - url = url.replace("%s", _quote(minion_id)) + url = url.replace("%s", urllib.parse.quote(minion_id)) grain_pattern = r"<(?P.*?)>" @@ -85,8 +76,8 @@ def ext_pillar(minion_id, pillar, url, with_grains=False): # pylint: disable=W0 log.error("Unable to get minion '%s' grain: %s", minion_id, grain_name) return {} - grain_value = _quote(six.text_type(grain_value)) - url = re.sub("<{0}>".format(grain_name), grain_value, url) + grain_value = urllib.parse.quote(str(grain_value)) + url = re.sub("<{}>".format(grain_name), grain_value, url) log.debug("Getting url: %s", url) data = __salt__["http.query"](url=url, decode=True, decode_type="yaml") diff --git a/salt/pillar/makostack.py b/salt/pillar/makostack.py index 56a3684c44a..9330327041e 100644 --- a/salt/pillar/makostack.py +++ b/salt/pillar/makostack.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Simple and flexible YAML ext_pillar which can read pillar from within pillar. @@ -373,19 +372,13 @@ You can also select a custom merging strategy using a ``__`` object in a list: +----------------+-------------------------+-------------------------+ """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import functools import logging import os -# Import Salt libs import salt.utils.yaml -# Import 3rd-party libs -from salt.ext import six - try: from mako.lookup import TemplateLookup from mako import exceptions @@ -420,12 +413,12 @@ def ext_pillar(minion_id, pillar, *args, **kwargs): "grains": functools.partial(salt.utils.data.traverse_dict_and_list, __grains__), "opts": functools.partial(salt.utils.data.traverse_dict_and_list, __opts__), } - for matcher, matchs in six.iteritems(kwargs): + for matcher, matchs in kwargs.items(): t, matcher = matcher.split(":", 1) if t not in traverse: raise Exception( - 'Unknown traverse option "{0}", ' - "should be one of {1}".format(t, traverse.keys()) + 'Unknown traverse option "{}", ' + "should be one of {}".format(t, traverse.keys()) ) cfgs = matchs.get(traverse[t](matcher, None), []) if not isinstance(cfgs, list): @@ -495,7 +488,7 @@ def _cleanup(obj): if obj: if isinstance(obj, dict): obj.pop("__", None) - for k, v in six.iteritems(obj): + for k, v in obj.items(): obj[k] = _cleanup(v) elif isinstance(obj, list) and isinstance(obj[0], dict) and "__" in obj[0]: del obj[0] @@ -506,12 +499,12 @@ def _merge_dict(stack, obj): strategy = obj.pop("__", "merge-last") if strategy not in strategies: raise Exception( - 'Unknown strategy "{0}", should be one of {1}'.format(strategy, strategies) + 'Unknown strategy "{}", should be one of {}'.format(strategy, strategies) ) if strategy == "overwrite": return _cleanup(obj) else: - for k, v in six.iteritems(obj): + for k, v in obj.items(): if strategy == "remove": stack.pop(k, None) continue @@ -545,7 +538,7 @@ def _merge_list(stack, obj): del obj[0] if strategy not in strategies: raise Exception( - 'Unknown strategy "{0}", should be one of {1}'.format(strategy, strategies) + 'Unknown strategy "{}", should be one of {}'.format(strategy, strategies) ) if strategy == "overwrite": return obj diff --git a/salt/pillar/mongo.py b/salt/pillar/mongo.py index fde43bb8067..fb0d8625fda 100644 --- a/salt/pillar/mongo.py +++ b/salt/pillar/mongo.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Read Pillar data from a mongodb collection @@ -54,15 +53,10 @@ dict in your SLS templates. Module Documentation ==================== """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import logging import re -# Import third party libs -from salt.ext import six - try: import pymongo @@ -157,7 +151,7 @@ def ext_pillar( # Converting _id to a string # will avoid the most common serialization error cases, but DBRefs # and whatnot will still cause problems. - result["_id"] = six.text_type(result["_id"]) + result["_id"] = str(result["_id"]) return result else: # If we can't find the minion the database it's not necessarily an diff --git a/salt/pillar/mysql.py b/salt/pillar/mysql.py index 3667eccd3c9..6f2330ed766 100644 --- a/salt/pillar/mysql.py +++ b/salt/pillar/mysql.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Retrieve Pillar data by doing a MySQL query @@ -45,20 +44,15 @@ Complete example as_list: True with_lists: [1,3] """ -from __future__ import absolute_import, print_function, unicode_literals import logging - -# Import python libs from contextlib import contextmanager -# Import Salt libs from salt.pillar.sql_base import SqlBaseExtPillar # Set up logging log = logging.getLogger(__name__) -# Import third party libs try: # Trying to import MySQLdb import MySQLdb @@ -142,7 +136,7 @@ class MySQLExtPillar(SqlBaseExtPillar): This function normalizes the config block into a set of queries we can use. The return is a list of consistently laid out dicts. """ - return super(MySQLExtPillar, self).extract_queries(args, kwargs) + return super().extract_queries(args, kwargs) def ext_pillar(minion_id, pillar, *args, **kwargs): diff --git a/salt/pillar/neutron.py b/salt/pillar/neutron.py index 811d8f2121a..738305b916b 100644 --- a/salt/pillar/neutron.py +++ b/salt/pillar/neutron.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Use Openstack Neutron data as a Pillar source. Will list all networks listed inside of Neutron, to all minions. @@ -43,12 +42,9 @@ name after the Keystone profile name: - neutron: my_openstack_config neutron_networks """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals import logging -# Import Salt Libs try: import salt.utils.openstack.neutron as suoneu diff --git a/salt/pillar/nodegroups.py b/salt/pillar/nodegroups.py index 4cb2fe451db..29642c4acf0 100644 --- a/salt/pillar/nodegroups.py +++ b/salt/pillar/nodegroups.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Nodegroups Pillar ================= @@ -35,12 +34,7 @@ Configuring Nodegroups Pillar """ # Import futures -from __future__ import absolute_import, print_function, unicode_literals -# Import 3rd-party libs -from salt.ext import six - -# Import Salt libs from salt.utils.minions import CkMinions __version__ = "0.0.2" @@ -60,7 +54,7 @@ def ext_pillar(minion_id, pillar, pillar_name=None): all_nodegroups = __opts__["nodegroups"] nodegroups_minion_is_in = [] ckminions = None - for nodegroup_name in six.iterkeys(all_nodegroups): + for nodegroup_name in all_nodegroups.keys(): ckminions = ckminions or CkMinions(__opts__) _res = ckminions.check_minions(all_nodegroups[nodegroup_name], "compound") match = _res["minions"] diff --git a/salt/pillar/pepa.py b/salt/pillar/pepa.py index b90a3f34e53..7d6403ae8c9 100644 --- a/salt/pillar/pepa.py +++ b/salt/pillar/pepa.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -# -*- coding: utf-8 -*- """ Pepa ==== @@ -263,9 +262,7 @@ For more examples and information see . """ # Import futures -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import glob import logging import os @@ -276,17 +273,12 @@ import jinja2 import salt.utils.files import salt.utils.yaml -# Import Salt libs -from salt.ext import six -from salt.ext.six.moves import input # pylint: disable=import-error,redefined-builtin - __author__ = "Michael Persson " __copyright__ = "Copyright (c) 2013 Michael Persson" __license__ = "Apache License, Version 2.0" __version__ = "0.6.6" -# Import 3rd-party libs try: import requests @@ -374,7 +366,7 @@ def key_value_to_tree(data): Convert key/value to tree """ tree = {} - for flatkey, value in six.iteritems(data): + for flatkey, value in data.items(): t = tree keys = flatkey.split(__opts__["pepa_delimiter"]) for i, key in enumerate(keys, 1): @@ -408,7 +400,7 @@ def ext_pillar(minion_id, pillar, resource, sequence, subkey=False, subkey_only= output["pepa_templates"] = [] immutable = {} - for categ, info in [next(six.iteritems(s)) for s in sequence]: + for categ, info in [next(iter(s.items())) for s in sequence]: if categ not in inp: log.warning("Category is not defined: %s", categ) continue @@ -561,7 +553,7 @@ def validate(output, resource): val = cerberus.Validator() if not val.validate(output["pepa_keys"], all_schemas): - for ekey, error in six.iteritems(val.errors): + for ekey, error in val.errors.items(): log.warning("Validation failed for key %s: %s", ekey, error) output["pepa_schema_keys"] = all_schemas @@ -620,7 +612,7 @@ if __name__ == "__main__": if not request.ok: raise RuntimeError( - "Failed to authenticate to SaltStack REST API: {0}".format(request.text) + "Failed to authenticate to SaltStack REST API: {}".format(request.text) ) response = request.json() diff --git a/salt/pillar/postgres.py b/salt/pillar/postgres.py index 9c87154f5de..a4bf8a0d107 100644 --- a/salt/pillar/postgres.py +++ b/salt/pillar/postgres.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Retrieve Pillar data by doing a postgres query @@ -28,20 +27,15 @@ Complete Example as_list: True with_lists: [1,3] """ -from __future__ import absolute_import, print_function, unicode_literals import logging - -# Import python libs from contextlib import contextmanager -# Import Salt libs from salt.pillar.sql_base import SqlBaseExtPillar # Set up logging log = logging.getLogger(__name__) -# Import third party libs try: import psycopg2 @@ -113,7 +107,7 @@ class POSTGRESExtPillar(SqlBaseExtPillar): This function normalizes the config block into a set of queries we can use. The return is a list of consistently laid out dicts. """ - return super(POSTGRESExtPillar, self).extract_queries(args, kwargs) + return super().extract_queries(args, kwargs) def ext_pillar(minion_id, pillar, *args, **kwargs): diff --git a/salt/pillar/puppet.py b/salt/pillar/puppet.py index e6449bd5d12..b907ad1f321 100644 --- a/salt/pillar/puppet.py +++ b/salt/pillar/puppet.py @@ -1,13 +1,9 @@ -# -*- coding: utf-8 -*- """ Execute an unmodified puppet_node_classifier and read the output as YAML. The YAML data is then directly overlaid onto the minion's Pillar data. """ -from __future__ import absolute_import, print_function, unicode_literals -# Import Python libs import logging -# Import Salt libs import salt.utils.yaml # Don't "fix" the above docstring to put it on two lines, as the sphinx @@ -24,7 +20,7 @@ def ext_pillar(minion_id, pillar, command): # pylint: disable=W0613 """ try: data = salt.utils.yaml.safe_load( - __salt__["cmd.run"]("{0} {1}".format(command, minion_id)) + __salt__["cmd.run"]("{} {}".format(command, minion_id)) ) return data["parameters"] except Exception: # pylint: disable=broad-except diff --git a/salt/pillar/reclass_adapter.py b/salt/pillar/reclass_adapter.py index 9b9ff999bc2..7de01b113a2 100644 --- a/salt/pillar/reclass_adapter.py +++ b/salt/pillar/reclass_adapter.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Use the "reclass" database as a Pillar source @@ -51,14 +50,8 @@ setting the configuration option, like in the example above. # not work. Thanks to the __virtual__ function, however, the plugin still # responds to the name 'reclass'. -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals -# Import salt libs from salt.exceptions import SaltInvocationError - -# Import 3rd-party libs -from salt.ext import six from salt.utils.reclass import ( filter_out_source_path_option, prepend_reclass_source_path, @@ -84,7 +77,7 @@ def __virtual__(retry=False): continue # each pillar entry is a single-key hash of name -> options - opts = next(six.itervalues(pillar)) + opts = next(iter(pillar.values())) prepend_reclass_source_path(opts) break @@ -119,14 +112,14 @@ def ext_pillar(minion_id, pillar, **kwargs): return reclass_ext_pillar(minion_id, pillar, **kwargs) except TypeError as e: - if "unexpected keyword argument" in six.text_type(e): - arg = six.text_type(e).split()[-1] + if "unexpected keyword argument" in str(e): + arg = str(e).split()[-1] raise SaltInvocationError("ext_pillar.reclass: unexpected option: " + arg) else: raise except KeyError as e: - if "id" in six.text_type(e): + if "id" in str(e): raise SaltInvocationError( "ext_pillar.reclass: __opts__ does not " "define minion ID" ) @@ -134,4 +127,4 @@ def ext_pillar(minion_id, pillar, **kwargs): raise except ReclassException as e: - raise SaltInvocationError("ext_pillar.reclass: {0}".format(e)) + raise SaltInvocationError("ext_pillar.reclass: {}".format(e)) diff --git a/salt/pillar/redismod.py b/salt/pillar/redismod.py index 9cf523a8515..7a6c6da84b1 100644 --- a/salt/pillar/redismod.py +++ b/salt/pillar/redismod.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Read pillar data from a Redis backend ===================================== @@ -30,10 +29,7 @@ Configuring the Redis ext_pillar - redis: {function: key_value} """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals -# Import Salt libs import salt.utils.json __virtualname__ = "redis" diff --git a/salt/pillar/rethinkdb_pillar.py b/salt/pillar/rethinkdb_pillar.py index 8aa28fa938a..9240a6df4b0 100644 --- a/salt/pillar/rethinkdb_pillar.py +++ b/salt/pillar/rethinkdb_pillar.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Provide external pillar data from RethinkDB @@ -42,7 +41,6 @@ In the example above the following happens. Module Documentation ==================== """ -from __future__ import absolute_import, print_function, unicode_literals # Import python libraries import logging diff --git a/salt/pillar/s3.py b/salt/pillar/s3.py index 0d1cc5c37e9..6e97dfd33bd 100644 --- a/salt/pillar/s3.py +++ b/salt/pillar/s3.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Copy pillar data from a bucket in Amazon S3 @@ -88,35 +87,22 @@ for each environment rather than specifying multiple_env. This is due to issue #22471 (https://github.com/saltstack/salt/issues/22471) """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import logging import os import pickle import time +import urllib.parse from copy import deepcopy import salt.utils.files import salt.utils.hashutils - -# Import 3rd-party libs -# pylint: disable=import-error,no-name-in-module,redefined-builtin -from salt.ext import six -from salt.ext.six.moves import filter -from salt.ext.six.moves.urllib.parse import quote as _quote - -# Import salt libs from salt.pillar import Pillar -# pylint: enable=import-error,no-name-in-module,redefined-builtin - - -# Set up logging log = logging.getLogger(__name__) -class S3Credentials(object): +class S3Credentials: def __init__( self, key, @@ -190,8 +176,8 @@ def ext_pillar( if s3_sync_on_update: # sync the buckets to the local cache log.info("Syncing local pillar cache from S3...") - for saltenv, env_meta in six.iteritems(metadata): - for bucket, files in six.iteritems(_find_files(env_meta)): + for saltenv, env_meta in metadata.items(): + for bucket, files in _find_files(env_meta).items(): for file_path in files: cached_file_path = _get_cached_file_name(bucket, saltenv, file_path) log.info("%s - %s : %s", bucket, saltenv, file_path) @@ -292,7 +278,7 @@ def _get_buckets_cache_filename(bucket, prefix): if not os.path.exists(cache_dir): os.makedirs(cache_dir) - return os.path.join(cache_dir, "{0}-{1}-files.cache".format(bucket, prefix)) + return os.path.join(cache_dir, "{}-{}-files.cache".format(bucket, prefix)) def _refresh_buckets_cache_file(creds, cache_file, multiple_env, environment, prefix): @@ -432,7 +418,7 @@ def _find_files(metadata): ret = {} - for bucket, data in six.iteritems(metadata): + for bucket, data in metadata.items(): if bucket not in ret: ret[bucket] = [] @@ -490,7 +476,7 @@ def _get_file_from_s3(creds, metadata, saltenv, bucket, path, cached_file_path): kms_keyid=creds.kms_keyid, bucket=bucket, service_url=creds.service_url, - path=_quote(path), + path=urllib.parse.quote(path), local_file=cached_file_path, verify_ssl=creds.verify_ssl, location=creds.location, diff --git a/salt/pillar/saltclass.py b/salt/pillar/saltclass.py index 614bec549de..3354b1ae7ba 100644 --- a/salt/pillar/saltclass.py +++ b/salt/pillar/saltclass.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ SaltClass Pillar Module ======================= @@ -12,8 +11,6 @@ SaltClass Pillar Module For additional configuration instructions, see the :mod:`saltclass ` module """ -# import python libs -from __future__ import absolute_import, print_function, unicode_literals import logging diff --git a/salt/pillar/sql_base.py b/salt/pillar/sql_base.py index 976ca8c0d87..f7d87105af0 100644 --- a/salt/pillar/sql_base.py +++ b/salt/pillar/sql_base.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Retrieve Pillar data by doing a SQL query @@ -168,17 +167,10 @@ More complete example for MySQL (to also show configuration) as_list: True with_lists: [1,3] """ -from __future__ import absolute_import, print_function, unicode_literals import abc # Added in python2.6 so always available - -# Import python libs import logging -from salt.ext import six -from salt.ext.six.moves import range - -# Import Salt libs from salt.utils.odict import OrderedDict # Please don't strip redundant parentheses from this file. @@ -196,7 +188,7 @@ def __virtual__(): return False -class SqlBaseExtPillar(six.with_metaclass(abc.ABCMeta, object)): +class SqlBaseExtPillar(metaclass=abc.ABCMeta): """ This class receives and processes the database rows in a database agnostic way. @@ -255,7 +247,7 @@ class SqlBaseExtPillar(six.with_metaclass(abc.ABCMeta, object)): x for x in qbuffer if ( - (isinstance(x[1], six.string_types) and len(x[1])) + (isinstance(x[1], str) and len(x[1])) or (isinstance(x[1], (list, tuple)) and (len(x[1]) > 0) and x[1][0]) or (isinstance(x[1], dict) and "query" in x[1] and len(x[1]["query"])) ) @@ -270,7 +262,7 @@ class SqlBaseExtPillar(six.with_metaclass(abc.ABCMeta, object)): "with_lists": None, "ignore_null": False, } - if isinstance(qb[1], six.string_types): + if isinstance(qb[1], str): defaults["query"] = qb[1] elif isinstance(qb[1], (list, tuple)): defaults["query"] = qb[1][0] @@ -279,9 +271,7 @@ class SqlBaseExtPillar(six.with_metaclass(abc.ABCMeta, object)): # May set 'as_list' from qb[1][2]. else: defaults.update(qb[1]) - if defaults["with_lists"] and isinstance( - defaults["with_lists"], six.string_types - ): + if defaults["with_lists"] and isinstance(defaults["with_lists"], str): defaults["with_lists"] = [ int(i) for i in defaults["with_lists"].split(",") ] diff --git a/salt/pillar/sqlcipher.py b/salt/pillar/sqlcipher.py index 902460032d5..a6ea8411928 100644 --- a/salt/pillar/sqlcipher.py +++ b/salt/pillar/sqlcipher.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Retrieve Pillar data by running a SQLCipher query @@ -57,20 +56,15 @@ Complete Example as_list: True with_lists: [1,3] """ -from __future__ import absolute_import, print_function, unicode_literals import logging - -# Import python libs from contextlib import contextmanager -# Import Salt libs from salt.pillar.sql_base import SqlBaseExtPillar # Set up logging log = logging.getLogger(__name__) -# Import third party libs try: from pysqlcipher import dbapi2 as sqlcipher @@ -123,7 +117,7 @@ class SQLCipherExtPillar(SqlBaseExtPillar): conn = sqlcipher.connect( _options.get("database"), timeout=float(_options.get("timeout")) ) - conn.execute('pragma key="{0}"'.format(_options.get("pass"))) + conn.execute('pragma key="{}"'.format(_options.get("pass"))) cursor = conn.cursor() try: yield cursor diff --git a/salt/pillar/sqlite3.py b/salt/pillar/sqlite3.py index 2a232f4ad92..20f795332cf 100644 --- a/salt/pillar/sqlite3.py +++ b/salt/pillar/sqlite3.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Retrieve Pillar data by doing a SQLite3 query @@ -46,15 +45,11 @@ Complete Example as_list: True with_lists: [1,3] """ -from __future__ import absolute_import, print_function, unicode_literals import logging import sqlite3 - -# Import python libs from contextlib import contextmanager -# Import Salt libs from salt.pillar.sql_base import SqlBaseExtPillar # Set up logging diff --git a/salt/pillar/svn_pillar.py b/salt/pillar/svn_pillar.py index 10b3fe888b4..61eabb290e6 100644 --- a/salt/pillar/svn_pillar.py +++ b/salt/pillar/svn_pillar.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Clone a remote SVN repository and use the filesystem as a Pillar source @@ -46,19 +45,14 @@ section in it, like this: '*': - bar """ -from __future__ import absolute_import, print_function, unicode_literals import hashlib import logging import os - -# Import python libs from copy import deepcopy -# Import salt libs from salt.pillar import Pillar -# Import third party libs HAS_SVN = False try: import pysvn @@ -89,7 +83,7 @@ def __virtual__(): return __virtualname__ -class SvnPillar(object): +class SvnPillar: """ Deal with the remote SVN repository for Pillar """ diff --git a/salt/pillar/varstack_pillar.py b/salt/pillar/varstack_pillar.py index 831820902a9..7f1d707b538 100644 --- a/salt/pillar/varstack_pillar.py +++ b/salt/pillar/varstack_pillar.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Use `Varstack `_ data as a Pillar source @@ -19,7 +18,6 @@ data to return as pillar information. From there you can take a look at the varstack on how this file is evaluated. """ -from __future__ import absolute_import, print_function, unicode_literals try: import varstack diff --git a/salt/pillar/vault.py b/salt/pillar/vault.py index efefbd55588..b36667b91f8 100644 --- a/salt/pillar/vault.py +++ b/salt/pillar/vault.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Vault Pillar Module @@ -121,8 +120,6 @@ minion-passwd minionbadpasswd1 """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import logging @@ -163,7 +160,7 @@ def ext_pillar( if version2["v2"]: path = version2["data"] - url = "v1/{0}".format(path) + url = "v1/{}".format(path) response = __utils__["vault.make_request"]("GET", url) if response.status_code == 200: vault_pillar = response.json().get("data", {}) diff --git a/salt/pillar/venafi.py b/salt/pillar/venafi.py index ec62525cd95..ca31100e474 100644 --- a/salt/pillar/venafi.py +++ b/salt/pillar/venafi.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Venafi Pillar Certificates @@ -13,7 +12,6 @@ section of your ``master`` configuration file: ext_pillar: - venafi: True """ -from __future__ import absolute_import, print_function, unicode_literals import logging diff --git a/salt/pillar/virtkey.py b/salt/pillar/virtkey.py index ca5ce4381e9..37afa66dd67 100644 --- a/salt/pillar/virtkey.py +++ b/salt/pillar/virtkey.py @@ -1,13 +1,9 @@ -# -*- coding: utf-8 -*- """ Accept a key from a hypervisor if the virt runner has already submitted an authorization request """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import logging -# Import salt libs import salt.utils.virt # Don't "fix" the above docstring to put it on two lines, as the sphinx diff --git a/salt/proxy/arista_pyeapi.py b/salt/proxy/arista_pyeapi.py index 0446d8c844e..18ffada1b7f 100644 --- a/salt/proxy/arista_pyeapi.py +++ b/salt/proxy/arista_pyeapi.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Arista pyeapi ============= @@ -65,15 +64,12 @@ Proxy Pillar Example username: example password: example """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python stdlib import logging # Import salt modules from salt.utils.args import clean_kwargs -# Import third party libs try: import pyeapi diff --git a/salt/proxy/chronos.py b/salt/proxy/chronos.py index cc60fc2c6a3..b128a550ece 100644 --- a/salt/proxy/chronos.py +++ b/salt/proxy/chronos.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Chronos ======== @@ -24,7 +23,6 @@ the chronos endpoint: .. versionadded:: 2015.8.2 """ -from __future__ import absolute_import, print_function, unicode_literals import logging @@ -57,7 +55,7 @@ def ping(): """ try: response = salt.utils.http.query( - "{0}/scheduler/jobs".format(CONFIG[CONFIG_BASE_URL]), + "{}/scheduler/jobs".format(CONFIG[CONFIG_BASE_URL]), decode_type="json", decode=True, ) diff --git a/salt/proxy/cisconso.py b/salt/proxy/cisconso.py index c88ce0f4c5a..aa97f37b1b5 100644 --- a/salt/proxy/cisconso.py +++ b/salt/proxy/cisconso.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Proxy Minion interface module for managing (practically) any network device with Cisco Network Services Orchestrator (Cisco NSO). Cisco NSO uses a series of @@ -172,12 +171,9 @@ responding: salt test.ping """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals import logging -# Import Salt Libs from salt.exceptions import SaltSystemExit # This must be present or the Salt loader won't load this module. diff --git a/salt/proxy/esxcluster.py b/salt/proxy/esxcluster.py index 2e8b2394fd0..fbc554ea257 100644 --- a/salt/proxy/esxcluster.py +++ b/salt/proxy/esxcluster.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Proxy Minion interface module for managing VMWare ESXi clusters. @@ -150,15 +149,9 @@ Associated states are documented in Look there to find an example structure for Pillar as well as an example ``.sls`` file for configuring an ESX cluster from scratch. """ - - -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals - import logging import os -# Import Salt Libs import salt.exceptions from salt.config.schemas.esxcluster import EsxclusterProxySchema from salt.utils.dictupdate import merge diff --git a/salt/proxy/esxdatacenter.py b/salt/proxy/esxdatacenter.py index 1082a7eb7d4..500b929f323 100644 --- a/salt/proxy/esxdatacenter.py +++ b/salt/proxy/esxdatacenter.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Proxy Minion interface module for managing VMWare ESXi clusters. @@ -145,13 +144,10 @@ Look there to find an example structure for Pillar as well as an example ``.sls`` file for configuring an ESX datacenter from scratch. """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals import logging import os -# Import Salt Libs import salt.exceptions from salt.config.schemas.esxdatacenter import EsxdatacenterProxySchema from salt.utils.dictupdate import merge diff --git a/salt/proxy/esxi.py b/salt/proxy/esxi.py index 061bf46abb0..703e751a3e8 100644 --- a/salt/proxy/esxi.py +++ b/salt/proxy/esxi.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Proxy Minion interface module for managing VMware ESXi hosts. @@ -270,7 +269,6 @@ for standing up an ESXi host from scratch. """ -from __future__ import absolute_import, print_function, unicode_literals import logging import os diff --git a/salt/proxy/esxvm.py b/salt/proxy/esxvm.py index f21aaa134f5..ce2e0751644 100644 --- a/salt/proxy/esxvm.py +++ b/salt/proxy/esxvm.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Proxy Minion interface module for managing VMWare ESXi virtual machines. @@ -145,13 +144,10 @@ Look there to find an example structure for Pillar as well as an example ``.sls`` file for configuring an ESX virtual machine from scratch. """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals import logging import os -# Import Salt Libs import salt.exceptions as excs from salt.utils.dictupdate import merge diff --git a/salt/proxy/fx2.py b/salt/proxy/fx2.py index bbdab761407..5e6feb94a53 100644 --- a/salt/proxy/fx2.py +++ b/salt/proxy/fx2.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*-, """ Dell FX2 chassis ================ @@ -171,9 +170,7 @@ Look there to find an example structure for pillar as well as an example ``.sls`` file for standing up a Dell Chassis from scratch. """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import logging import salt.utils.http diff --git a/salt/proxy/marathon.py b/salt/proxy/marathon.py index b5d83a3a234..72242c99171 100644 --- a/salt/proxy/marathon.py +++ b/salt/proxy/marathon.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Marathon ======== @@ -24,7 +23,6 @@ the marathon endpoint: .. versionadded:: 2015.8.2 """ -from __future__ import absolute_import, print_function, unicode_literals import logging @@ -57,9 +55,7 @@ def ping(): """ try: response = salt.utils.http.query( - "{0}/ping".format(CONFIG[CONFIG_BASE_URL]), - decode_type="plain", - decode=True, + "{}/ping".format(CONFIG[CONFIG_BASE_URL]), decode_type="plain", decode=True, ) log.debug( "marathon.info returned successfully: %s", response, diff --git a/salt/proxy/napalm.py b/salt/proxy/napalm.py index ef90c62d9af..ccddd2b6e4b 100644 --- a/salt/proxy/napalm.py +++ b/salt/proxy/napalm.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ NAPALM: Network Automation and Programmability Abstraction Layer with Multivendor support ========================================================================================= @@ -158,15 +157,12 @@ Example using a user-specific library, extending NAPALM's capabilities, e.g. ``c ``salt '*' net.arp username=my-alt-usr force_reconnect=True``. """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python lib import logging import salt.utils.napalm # Import Salt modules -from salt.ext import six log = logging.getLogger(__file__) @@ -295,7 +291,7 @@ def shutdown(opts): log.error( "Cannot close connection with %s%s! Please check error: %s", NETWORK_DEVICE.get("HOSTNAME", "[unknown hostname]"), - ":{0}".format(port) if port else "", + ":{}".format(port) if port else "", error, ) @@ -342,7 +338,7 @@ def call(method, *args, **kwargs): """ kwargs_copy = {} kwargs_copy.update(kwargs) - for karg, warg in six.iteritems(kwargs_copy): + for karg, warg in kwargs_copy.items(): # will remove None values # thus the NAPALM methods will be called with their defaults if warg is None: diff --git a/salt/proxy/nxos_api.py b/salt/proxy/nxos_api.py index da32e63391b..62a04629680 100644 --- a/salt/proxy/nxos_api.py +++ b/salt/proxy/nxos_api.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Proxy Minion to manage Cisco Nexus Switches (NX-OS) over the NX-API @@ -99,9 +98,7 @@ Proxy Pillar Example username: example password: example """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python stdlib import copy import logging diff --git a/salt/proxy/philips_hue.py b/salt/proxy/philips_hue.py index 0a2365b921a..9b846baf096 100644 --- a/salt/proxy/philips_hue.py +++ b/salt/proxy/philips_hue.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright 2015 SUSE LLC # @@ -34,16 +33,13 @@ To configure the proxy minion: """ # pylint: disable=import-error,no-name-in-module,redefined-builtin -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs +import http.client import logging import time -import salt.ext.six.moves.http_client as http_client import salt.utils.json from salt.exceptions import CommandExecutionError, MinionError -from salt.ext import six __proxyenabled__ = ["philips_hue"] @@ -51,7 +47,7 @@ CONFIG = {} log = logging.getLogger(__file__) -class Const(object): +class Const: """ Constants for the lamp operations. """ @@ -93,7 +89,7 @@ def init(cnf): message="Cannot find 'user' parameter in the proxy configuration" ) - CONFIG["uri"] = "/api/{0}".format(CONFIG["user"]) + CONFIG["uri"] = "/api/{}".format(CONFIG["user"]) def ping(*args, **kw): @@ -121,20 +117,20 @@ def _query(lamp_id, state, action="", method="GET"): # Because salt.utils.query is that dreadful... :( err = None - url = "{0}/lights{1}".format( - CONFIG["uri"], lamp_id and "/{0}".format(lamp_id) or "" - ) + (action and "/{0}".format(action) or "") - conn = http_client.HTTPConnection(CONFIG["host"]) + url = "{}/lights{}".format( + CONFIG["uri"], lamp_id and "/{}".format(lamp_id) or "" + ) + (action and "/{}".format(action) or "") + conn = http.client.HTTPConnection(CONFIG["host"]) if method == "PUT": conn.request(method, url, salt.utils.json.dumps(state)) else: conn.request(method, url) resp = conn.getresponse() - if resp.status == http_client.OK: + if resp.status == http.client.OK: res = salt.utils.json.loads(resp.read()) else: - err = "HTTP error: {0}, {1}".format(resp.status, resp.reason) + err = "HTTP error: {}, {}".format(resp.status, resp.reason) conn.close() if err: raise CommandExecutionError(err) @@ -212,8 +208,8 @@ def call_lights(*args, **kwargs): res = dict() lights = _get_lights() for dev_id in "id" in kwargs and _get_devices(kwargs) or sorted(lights.keys()): - if lights.get(six.text_type(dev_id)): - res[dev_id] = lights[six.text_type(dev_id)] + if lights.get(str(dev_id)): + res[dev_id] = lights[str(dev_id)] return res or False @@ -246,9 +242,7 @@ def call_switch(*args, **kwargs): else: # Invert the current state state = ( - devices[six.text_type(dev_id)]["state"]["on"] - and Const.LAMP_OFF - or Const.LAMP_ON + devices[str(dev_id)]["state"]["on"] and Const.LAMP_OFF or Const.LAMP_ON ) out[dev_id] = _set(dev_id, state) @@ -275,7 +269,7 @@ def call_blink(*args, **kwargs): pause = kwargs.get("pause", 0) res = dict() for dev_id in "id" not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): - state = devices[six.text_type(dev_id)]["state"]["on"] + state = devices[str(dev_id)]["state"]["on"] _set(dev_id, state and Const.LAMP_OFF or Const.LAMP_ON) if pause: time.sleep(pause) @@ -321,7 +315,7 @@ def call_status(*args, **kwargs): res = dict() devices = _get_lights() for dev_id in "id" not in kwargs and sorted(devices.keys()) or _get_devices(kwargs): - dev_id = six.text_type(dev_id) + dev_id = str(dev_id) res[dev_id] = { "on": devices[dev_id]["state"]["on"], "reachable": devices[dev_id]["state"]["reachable"], diff --git a/salt/proxy/rest_sample.py b/salt/proxy/rest_sample.py index bed43119256..bd106a81d5b 100644 --- a/salt/proxy/rest_sample.py +++ b/salt/proxy/rest_sample.py @@ -1,11 +1,8 @@ -# -*- coding: utf-8 -*- """ This is a simple proxy-minion designed to connect to and communicate with the bottle-based web service contained in https://github.com/saltstack/salt-contrib/tree/master/proxyminion_rest_example """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import logging import salt.utils.http diff --git a/salt/queues/pgjsonb_queue.py b/salt/queues/pgjsonb_queue.py index cb148fd7294..b08c16e3727 100644 --- a/salt/queues/pgjsonb_queue.py +++ b/salt/queues/pgjsonb_queue.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ .. versionadded:: 2016.3.0 @@ -39,17 +38,13 @@ Use the following Pg database schema: salt-run queue.process_queue test all backend=pgjsonb """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import logging import sys from contextlib import contextmanager -# import salt libs import salt.utils.json from salt.exceptions import SaltInvocationError, SaltMasterError -from salt.ext import six try: import psycopg2 @@ -87,7 +82,7 @@ def _conn(commit=False): conn_kwargs = {} for key, value in defaults.items(): conn_kwargs[key] = __opts__.get( - "queue.{0}.{1}".format(__virtualname__, key), value + "queue.{}.{}".format(__virtualname__, key), value ) try: conn = psycopg2.connect(**conn_kwargs) @@ -102,9 +97,9 @@ def _conn(commit=False): yield cursor except psycopg2.DatabaseError as err: error = err.args - sys.stderr.write(six.text_type(error)) + sys.stderr.write(str(error)) cursor.execute("ROLLBACK") - six.reraise(*sys.exc_info()) + raise else: if commit: cursor.execute("COMMIT") @@ -123,9 +118,7 @@ def _list_tables(cur): def _create_table(cur, queue): - cmd = "CREATE TABLE {0}(id SERIAL PRIMARY KEY, " "data jsonb NOT NULL)".format( - queue - ) + cmd = "CREATE TABLE {}(id SERIAL PRIMARY KEY, " "data jsonb NOT NULL)".format(queue) log.debug("SQL Query: %s", cmd) cur.execute(cmd) return True @@ -136,7 +129,7 @@ def _list_items(queue): Private function to list contents of a queue """ with _conn() as cur: - cmd = "SELECT data FROM {0}".format(queue) + cmd = "SELECT data FROM {}".format(queue) log.debug("SQL Query: %s", cmd) cur.execute(cmd) contents = cur.fetchall() @@ -199,7 +192,7 @@ def insert(queue, items): with _conn(commit=True) as cur: if isinstance(items, dict): items = salt.utils.json.dumps(items) - cmd = str("""INSERT INTO {0}(data) VALUES('{1}')""").format( + cmd = """INSERT INTO {}(data) VALUES('{}')""".format( queue, items ) # future lint: disable=blacklisted-function log.debug("SQL Query: %s", cmd) @@ -208,11 +201,11 @@ def insert(queue, items): except psycopg2.IntegrityError as esc: return ( "Item already exists in this queue. " - "postgres error: {0}".format(esc) + "postgres error: {}".format(esc) ) if isinstance(items, list): items = [(salt.utils.json.dumps(el),) for el in items] - cmd = str("INSERT INTO {0}(data) VALUES (%s)").format( + cmd = "INSERT INTO {}(data) VALUES (%s)".format( queue ) # future lint: disable=blacklisted-function log.debug("SQL Query: %s", cmd) @@ -221,7 +214,7 @@ def insert(queue, items): except psycopg2.IntegrityError as esc: return ( "One or more items already exists in this queue. " - "postgres error: {0}".format(esc) + "postgres error: {}".format(esc) ) return True @@ -242,7 +235,7 @@ def delete(queue, items): return True if isinstance(items, list): items = [(salt.utils.json.dumps(el),) for el in items] - cmd = "DELETE FROM {0} WHERE data = %s".format(queue) + cmd = "DELETE FROM {} WHERE data = %s".format(queue) log.debug("SQL Query: %s", cmd) cur.executemany(cmd, items) return True @@ -252,26 +245,26 @@ def pop(queue, quantity=1, is_runner=False): """ Pop one or more or all items from the queue return them. """ - cmd = "SELECT id, data FROM {0}".format(queue) + cmd = "SELECT id, data FROM {}".format(queue) if quantity != "all": try: quantity = int(quantity) except ValueError as exc: - error_txt = ( - 'Quantity must be an integer or "all".\n' 'Error: "{0}".'.format(exc) + error_txt = 'Quantity must be an integer or "all".\n' 'Error: "{}".'.format( + exc ) raise SaltInvocationError(error_txt) - cmd = "".join([cmd, " LIMIT {0};".format(quantity)]) + cmd = "".join([cmd, " LIMIT {};".format(quantity)]) log.debug("SQL Query: %s", cmd) items = [] with _conn(commit=True) as cur: cur.execute(cmd) result = cur.fetchall() if len(result) > 0: - ids = [six.text_type(item[0]) for item in result] + ids = [str(item[0]) for item in result] items = [item[1] for item in result] idlist = "','".join(ids) - del_cmd = """DELETE FROM {0} WHERE id IN ('{1}');""".format(queue, idlist) + del_cmd = """DELETE FROM {} WHERE id IN ('{}');""".format(queue, idlist) log.debug("SQL Query: %s", del_cmd) diff --git a/salt/queues/sqlite_queue.py b/salt/queues/sqlite_queue.py index ae8a0c7e09a..b046e892aed 100644 --- a/salt/queues/sqlite_queue.py +++ b/salt/queues/sqlite_queue.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ .. versionadded:: 2014.7.0 @@ -12,8 +11,6 @@ to another location:: sqlite_queue_dir: /home/myuser/salt/master/queues """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import glob import logging @@ -24,9 +21,6 @@ import sqlite3 import salt.utils.json from salt.exceptions import SaltInvocationError -# Import 3rd-party libs -from salt.ext import six - log = logging.getLogger(__name__) # Define the module's virtual name @@ -44,7 +38,7 @@ def _conn(queue): Return an sqlite connection """ queue_dir = __opts__["sqlite_queue_dir"] - db = os.path.join(queue_dir, "{0}.db".format(queue)) + db = os.path.join(queue_dir, "{}.db".format(queue)) log.debug("Connecting to: %s", db) con = sqlite3.connect(db) @@ -67,7 +61,7 @@ def _list_tables(con): def _create_table(con, queue): with con: cur = con.cursor() - cmd = "CREATE TABLE {0}(id INTEGER PRIMARY KEY, " "name TEXT UNIQUE)".format( + cmd = "CREATE TABLE {}(id INTEGER PRIMARY KEY, " "name TEXT UNIQUE)".format( queue ) log.debug("SQL Query: %s", cmd) @@ -82,7 +76,7 @@ def _list_items(queue): con = _conn(queue) with con: cur = con.cursor() - cmd = "SELECT name FROM {0}".format(queue) + cmd = "SELECT name FROM {}".format(queue) log.debug("SQL Query: %s", cmd) cur.execute(cmd) contents = cur.fetchall() @@ -144,19 +138,19 @@ def insert(queue, items): con = _conn(queue) with con: cur = con.cursor() - if isinstance(items, six.string_types): + if isinstance(items, str): items = _quote_escape(items) - cmd = """INSERT INTO {0}(name) VALUES('{1}')""".format(queue, items) + cmd = """INSERT INTO {}(name) VALUES('{}')""".format(queue, items) log.debug("SQL Query: %s", cmd) try: cur.execute(cmd) except sqlite3.IntegrityError as esc: - return "Item already exists in this queue. " "sqlite error: {0}".format( + return "Item already exists in this queue. " "sqlite error: {}".format( esc ) if isinstance(items, list): items = [_quote_escape(el) for el in items] - cmd = "INSERT INTO {0}(name) VALUES(?)".format(queue) + cmd = "INSERT INTO {}(name) VALUES(?)".format(queue) log.debug("SQL Query: %s", cmd) newitems = [] for item in items: @@ -167,19 +161,19 @@ def insert(queue, items): except sqlite3.IntegrityError as esc: return ( "One or more items already exists in this queue. " - "sqlite error: {0}".format(esc) + "sqlite error: {}".format(esc) ) if isinstance(items, dict): items = salt.utils.json.dumps(items).replace('"', "'") items = _quote_escape(items) - cmd = str("""INSERT INTO {0}(name) VALUES('{1}')""").format( + cmd = """INSERT INTO {}(name) VALUES('{}')""".format( queue, items ) # future lint: disable=blacklisted-function log.debug("SQL Query: %s", cmd) try: cur.execute(cmd) except sqlite3.IntegrityError as esc: - return "Item already exists in this queue. " "sqlite error: {0}".format( + return "Item already exists in this queue. " "sqlite error: {}".format( esc ) return True @@ -192,15 +186,15 @@ def delete(queue, items): con = _conn(queue) with con: cur = con.cursor() - if isinstance(items, six.string_types): + if isinstance(items, str): items = _quote_escape(items) - cmd = """DELETE FROM {0} WHERE name = '{1}'""".format(queue, items) + cmd = """DELETE FROM {} WHERE name = '{}'""".format(queue, items) log.debug("SQL Query: %s", cmd) cur.execute(cmd) return True if isinstance(items, list): items = [_quote_escape(el) for el in items] - cmd = "DELETE FROM {0} WHERE name = ?".format(queue) + cmd = "DELETE FROM {} WHERE name = ?".format(queue) log.debug("SQL Query: %s", cmd) newitems = [] for item in items: @@ -210,7 +204,7 @@ def delete(queue, items): if isinstance(items, dict): items = salt.utils.json.dumps(items).replace('"', "'") items = _quote_escape(items) - cmd = ("""DELETE FROM {0} WHERE name = '{1}'""").format( + cmd = ("""DELETE FROM {} WHERE name = '{}'""").format( queue, items ) # future lint: disable=blacklisted-function log.debug("SQL Query: %s", cmd) @@ -223,16 +217,16 @@ def pop(queue, quantity=1, is_runner=False): """ Pop one or more or all items from the queue return them. """ - cmd = "SELECT name FROM {0}".format(queue) + cmd = "SELECT name FROM {}".format(queue) if quantity != "all": try: quantity = int(quantity) except ValueError as exc: - error_txt = ( - 'Quantity must be an integer or "all".\n' 'Error: "{0}".'.format(exc) + error_txt = 'Quantity must be an integer or "all".\n' 'Error: "{}".'.format( + exc ) raise SaltInvocationError(error_txt) - cmd = "".join([cmd, " LIMIT {0}".format(quantity)]) + cmd = "".join([cmd, " LIMIT {}".format(quantity)]) log.debug("SQL Query: %s", cmd) con = _conn(queue) items = [] @@ -243,9 +237,7 @@ def pop(queue, quantity=1, is_runner=False): items = [item[0] for item in result] itemlist = '","'.join(items) _quote_escape(itemlist) - del_cmd = """DELETE FROM {0} WHERE name IN ("{1}")""".format( - queue, itemlist - ) + del_cmd = """DELETE FROM {} WHERE name IN ("{}")""".format(queue, itemlist) log.debug("SQL Query: %s", del_cmd) diff --git a/salt/renderers/cheetah.py b/salt/renderers/cheetah.py index 35c956b8230..d7351fa6af9 100644 --- a/salt/renderers/cheetah.py +++ b/salt/renderers/cheetah.py @@ -1,14 +1,8 @@ -# -*- coding: utf-8 -*- """ Cheetah Renderer for Salt """ -from __future__ import absolute_import, print_function, unicode_literals -# Import salt libs -from salt.ext import six - -# Import 3rd party libs try: from Cheetah.Template import Template @@ -26,7 +20,7 @@ def render(cheetah_data, saltenv="base", sls="", method="xml", **kws): if not HAS_LIBS: return {} - if not isinstance(cheetah_data, six.string_types): + if not isinstance(cheetah_data, str): cheetah_data = cheetah_data.read() if cheetah_data.startswith("#!"): @@ -34,4 +28,4 @@ def render(cheetah_data, saltenv="base", sls="", method="xml", **kws): if not cheetah_data.strip(): return {} - return six.text_type(Template(cheetah_data, searchList=[kws])) + return str(Template(cheetah_data, searchList=[kws])) diff --git a/salt/renderers/dson.py b/salt/renderers/dson.py index 01ec7890d00..0a9597aa5f6 100644 --- a/salt/renderers/dson.py +++ b/salt/renderers/dson.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ DSON Renderer for Salt @@ -12,14 +11,9 @@ This renderer requires `Dogeon`__ (installable via pip) .. __: https://github.com/soasme/dogeon """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import logging -# Import salt libs -from salt.ext import six - try: import dson except ImportError: @@ -42,7 +36,7 @@ def render(dson_input, saltenv="base", sls="", **kwargs): :rtype: A Python data structure """ - if not isinstance(dson_input, six.string_types): + if not isinstance(dson_input, str): dson_input = dson_input.read() log.debug("DSON input = %s", dson_input) diff --git a/salt/renderers/genshi.py b/salt/renderers/genshi.py index 76a241e0767..4f09d98928b 100644 --- a/salt/renderers/genshi.py +++ b/salt/renderers/genshi.py @@ -1,14 +1,8 @@ -# -*- coding: utf-8 -*- """ Genshi Renderer for Salt """ -from __future__ import absolute_import, print_function, unicode_literals -# Import salt libs -from salt.ext import six - -# Import 3rd party libs try: from genshi.template import MarkupTemplate from genshi.template import NewTextTemplate @@ -41,7 +35,7 @@ def render(genshi_data, saltenv="base", sls="", method="xml", **kws): if not HAS_LIBS: return {} - if not isinstance(genshi_data, six.string_types): + if not isinstance(genshi_data, str): genshi_data = genshi_data.read() if genshi_data.startswith("#!"): diff --git a/salt/renderers/hjson.py b/salt/renderers/hjson.py index feb618df7bc..f76f993dee6 100644 --- a/salt/renderers/hjson.py +++ b/salt/renderers/hjson.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ hjson renderer for Salt @@ -7,12 +6,7 @@ See the hjson_ documentation for more information .. _hjson: http://laktak.github.io/hjson/ """ -from __future__ import absolute_import, print_function, unicode_literals -# Import salt libs -from salt.ext import six - -# Import 3rd party libs try: import hjson @@ -28,7 +22,7 @@ def render(hjson_data, saltenv="base", sls="", **kws): :rtype: A Python data structure """ - if not isinstance(hjson_data, six.string_types): + if not isinstance(hjson_data, str): hjson_data = hjson_data.read() if hjson_data.startswith("#!"): diff --git a/salt/renderers/json.py b/salt/renderers/json.py index d094de62d2d..36125685334 100644 --- a/salt/renderers/json.py +++ b/salt/renderers/json.py @@ -1,16 +1,10 @@ -# -*- coding: utf-8 -*- """ JSON Renderer for Salt """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import salt.utils.json -# Import salt libs -from salt.ext import six - json = salt.utils.json.import_json() @@ -21,7 +15,7 @@ def render(json_data, saltenv="base", sls="", **kws): :rtype: A Python data structure """ - if not isinstance(json_data, six.string_types): + if not isinstance(json_data, str): json_data = json_data.read() if json_data.startswith("#!"): diff --git a/salt/renderers/json5.py b/salt/renderers/json5.py index 5063cb5d253..9d4b345113f 100644 --- a/salt/renderers/json5.py +++ b/salt/renderers/json5.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ JSON5 Renderer for Salt @@ -12,14 +11,9 @@ This renderer requires the `json5 python bindings`__, installable via pip. .. __: https://pypi.python.org/pypi/json5 """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import logging -# Import salt libs -from salt.ext import six - try: import json5 as json @@ -47,7 +41,7 @@ def render(json_data, saltenv="base", sls="", **kws): :rtype: A Python data structure """ - if not isinstance(json_data, six.string_types): + if not isinstance(json_data, str): json_data = json_data.read() if json_data.startswith("#!"): diff --git a/salt/renderers/mako.py b/salt/renderers/mako.py index e5bcf8862b2..c2c300c3800 100644 --- a/salt/renderers/mako.py +++ b/salt/renderers/mako.py @@ -1,17 +1,13 @@ -# -*- coding: utf-8 -*- """ Mako Renderer for Salt """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals + +import io import salt.utils.templates from salt.exceptions import SaltRenderError -# Import salt libs -from salt.ext import six - def render(template_file, saltenv="base", sls="", context=None, tmplpath=None, **kws): """ @@ -37,4 +33,4 @@ def render(template_file, saltenv="base", sls="", context=None, tmplpath=None, * raise SaltRenderError( tmp_data.get("data", "Unknown render error in mako renderer") ) - return six.moves.StringIO(tmp_data["data"]) + return io.StringIO(tmp_data["data"]) diff --git a/salt/renderers/msgpack.py b/salt/renderers/msgpack.py index a0f2973af81..ceb25acf10e 100644 --- a/salt/renderers/msgpack.py +++ b/salt/renderers/msgpack.py @@ -1,9 +1,4 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals - -# Import salt libs import salt.utils.msgpack -from salt.ext import six def render(msgpack_data, saltenv="base", sls="", **kws): @@ -19,7 +14,7 @@ def render(msgpack_data, saltenv="base", sls="", **kws): :rtype: A Python data structure """ - if not isinstance(msgpack_data, six.string_types): + if not isinstance(msgpack_data, str): msgpack_data = msgpack_data.read() if msgpack_data.startswith("#!"): diff --git a/salt/renderers/nacl.py b/salt/renderers/nacl.py index 114594785ce..156913150e2 100644 --- a/salt/renderers/nacl.py +++ b/salt/renderers/nacl.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- r""" Renderer that will decrypt NACL ciphers @@ -53,16 +52,10 @@ data like so: """ -from __future__ import absolute_import, print_function, unicode_literals - import logging import re -# Import 3rd-party libs -import salt.ext.six as six import salt.syspaths - -# Import salt libs import salt.utils.stringio log = logging.getLogger(__name__) @@ -71,19 +64,19 @@ NACL_REGEX = r"^NACL\[(.*)\]$" def _decrypt_object(obj, **kwargs): """ - Recursively try to decrypt any object. If the object is a six.string_types - (string or unicode), and it contains a valid NACLENC pretext, decrypt it, - otherwise keep going until a string is found. + Recursively try to decrypt any object. If the object is a str, and it + contains a valid NACLENC pretext, decrypt it, otherwise keep going until a + string is found. """ if salt.utils.stringio.is_readable(obj): return _decrypt_object(obj.getvalue(), **kwargs) - if isinstance(obj, six.string_types): + if isinstance(obj, str): if re.search(NACL_REGEX, obj) is not None: return __salt__["nacl.dec"](re.search(NACL_REGEX, obj).group(1), **kwargs) else: return obj elif isinstance(obj, dict): - for key, value in six.iteritems(obj): + for key, value in obj.items(): obj[key] = _decrypt_object(value, **kwargs) return obj elif isinstance(obj, list): diff --git a/salt/renderers/pass.py b/salt/renderers/pass.py index 06723e53467..71b1021b96a 100644 --- a/salt/renderers/pass.py +++ b/salt/renderers/pass.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Pass Renderer for Salt ====================== @@ -48,21 +47,15 @@ Install pass binary pkg.installed """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import logging import os from os.path import expanduser from subprocess import PIPE, Popen -# Import salt libs import salt.utils.path from salt.exceptions import SaltRenderError -# Import 3rd-party libs -from salt.ext import six - log = logging.getLogger(__name__) @@ -82,7 +75,7 @@ def _fetch_secret(pass_path): Fetch secret from pass based on pass_path. If there is any error, return back the original pass_path value """ - cmd = "pass show {0}".format(pass_path.strip()) + cmd = "pass show {}".format(pass_path.strip()) log.debug("Fetching secret: %s", cmd) proc = Popen(cmd.split(" "), stdout=PIPE, stderr=PIPE) @@ -100,10 +93,10 @@ def _decrypt_object(obj): """ Recursively try to find a pass path (string) that can be handed off to pass """ - if isinstance(obj, six.string_types): + if isinstance(obj, str): return _fetch_secret(obj) elif isinstance(obj, dict): - for pass_key, pass_path in six.iteritems(obj): + for pass_key, pass_path in obj.items(): obj[pass_key] = _decrypt_object(pass_path) elif isinstance(obj, list): for pass_key, pass_path in enumerate(obj): diff --git a/salt/renderers/py.py b/salt/renderers/py.py index 34f6fdf6e47..0f67d7e62e7 100644 --- a/salt/renderers/py.py +++ b/salt/renderers/py.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Pure python state renderer ========================== @@ -110,14 +109,10 @@ Full Example return config """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import os import salt.utils.templates - -# Import salt libs from salt.exceptions import SaltRenderError @@ -129,7 +124,7 @@ def render(template, saltenv="base", sls="", tmplpath=None, **kws): """ template = tmplpath if not os.path.isfile(template): - raise SaltRenderError("Template {0} is not a file!".format(template)) + raise SaltRenderError("Template {} is not a file!".format(template)) tmp_data = salt.utils.templates.py( template, diff --git a/salt/renderers/pydsl.py b/salt/renderers/pydsl.py index 3987d3abba1..6602c56805b 100644 --- a/salt/renderers/pydsl.py +++ b/salt/renderers/pydsl.py @@ -229,7 +229,7 @@ is enabled by setting the ``ordered`` option on ``__pydsl__``. __pydsl__.set(ordered=True) for i in range(10): - i = six.text_type(i) + i = str(i) state(i).cmd.run('echo '+i, cwd='/') state('1').cmd.run('echo one') state('2').cmd.run(name='echo two') diff --git a/salt/renderers/stateconf.py b/salt/renderers/stateconf.py index 298ae283385..397468c7ed4 100644 --- a/salt/renderers/stateconf.py +++ b/salt/renderers/stateconf.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ A flexible renderer that takes a templating engine and a data format @@ -26,25 +25,19 @@ A flexible renderer that takes a templating engine and a data format # - apache: >= 0.1.0 # -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import copy import getopt +import io import logging import os import re from itertools import chain -# Import salt libs import salt.utils.files import salt.utils.stringutils from salt.exceptions import SaltRenderError -# Import 3rd-party libs -from salt.ext import six -from salt.ext.six.moves import StringIO # pylint: disable=import-error - __all__ = ["render"] log = logging.getLogger(__name__) @@ -117,7 +110,12 @@ def render(input, saltenv="base", sls="", argline="", **kws): ctx.update(context) tmplout = render_template( - StringIO(data), saltenv, sls, context=ctx, argline=rt_argline.strip(), **kws + io.StringIO(data), + saltenv, + sls, + context=ctx, + argline=rt_argline.strip(), + **kws ) high = render_data(tmplout, saltenv, sls, argline=rd_argline.strip()) return process_high_data(high, extract) @@ -135,7 +133,7 @@ def render(input, saltenv="base", sls="", argline="", **kws): sid = has_names_decls(data) if sid: raise SaltRenderError( - "'names' declaration(found in state id: {0}) is " + "'names' declaration(found in state id: {}) is " "not supported with implicitly ordered states! You " "should generate the states in a template for-loop " "instead.".format(sid) @@ -203,11 +201,11 @@ def render(input, saltenv="base", sls="", argline="", **kws): name, rt_argline = (args[1] + " ").split(" ", 1) render_template = renderers[name] # e.g., the mako renderer except KeyError as err: - raise SaltRenderError("Renderer: {0} is not available!".format(err)) + raise SaltRenderError("Renderer: {} is not available!".format(err)) except IndexError: raise INVALID_USAGE_ERROR - if isinstance(input, six.string_types): + if isinstance(input, str): with salt.utils.files.fopen(input, "r") as ifile: sls_templ = salt.utils.stringutils.to_unicode(ifile.read()) else: # assume file-like @@ -227,7 +225,7 @@ def render(input, saltenv="base", sls="", argline="", **kws): prefix = sls + "::" tmplctx = { k[len(prefix) :] if k.startswith(prefix) else k: v - for k, v in six.iteritems(tmplctx) + for k, v in tmplctx.items() } else: tmplctx = {} @@ -262,8 +260,8 @@ def rewrite_single_shorthand_state_decl(data): # pylint: disable=C0103 state_id_decl: state.func: [] """ - for sid, states in six.iteritems(data): - if isinstance(states, six.string_types): + for sid, states in data.items(): + if isinstance(states, str): data[sid] = {states: []} @@ -328,7 +326,7 @@ def nvlist(thelist, names=None): for nvitem in thelist: if isinstance(nvitem, dict): # then nvitem is a name-value item(a dict) of the list. - name, value = next(six.iteritems(nvitem)) + name, value = next(iter(nvitem.items())) if names is None or name in names: yield nvitem, name, value @@ -349,17 +347,16 @@ def nvlist2(thelist, names=None): """ for _, _, value in nvlist(thelist, names): - for each in nvlist(value): - yield each + yield from nvlist(value) def statelist(states_dict, sid_excludes=frozenset(["include", "exclude"])): - for sid, states in six.iteritems(states_dict): + for sid, states in states_dict.items(): if sid.startswith("__"): continue if sid in sid_excludes: continue - for sname, args in six.iteritems(states): + for sname, args in states.items(): if sname.startswith("__"): continue yield sid, states, sname, args @@ -401,11 +398,11 @@ def rename_state_ids(data, sls, is_extend=False): newsid = _local_to_abs_sid(sid, sls) if newsid in data: raise SaltRenderError( - "Can't rename state id({0}) into {1} because the later " + "Can't rename state id({}) into {} because the later " "already exists!".format(sid, newsid) ) # add a '- name: sid' to those states without '- name'. - for sname, args in six.iteritems(data[sid]): + for sname, args in data[sid].items(): if state_name(sname) == STATE_NAME: continue for arg in args: @@ -430,7 +427,7 @@ EXTENDED_REQUIRE_IN = {} # explicit require_in/watch_in/listen_in/onchanges_in/onfail_in can only contain states after it def add_implicit_requires(data): def T(sid, state): # pylint: disable=C0103 - return "{0}:{1}".format(sid, state_name(state)) + return "{}:{}".format(sid, state_name(state)) states_before = set() states_after = set() @@ -462,7 +459,7 @@ def add_implicit_requires(data): for _, rstate, rsid in reqs: if T(rsid, rstate) in states_after: raise SaltRenderError( - "State({0}) can't require/watch/listen/onchanges/onfail a state({1}) defined " + "State({}) can't require/watch/listen/onchanges/onfail a state({}) defined " "after it!".format(tag, T(rsid, rstate)) ) @@ -472,7 +469,7 @@ def add_implicit_requires(data): for _, rstate, rsid in reqs: if T(rsid, rstate) in states_before: raise SaltRenderError( - "State({0}) can't require_in/watch_in/listen_in/onchanges_in/onfail_in a state({1}) " + "State({}) can't require_in/watch_in/listen_in/onchanges_in/onfail_in a state({}) " "defined before it!".format(tag, T(rsid, rstate)) ) @@ -492,7 +489,7 @@ def add_start_state(data, sls): start_sid = __opts__["stateconf_start_state"] if start_sid in data: raise SaltRenderError( - "Can't generate start state({0})! The same state id already " + "Can't generate start state({})! The same state id already " "exists!".format(start_sid) ) if not data: @@ -502,14 +499,14 @@ def add_start_state(data, sls): # no __sls__, or it's the first state whose id declaration has a # __sls__ == sls. non_sids = ("include", "exclude", "extend") - for sid, states in six.iteritems(data): + for sid, states in data.items(): if sid in non_sids or sid.startswith("__"): continue if "__sls__" not in states or states["__sls__"] == sls: break else: raise SaltRenderError("Can't determine the first state in the sls file!") - reqin = {state_name(next(six.iterkeys(data[sid]))): sid} + reqin = {state_name(next(iter(data[sid].keys()))): sid} data[start_sid] = {STATE_FUNC: [{"require_in": [reqin]}]} @@ -517,7 +514,7 @@ def add_goal_state(data): goal_sid = __opts__["stateconf_goal_state"] if goal_sid in data: raise SaltRenderError( - "Can't generate goal state({0})! The same state id already " + "Can't generate goal state({})! The same state id already " "exists!".format(goal_sid) ) else: @@ -561,7 +558,7 @@ STATE_CONF_EXT = {} # stateconf.set under extend: ... def extract_state_confs(data, is_extend=False): - for state_id, state_dict in six.iteritems(data): + for state_id, state_dict in data.items(): if state_id == "extend" and not is_extend: extract_state_confs(state_dict, True) continue @@ -578,7 +575,7 @@ def extract_state_confs(data, is_extend=False): for sdk in state_dict[key]: if not isinstance(sdk, dict): continue - key, val = next(six.iteritems(sdk)) + key, val = next(iter(sdk.items())) conf[key] = val if not is_extend and state_id in STATE_CONF_EXT: diff --git a/salt/renderers/wempy.py b/salt/renderers/wempy.py index d5b59e47459..66976f6b383 100644 --- a/salt/renderers/wempy.py +++ b/salt/renderers/wempy.py @@ -1,14 +1,8 @@ -# -*- coding: utf-8 -*- - -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals +import io import salt.utils.templates from salt.exceptions import SaltRenderError -# Import salt libs -from salt.ext import six - def render(template_file, saltenv="base", sls="", argline="", context=None, **kws): """ @@ -32,4 +26,4 @@ def render(template_file, saltenv="base", sls="", argline="", context=None, **kw raise SaltRenderError( tmp_data.get("data", "Unknown render error in the wempy renderer") ) - return six.moves.StringIO(tmp_data["data"]) + return io.StringIO(tmp_data["data"]) diff --git a/salt/renderers/yaml.py b/salt/renderers/yaml.py index fe1666a549c..dbc71404ffc 100644 --- a/salt/renderers/yaml.py +++ b/salt/renderers/yaml.py @@ -1,23 +1,17 @@ -# -*- coding: utf-8 -*- """ YAML Renderer for Salt For YAML usage information see :ref:`Understanding YAML `. """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import logging import warnings -# Import salt libs import salt.utils.url import salt.utils.yamlloader as yamlloader_new import salt.utils.yamlloader_old as yamlloader_old from salt.exceptions import SaltRenderError -from salt.ext import six -from salt.ext.six import string_types from salt.utils.odict import OrderedDict from yaml.constructor import ConstructorError from yaml.parser import ParserError @@ -61,7 +55,7 @@ def render(yaml_data, saltenv="base", sls="", argline="", **kws): yamlloader = yamlloader_old else: yamlloader = yamlloader_new - if not isinstance(yaml_data, string_types): + if not isinstance(yaml_data, str): yaml_data = yaml_data.read() with warnings.catch_warnings(record=True) as warn_list: try: @@ -92,7 +86,7 @@ def render(yaml_data, saltenv="base", sls="", argline="", **kws): sure they're not dicts. """ if isinstance(data, dict): - for key, value in six.iteritems(data): + for key, value in data.items(): if isinstance(key, dict): raise SaltRenderError( "Invalid YAML, possible double curly-brace" diff --git a/salt/renderers/yamlex.py b/salt/renderers/yamlex.py index 2184b16d4b8..6b7756ef954 100644 --- a/salt/renderers/yamlex.py +++ b/salt/renderers/yamlex.py @@ -1,11 +1,6 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals - -# Import python libs import logging import warnings -# Import salt libs import salt.utils.url from salt.serializers.yamlex import deserialize diff --git a/salt/returners/carbon_return.py b/salt/returners/carbon_return.py index 3d31b964492..a639b05a9d7 100644 --- a/salt/returners/carbon_return.py +++ b/salt/returners/carbon_return.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Take data from salt and "return" it into a carbon receiver @@ -80,7 +79,6 @@ To override individual configuration items, append --return_kwargs '{"key:": "va salt '*' test.ping --return carbon --return_kwargs '{"skip_on_error": False}' """ -from __future__ import absolute_import, print_function, unicode_literals import logging import pickle @@ -133,7 +131,7 @@ def _carbon(host, port): ) carbon_sock.connect((host, port)) - except socket.error as err: + except OSError as err: log.error("Error connecting to %s:%s, %s", host, port, err) raise else: @@ -200,10 +198,10 @@ def _walk(path, value, metrics, timestamp, skip): ) if isinstance(value, Mapping): for key, val in value.items(): - _walk("{0}.{1}".format(path, key), val, metrics, timestamp, skip) + _walk("{}.{}".format(path, key), val, metrics, timestamp, skip) elif isinstance(value, list): for item in value: - _walk("{0}.{1}".format(path, item), item, metrics, timestamp, skip) + _walk("{}.{}".format(path, item), item, metrics, timestamp, skip) else: try: @@ -212,7 +210,7 @@ def _walk(path, value, metrics, timestamp, skip): except (TypeError, ValueError): msg = ( "Error in carbon returner, when trying to convert metric: " - "{0}, with val: {1}".format(path, value) + "{}, with val: {}".format(path, value) ) if skip: log.debug(msg) diff --git a/salt/returners/cassandra_cql_return.py b/salt/returners/cassandra_cql_return.py index 489025988f5..504cdb1a2fd 100644 --- a/salt/returners/cassandra_cql_return.py +++ b/salt/returners/cassandra_cql_return.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Return data to a cassandra server @@ -117,23 +116,17 @@ needs. SaltStack has seen situations where these timeouts can resolve some stacktraces that appear to come from the Datastax Python driver. """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import logging import time import uuid import salt.exceptions - -# Import salt libs import salt.returners import salt.utils.jid import salt.utils.json from salt.exceptions import CommandExecutionError -from salt.ext import six -# Import third party libs try: # The following imports are not directly required by this module. Rather, # they are required by the modules/cassandra_cql execution module, on which @@ -195,9 +188,9 @@ def returner(ret): ) VALUES (?, ?, ?, ?, ?, ?, ?)""" statement_arguments = [ - "{0}".format(ret["jid"]), - "{0}".format(ret["id"]), - "{0}".format(ret["fun"]), + "{}".format(ret["jid"]), + "{}".format(ret["id"]), + "{}".format(ret["fun"]), int(time.time() * 1000), salt.utils.json.dumps(ret).replace("'", "''"), salt.utils.json.dumps(ret["return"]).replace("'", "''"), @@ -222,7 +215,7 @@ def returner(ret): minion_id, last_fun ) VALUES (?, ?)""" - statement_arguments = ["{0}".format(ret["id"]), "{0}".format(ret["fun"])] + statement_arguments = ["{}".format(ret["id"]), "{}".format(ret["fun"])] # cassandra_cql.cql_query may raise a CommandExecutionError try: @@ -261,7 +254,7 @@ def event_return(events): ?, ?, ?, ?, ?) """ statement_arguments = [ - six.text_type(uuid.uuid1()), + str(uuid.uuid1()), int(time.time() * 1000), salt.utils.json.dumps(data).replace("'", "''"), __opts__["id"], diff --git a/salt/returners/cassandra_return.py b/salt/returners/cassandra_return.py index f53817769cc..fe56640e53b 100644 --- a/salt/returners/cassandra_return.py +++ b/salt/returners/cassandra_return.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Return data to a Cassandra ColumnFamily @@ -19,17 +18,11 @@ Required python modules: pycassa salt '*' test.ping --return cassandra """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import logging -# Import salt libs import salt.utils.jid -# Import third party libs -from salt.ext import six - try: import pycassa # pylint: disable=import-error @@ -76,10 +69,10 @@ def returner(ret): columns = {"fun": ret["fun"], "id": ret["id"]} if isinstance(ret["return"], dict): - for key, value in six.iteritems(ret["return"]): - columns["return.{0}".format(key)] = six.text_type(value) + for key, value in ret["return"].items(): + columns["return.{}".format(key)] = str(value) else: - columns["return"] = six.text_type(ret["return"]) + columns["return"] = str(ret["return"]) log.debug(columns) ccf.insert(ret["jid"], columns) diff --git a/salt/returners/couchbase_return.py b/salt/returners/couchbase_return.py index ece18829667..f22d55e6023 100644 --- a/salt/returners/couchbase_return.py +++ b/salt/returners/couchbase_return.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Simple returner for Couchbase. Optional configuration settings are listed below, along with sane defaults. @@ -48,18 +47,13 @@ JID/MINION_ID return: return_data full_ret: full load of job return """ -from __future__ import absolute_import, print_function, unicode_literals import logging -# Import Salt libs import salt.utils.jid import salt.utils.json import salt.utils.minions -# Import 3rd-party libs -from salt.ext import six - try: import couchbase @@ -187,7 +181,7 @@ def prep_jid(nocache=False, passed_jid=None): try: cb_.add( - six.text_type(jid), {"nocache": nocache}, ttl=_get_ttl(), + str(jid), {"nocache": nocache}, ttl=_get_ttl(), ) except couchbase.exceptions.KeyExistsError: # TODO: some sort of sleep or something? Spinning is generally bad practice @@ -203,7 +197,7 @@ def returner(load): """ cb_ = _get_connection() - hn_key = "{0}/{1}".format(load["jid"], load["id"]) + hn_key = "{}/{}".format(load["jid"], load["id"]) try: ret_doc = {"return": load["return"], "full_ret": salt.utils.json.dumps(load)} @@ -226,13 +220,13 @@ def save_load(jid, clear_load, minion=None): cb_ = _get_connection() try: - jid_doc = cb_.get(six.text_type(jid)) + jid_doc = cb_.get(str(jid)) except couchbase.exceptions.NotFoundError: - cb_.add(six.text_type(jid), {}, ttl=_get_ttl()) - jid_doc = cb_.get(six.text_type(jid)) + cb_.add(str(jid), {}, ttl=_get_ttl()) + jid_doc = cb_.get(str(jid)) jid_doc.value["load"] = clear_load - cb_.replace(six.text_type(jid), jid_doc.value, cas=jid_doc.cas, ttl=_get_ttl()) + cb_.replace(str(jid), jid_doc.value, cas=jid_doc.cas, ttl=_get_ttl()) # if you have a tgt, save that for the UI etc if "tgt" in clear_load and clear_load["tgt"] != "": @@ -253,7 +247,7 @@ def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argume cb_ = _get_connection() try: - jid_doc = cb_.get(six.text_type(jid)) + jid_doc = cb_.get(str(jid)) except couchbase.exceptions.NotFoundError: log.warning("Could not write job cache file for jid: %s", jid) return False @@ -263,7 +257,7 @@ def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argume jid_doc.value["minions"] = sorted(set(jid_doc.value["minions"] + minions)) else: jid_doc.value["minions"] = minions - cb_.replace(six.text_type(jid), jid_doc.value, cas=jid_doc.cas, ttl=_get_ttl()) + cb_.replace(str(jid), jid_doc.value, cas=jid_doc.cas, ttl=_get_ttl()) def get_load(jid): @@ -273,7 +267,7 @@ def get_load(jid): cb_ = _get_connection() try: - jid_doc = cb_.get(six.text_type(jid)) + jid_doc = cb_.get(str(jid)) except couchbase.exceptions.NotFoundError: return {} @@ -297,7 +291,7 @@ def get_jid(jid): ret = {} for result in cb_.query( - DESIGN_NAME, "jid_returns", key=six.text_type(jid), include_docs=True + DESIGN_NAME, "jid_returns", key=str(jid), include_docs=True ): ret[result.value] = result.doc.value diff --git a/salt/returners/couchdb_return.py b/salt/returners/couchdb_return.py index 2f5efd03a41..455278638c7 100644 --- a/salt/returners/couchdb_return.py +++ b/salt/returners/couchdb_return.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Simple returner for CouchDB. Optional configuration settings are listed below, along with sane defaults: @@ -52,28 +51,18 @@ otherwise multi-minion targeting can lead to losing output: * other minions fail with ``{'error': 'HTTP Error 409: Conflict'}`` """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import logging import time +from urllib.error import HTTPError +from urllib.request import HTTPHandler as _HTTPHandler +from urllib.request import Request as _Request +from urllib.request import build_opener as _build_opener import salt.returners - -# Import Salt libs import salt.utils.jid import salt.utils.json -# Import 3rd-party libs -# pylint: disable=no-name-in-module,import-error -from salt.ext.six.moves.urllib.error import HTTPError -from salt.ext.six.moves.urllib.request import HTTPHandler as _HTTPHandler -from salt.ext.six.moves.urllib.request import Request as _Request -from salt.ext.six.moves.urllib.request import build_opener as _build_opener - -# pylint: enable=no-name-in-module,import-error - - log = logging.getLogger(__name__) # Define the module's virtual name @@ -134,7 +123,7 @@ def _request(method, url, content_type=None, _data=None): try: handler = opener.open(request) except HTTPError as exc: - return {"error": "{0}".format(exc)} + return {"error": "{}".format(exc)} return salt.utils.json.loads(handler.read()) diff --git a/salt/returners/django_return.py b/salt/returners/django_return.py index 374c6f7fcf8..a1f15f9ed89 100644 --- a/salt/returners/django_return.py +++ b/salt/returners/django_return.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ A returner that will inform a Django system that returns are available using Django's signal system. @@ -27,7 +26,6 @@ An example Django module that registers a function called """ # Import Python libraries -from __future__ import absolute_import, print_function, unicode_literals import logging diff --git a/salt/returners/etcd_return.py b/salt/returners/etcd_return.py index 9afcd335dcd..99cfa42e828 100644 --- a/salt/returners/etcd_return.py +++ b/salt/returners/etcd_return.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Return data to an etcd server or cluster @@ -64,12 +63,9 @@ create the profiles as specified above. Then add: etcd.returner_read_profile: my_etcd_read etcd.returner_write_profile: my_etcd_write """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import logging -# Import salt libs import salt.utils.jid import salt.utils.json @@ -132,7 +128,7 @@ def save_load(jid, load, minions=None): """ Save the load to the specified jid """ - log.debug("sdstack_etcd returner called jid: {0}".format(jid)) + log.debug("sdstack_etcd returner called jid: {}".format(jid)) write_profile = __opts__.get("etcd.returner_write_profile") client, path = _get_conn(__opts__, write_profile) if write_profile: @@ -160,7 +156,7 @@ def get_load(jid): """ Return the load data that marks a specified jid """ - log.debug("sdstack_etcd returner called jid: {0}".format(jid)) + log.debug("sdstack_etcd returner called jid: {}".format(jid)) read_profile = __opts__.get("etcd.returner_read_profile") client, path = _get_conn(__opts__, read_profile) return salt.utils.json.loads( @@ -172,7 +168,7 @@ def get_jid(jid): """ Return the information returned when the specified job id was executed """ - log.debug("sdstack_etcd returner called jid: {0}".format(jid)) + log.debug("sdstack_etcd returner called jid: {}".format(jid)) ret = {} client, path = _get_conn(__opts__) items = client.get("/".join((path, "jobs", jid))) @@ -189,7 +185,7 @@ def get_fun(fun): """ Return a dict of the last function called for all minions """ - log.debug("sdstack_etcd returner called fun: {0}".format(fun)) + log.debug("sdstack_etcd returner called fun: {}".format(fun)) ret = {} client, path = _get_conn(__opts__) items = client.get("/".join((path, "minions"))) diff --git a/salt/returners/influxdb_return.py b/salt/returners/influxdb_return.py index d010df42197..c332685644e 100644 --- a/salt/returners/influxdb_return.py +++ b/salt/returners/influxdb_return.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Return data to an influxdb server. @@ -50,19 +49,14 @@ To override individual configuration items, append --return_kwargs '{"key:": "va salt '*' test.ping --return influxdb --return_kwargs '{"db": "another-salt"}' """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import logging import requests import salt.returners - -# Import Salt libs import salt.utils.jid from salt.utils.decorators import memoize -# Import third party libs try: import influxdb import influxdb.influxdb08 @@ -114,7 +108,7 @@ def _get_version(host, port, user, password): # check the InfluxDB version via the HTTP API try: result = requests.get( - "http://{0}:{1}/ping".format(host, port), auth=(user, password) + "http://{}:{}/ping".format(host, port), auth=(user, password) ) if influxDBVersionHeader in result.headers: version = result.headers[influxDBVersionHeader] @@ -229,7 +223,7 @@ def get_load(jid): Return the load data that marks a specified jid """ serv = _get_serv(ret=None) - sql = "select load from jids where jid = '{0}'".format(jid) + sql = "select load from jids where jid = '{}'".format(jid) log.debug(">> Now in get_load %s", jid) data = serv.query(sql) @@ -245,7 +239,7 @@ def get_jid(jid): """ serv = _get_serv(ret=None) - sql = "select id, full_ret from returns where jid = '{0}'".format(jid) + sql = "select id, full_ret from returns where jid = '{}'".format(jid) data = serv.query(sql) ret = {} @@ -265,7 +259,7 @@ def get_fun(fun): sql = """select first(id) as fid, first(full_ret) as fret from returns - where fun = '{0}' + where fun = '{}' group by fun, id """.format( fun diff --git a/salt/returners/kafka_return.py b/salt/returners/kafka_return.py index 47ee7342d27..36d20a345dc 100644 --- a/salt/returners/kafka_return.py +++ b/salt/returners/kafka_return.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - """ Return data to a Kafka topic @@ -23,13 +21,11 @@ To use the kafka returner, append `--return kafka` to the Salt command, eg; salt '*' test.ping --return kafka """ -from __future__ import absolute_import, print_function, unicode_literals import logging import salt.utils.json -# Import third-party libs try: from confluent_kafka import Producer diff --git a/salt/returners/librato_return.py b/salt/returners/librato_return.py index 1c19ad255af..a65b99ff68a 100644 --- a/salt/returners/librato_return.py +++ b/salt/returners/librato_return.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Salt returner to return highstate stats to Librato @@ -30,17 +29,12 @@ by adding more tags to the submission. """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import logging import salt.returners - -# Import Salt libs import salt.utils.jid -# Import third party libs try: import librato diff --git a/salt/returners/local.py b/salt/returners/local.py index ab902ec175d..156d38d5be6 100644 --- a/salt/returners/local.py +++ b/salt/returners/local.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ The local returner is used to test the returner interface, it just prints the return data to the console to verify that it is being passed properly @@ -10,9 +9,6 @@ To use the local returner, append '--return local' to the salt command. ex: salt '*' test.ping --return local """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals - def returner(ret): """ diff --git a/salt/returners/local_cache.py b/salt/returners/local_cache.py index 326bad19411..9aca744bbf7 100644 --- a/salt/returners/local_cache.py +++ b/salt/returners/local_cache.py @@ -1,13 +1,9 @@ -# -*- coding: utf-8 -*- """ Return data to local job cache """ -from __future__ import absolute_import, print_function, unicode_literals import bisect - -# Import python libs import errno import glob import logging @@ -16,8 +12,6 @@ import shutil import time import salt.exceptions - -# Import salt libs import salt.payload import salt.utils.atomicfile import salt.utils.files @@ -26,10 +20,6 @@ import salt.utils.minions import salt.utils.msgpack import salt.utils.stringutils -# Import 3rd-party libs -from salt.ext import six -from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin - log = logging.getLogger(__name__) # load is the published job @@ -99,7 +89,7 @@ def prep_jid(nocache=False, passed_jid=None, recurse_count=0): So do what you have to do to make sure that stays the case """ if recurse_count >= 5: - err = "prep_jid could not store a jid after {0} tries.".format(recurse_count) + err = "prep_jid could not store a jid after {} tries.".format(recurse_count) log.error(err) raise salt.exceptions.SaltCacheError(err) if passed_jid is None: # this can be a None or an empty string. @@ -125,7 +115,7 @@ def prep_jid(nocache=False, passed_jid=None, recurse_count=0): if nocache: with salt.utils.files.fopen(os.path.join(jid_dir, "nocache"), "wb+"): pass - except IOError: + except OSError: log.warning("Could not write out jid file for job %s. Retrying.", jid) time.sleep(0.1) return prep_jid( @@ -172,9 +162,7 @@ def returner(load): raise serial.dump( - dict( - (key, load[key]) for key in ["return", "retcode", "success"] if key in load - ), + {key: load[key] for key in ["return", "retcode", "success"] if key in load}, # Use atomic open here to avoid the file being read before it's # completely written to. Refs #1935 salt.utils.atomicfile.atomic_open(os.path.join(hn_dir, RETURN_P), "w+b"), @@ -198,7 +186,7 @@ def save_load(jid, clear_load, minions=None, recurse_count=0): as for salt-ssh) """ if recurse_count >= 5: - err = "save_load could not write job cache file after {0} retries.".format( + err = "save_load could not write job cache file after {} retries.".format( recurse_count ) log.error(err) @@ -222,7 +210,7 @@ def save_load(jid, clear_load, minions=None, recurse_count=0): try: with salt.utils.files.fopen(os.path.join(jid_dir, LOAD_P), "w+b") as wfh: serial.dump(clear_load, wfh) - except IOError as exc: + except OSError as exc: log.warning("Could not write job invocation cache file: %s", exc) time.sleep(0.1) return save_load( @@ -252,7 +240,7 @@ def save_minions(jid, minions, syndic_id=None): log.debug( "Adding minions for job %s%s: %s", jid, - " from syndic master '{0}'".format(syndic_id) if syndic_id else "", + " from syndic master '{}'".format(syndic_id) if syndic_id else "", minions, ) serial = salt.payload.Serial(__opts__) @@ -283,7 +271,7 @@ def save_minions(jid, minions, syndic_id=None): pass with salt.utils.files.fopen(minions_path, "w+b") as wfh: serial.dump(minions, wfh) - except IOError as exc: + except OSError as exc: log.error( "Failed to write minion list %s to job cache file %s: %s", minions, @@ -325,7 +313,7 @@ def get_load(jid): try: with salt.utils.files.fopen(minions_path, "rb") as rfh: all_minions.update(serial.load(rfh)) - except IOError as exc: + except OSError as exc: salt.utils.files.process_read_exception(exc, minions_path) if all_minions: @@ -367,7 +355,7 @@ def get_jid(jid): with salt.utils.files.fopen(outp, "rb") as rfh: ret[fn_]["out"] = serial.load(rfh) except Exception as exc: # pylint: disable=broad-except - if "Permission denied:" in six.text_type(exc): + if "Permission denied:" in str(exc): raise return ret @@ -481,7 +469,7 @@ def update_endtime(jid, time): os.makedirs(jid_dir) with salt.utils.files.fopen(os.path.join(jid_dir, ENDTIME), "w") as etfile: etfile.write(salt.utils.stringutils.to_str(time)) - except IOError as exc: + except OSError as exc: log.warning("Could not write job invocation cache file: %s", exc) diff --git a/salt/returners/mattermost_returner.py b/salt/returners/mattermost_returner.py index f8c309fcbac..26f9fd041bb 100644 --- a/salt/returners/mattermost_returner.py +++ b/salt/returners/mattermost_returner.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Return salt data via mattermost @@ -43,25 +42,13 @@ To override individual configuration items, append --return_kwargs '{'key:': 'va salt '*' test.ping --return mattermost --return_kwargs '{'channel': '#random'}' """ -from __future__ import absolute_import, print_function, unicode_literals -# Import Python libs import logging -# pylint: disable=import-error,no-name-in-module,redefined-builtin -import salt.ext.six.moves.http_client - -# Import Salt Libs import salt.returners import salt.utils.json import salt.utils.mattermost -# Import 3rd-party libs -from salt.ext import six - -# pylint: enable=import-error,no-name-in-module,redefined-builtin - - log = logging.getLogger(__name__) __virtualname__ = "mattermost" @@ -114,11 +101,11 @@ def returner(ret): returns = ret.get("return") message = ( - "id: {0}\r\n" - "function: {1}\r\n" - "function args: {2}\r\n" - "jid: {3}\r\n" - "return: {4}\r\n" + "id: {}\r\n" + "function: {}\r\n" + "function args: {}\r\n" + "jid: {}\r\n" + "return: {}\r\n" ).format( ret.get("id"), ret.get("fun"), ret.get("fun_args"), ret.get("jid"), returns ) @@ -145,9 +132,9 @@ def event_return(events): for event in events: log.debug("Event: %s", event) log.debug("Event data: %s", event["data"]) - message = "tag: {0}\r\n".format(event["tag"]) - for key, value in six.iteritems(event["data"]): - message += "{0}: {1}\r\n".format(key, value) + message = "tag: {}\r\n".format(event["tag"]) + for key, value in event["data"].items(): + message += "{}: {}\r\n".format(key, value) result = post_message(channel, message, username, api_url, hook) if not result: is_ok = False @@ -176,7 +163,7 @@ def post_message(channel, message, username, api_url, hook): result = salt.utils.mattermost.query( api_url=api_url, hook=hook, - data=str("payload={0}").format(salt.utils.json.dumps(parameters)), + data="payload={}".format(salt.utils.json.dumps(parameters)), ) # future lint: disable=blacklisted-function log.debug("result %s", result) diff --git a/salt/returners/memcache_return.py b/salt/returners/memcache_return.py index 159c3291142..a5d80802757 100644 --- a/salt/returners/memcache_return.py +++ b/salt/returners/memcache_return.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Return data to a memcache server @@ -45,19 +44,15 @@ To override individual configuration items, append --return_kwargs '{"key:": "va salt '*' test.ping --return memcache --return_kwargs '{"host": "hostname.domain.com"}' """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import logging import salt.returners import salt.utils.jid import salt.utils.json -from salt.ext import six log = logging.getLogger(__name__) -# Import third party libs try: import memcache @@ -108,7 +103,7 @@ def _get_serv(ret): # Combine host and port to conform syntax of python memcache client memcacheoptions = (host, port) - return memcache.Client(["{0}:{1}".format(*memcacheoptions)], debug=0) + return memcache.Client(["{}:{}".format(*memcacheoptions)], debug=0) # # TODO: make memcacheoptions cluster aware # Servers can be passed in two forms: # 1. Strings of the form C{"host:port"}, which implies a default weight of 1 @@ -126,9 +121,9 @@ def _get_list(serv, key): def _append_list(serv, key, value): if value in _get_list(serv, key): return - r = serv.append(key, "{0},".format(value)) + r = serv.append(key, "{},".format(value)) if not r: - serv.add(key, "{0},".format(value)) + serv.add(key, "{},".format(value)) def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument @@ -147,8 +142,8 @@ def returner(ret): jid = ret["jid"] fun = ret["fun"] rets = salt.utils.json.dumps(ret) - serv.set("{0}:{1}".format(jid, minion), rets) # cache for get_jid - serv.set("{0}:{1}".format(fun, minion), rets) # cache for get_fun + serv.set("{}:{}".format(jid, minion), rets) # cache for get_jid + serv.set("{}:{}".format(fun, minion), rets) # cache for get_fun # The following operations are neither efficient nor atomic. # If there is a way to make them so, this should be updated. @@ -188,10 +183,10 @@ def get_jid(jid): """ serv = _get_serv(ret=None) minions = _get_list(serv, "minions") - returns = serv.get_multi(minions, key_prefix="{0}:".format(jid)) + returns = serv.get_multi(minions, key_prefix="{}:".format(jid)) # returns = {minion: return, minion: return, ...} ret = {} - for minion, data in six.iteritems(returns): + for minion, data in returns.items(): ret[minion] = salt.utils.json.loads(data) return ret @@ -202,10 +197,10 @@ def get_fun(fun): """ serv = _get_serv(ret=None) minions = _get_list(serv, "minions") - returns = serv.get_multi(minions, key_prefix="{0}:".format(fun)) + returns = serv.get_multi(minions, key_prefix="{}:".format(fun)) # returns = {minion: return, minion: return, ...} ret = {} - for minion, data in six.iteritems(returns): + for minion, data in returns.items(): ret[minion] = salt.utils.json.loads(data) return ret @@ -218,7 +213,7 @@ def get_jids(): jids = _get_list(serv, "jids") loads = serv.get_multi(jids) # {jid: load, jid: load, ...} ret = {} - for jid, load in six.iteritems(loads): + for jid, load in loads.items(): ret[jid] = salt.utils.jid.format_jid_instance(jid, salt.utils.json.loads(load)) return ret diff --git a/salt/returners/mongo_future_return.py b/salt/returners/mongo_future_return.py index 05f61df6989..98b565cbced 100644 --- a/salt/returners/mongo_future_return.py +++ b/salt/returners/mongo_future_return.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Return data to a mongodb server @@ -92,19 +91,13 @@ To override individual configuration items, append --return_kwargs '{"key:": "va salt '*' test.ping --return mongo --return_kwargs '{"db": "another-salt"}' """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import logging import salt.returners - -# Import Salt libs import salt.utils.jid -from salt.ext import six from salt.utils.versions import LooseVersion as _LooseVersion -# Import third party libs try: import pymongo @@ -130,7 +123,7 @@ def _remove_dots(src): Remove the dots from the given data structure """ output = {} - for key, val in six.iteritems(src): + for key, val in src.items(): if isinstance(val, dict): val = _remove_dots(val) output[key.replace(".", "-")] = val diff --git a/salt/returners/mongo_return.py b/salt/returners/mongo_return.py index 3a9c3808012..ab879a4967e 100644 --- a/salt/returners/mongo_return.py +++ b/salt/returners/mongo_return.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Return data to a mongodb server @@ -60,19 +59,13 @@ To override individual configuration items, append --return_kwargs '{"key:": "va salt '*' test.ping --return mongo --return_kwargs '{"db": "another-salt"}' """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import logging import salt.returners - -# import Salt libs import salt.utils.jid -from salt.ext import six from salt.utils.versions import LooseVersion as _LooseVersion -# Import third party libs try: import pymongo @@ -100,7 +93,7 @@ def _remove_dots(src): Remove dots from the given data structure """ output = {} - for key, val in six.iteritems(src): + for key, val in src.items(): if isinstance(val, dict): val = _remove_dots(val) output[key.replace(".", "-")] = val diff --git a/salt/returners/multi_returner.py b/salt/returners/multi_returner.py index 29145b209d9..550a6c1e43e 100644 --- a/salt/returners/multi_returner.py +++ b/salt/returners/multi_returner.py @@ -1,15 +1,11 @@ -# -*- coding: utf-8 -*- """ Read/Write multiple returners """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import logging -# Import salt libs import salt.minion log = logging.getLogger(__name__) @@ -46,11 +42,9 @@ def prep_jid(nocache=False, passed_jid=None): jid = passed_jid for returner_ in __opts__[CONFIG_KEY]: if jid is None: - jid = _mminion().returners["{0}.prep_jid".format(returner_)]( - nocache=nocache - ) + jid = _mminion().returners["{}.prep_jid".format(returner_)](nocache=nocache) else: - r_jid = _mminion().returners["{0}.prep_jid".format(returner_)]( + r_jid = _mminion().returners["{}.prep_jid".format(returner_)]( nocache=nocache ) if r_jid != jid: @@ -63,7 +57,7 @@ def returner(load): Write return to all returners in multi_returner """ for returner_ in __opts__[CONFIG_KEY]: - _mminion().returners["{0}.returner".format(returner_)](load) + _mminion().returners["{}.returner".format(returner_)](load) def save_load(jid, clear_load, minions=None): @@ -71,7 +65,7 @@ def save_load(jid, clear_load, minions=None): Write load to all returners in multi_returner """ for returner_ in __opts__[CONFIG_KEY]: - _mminion().returners["{0}.save_load".format(returner_)](jid, clear_load) + _mminion().returners["{}.save_load".format(returner_)](jid, clear_load) def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument @@ -86,7 +80,7 @@ def get_load(jid): """ ret = {} for returner_ in __opts__[CONFIG_KEY]: - ret.update(_mminion().returners["{0}.get_load".format(returner_)](jid)) + ret.update(_mminion().returners["{}.get_load".format(returner_)](jid)) return ret @@ -97,7 +91,7 @@ def get_jid(jid): """ ret = {} for returner_ in __opts__[CONFIG_KEY]: - ret.update(_mminion().returners["{0}.get_jid".format(returner_)](jid)) + ret.update(_mminion().returners["{}.get_jid".format(returner_)](jid)) return ret @@ -108,7 +102,7 @@ def get_jids(): """ ret = {} for returner_ in __opts__[CONFIG_KEY]: - ret.update(_mminion().returners["{0}.get_jids".format(returner_)]()) + ret.update(_mminion().returners["{}.get_jids".format(returner_)]()) return ret @@ -118,6 +112,6 @@ def clean_old_jobs(): Clean out the old jobs from all returners (if you have it) """ for returner_ in __opts__[CONFIG_KEY]: - fstr = "{0}.clean_old_jobs".format(returner_) + fstr = "{}.clean_old_jobs".format(returner_) if fstr in _mminion().returners: _mminion().returners[fstr]() diff --git a/salt/returners/mysql.py b/salt/returners/mysql.py index b7bb05164fb..118006aa88a 100644 --- a/salt/returners/mysql.py +++ b/salt/returners/mysql.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Return data to a mysql server @@ -138,24 +137,16 @@ To override individual configuration items, append --return_kwargs '{"key:": "va salt '*' test.ping --return mysql --return_kwargs '{"db": "another-salt"}' """ -from __future__ import absolute_import, print_function, unicode_literals import logging import sys - -# Import python libs from contextlib import contextmanager import salt.exceptions - -# Import salt libs import salt.returners import salt.utils.jid import salt.utils.json -# Import 3rd-party libs -from salt.ext import six - # Let's not allow PyLint complain about string substitution # pylint: disable=W1321,E1321 @@ -227,8 +218,8 @@ def _get_options(ret=None): defaults=defaults, ) # post processing - for k, v in six.iteritems(_options): - if isinstance(v, six.string_types) and v.lower() == "none": + for k, v in _options.items(): + if isinstance(v, str) and v.lower() == "none": # Ensure 'None' is rendered as None _options[k] = None if k == "port": @@ -291,9 +282,9 @@ def _get_serv(ret=None, commit=False): yield cursor except MySQLdb.DatabaseError as err: error = err.args - sys.stderr.write(six.text_type(error)) + sys.stderr.write(str(error)) cursor.execute("ROLLBACK") - six.reraise(*sys.exc_info()) + raise else: if commit: cursor.execute("COMMIT") @@ -515,8 +506,8 @@ def _purge_jobs(timestamp): log.error( "mysql returner archiver was unable to delete contents of table 'jids'" ) - log.error(six.text_type(e)) - raise salt.exceptions.SaltRunnerError(six.text_type(e)) + log.error(str(e)) + raise salt.exceptions.SaltRunnerError(str(e)) try: sql = "delete from `salt_returns` where alter_time < %s" @@ -526,8 +517,8 @@ def _purge_jobs(timestamp): log.error( "mysql returner archiver was unable to delete contents of table 'salt_returns'" ) - log.error(six.text_type(e)) - raise salt.exceptions.SaltRunnerError(six.text_type(e)) + log.error(str(e)) + raise salt.exceptions.SaltRunnerError(str(e)) try: sql = "delete from `salt_events` where alter_time < %s" @@ -537,8 +528,8 @@ def _purge_jobs(timestamp): log.error( "mysql returner archiver was unable to delete contents of table 'salt_events'" ) - log.error(six.text_type(e)) - raise salt.exceptions.SaltRunnerError(six.text_type(e)) + log.error(str(e)) + raise salt.exceptions.SaltRunnerError(str(e)) return True @@ -556,7 +547,7 @@ def _archive_jobs(timestamp): for table_name in source_tables: try: tmp_table_name = table_name + "_archive" - sql = "create table if not exists {0} like {1}".format( + sql = "create table if not exists {} like {}".format( tmp_table_name, table_name ) cur.execute(sql) @@ -566,11 +557,11 @@ def _archive_jobs(timestamp): log.error( "mysql returner archiver was unable to create the archive tables." ) - log.error(six.text_type(e)) - raise salt.exceptions.SaltRunnerError(six.text_type(e)) + log.error(str(e)) + raise salt.exceptions.SaltRunnerError(str(e)) try: - sql = "insert into `{0}` select * from `{1}` where jid in (select distinct jid from salt_returns where alter_time < %s)".format( + sql = "insert into `{}` select * from `{}` where jid in (select distinct jid from salt_returns where alter_time < %s)".format( target_tables["jids"], "jids" ) cur.execute(sql, (timestamp,)) @@ -579,14 +570,14 @@ def _archive_jobs(timestamp): log.error( "mysql returner archiver was unable to copy contents of table 'jids'" ) - log.error(six.text_type(e)) - raise salt.exceptions.SaltRunnerError(six.text_type(e)) + log.error(str(e)) + raise salt.exceptions.SaltRunnerError(str(e)) except Exception as e: # pylint: disable=broad-except log.error(e) raise try: - sql = "insert into `{0}` select * from `{1}` where alter_time < %s".format( + sql = "insert into `{}` select * from `{}` where alter_time < %s".format( target_tables["salt_returns"], "salt_returns" ) cur.execute(sql, (timestamp,)) @@ -595,11 +586,11 @@ def _archive_jobs(timestamp): log.error( "mysql returner archiver was unable to copy contents of table 'salt_returns'" ) - log.error(six.text_type(e)) - raise salt.exceptions.SaltRunnerError(six.text_type(e)) + log.error(str(e)) + raise salt.exceptions.SaltRunnerError(str(e)) try: - sql = "insert into `{0}` select * from `{1}` where alter_time < %s".format( + sql = "insert into `{}` select * from `{}` where alter_time < %s".format( target_tables["salt_events"], "salt_events" ) cur.execute(sql, (timestamp,)) @@ -608,8 +599,8 @@ def _archive_jobs(timestamp): log.error( "mysql returner archiver was unable to copy contents of table 'salt_events'" ) - log.error(six.text_type(e)) - raise salt.exceptions.SaltRunnerError(six.text_type(e)) + log.error(str(e)) + raise salt.exceptions.SaltRunnerError(str(e)) return _purge_jobs(timestamp) @@ -623,7 +614,7 @@ def clean_old_jobs(): if __opts__.get("keep_jobs", False) and int(__opts__.get("keep_jobs", 0)) > 0: try: with _get_serv() as cur: - sql = "select date_sub(now(), interval {0} hour) as stamp;".format( + sql = "select date_sub(now(), interval {} hour) as stamp;".format( __opts__["keep_jobs"] ) cur.execute(sql) @@ -638,5 +629,5 @@ def clean_old_jobs(): log.error( "Mysql returner was unable to get timestamp for purge/archive of jobs" ) - log.error(six.text_type(e)) - raise salt.exceptions.SaltRunnerError(six.text_type(e)) + log.error(str(e)) + raise salt.exceptions.SaltRunnerError(str(e)) diff --git a/salt/returners/nagios_nrdp_return.py b/salt/returners/nagios_nrdp_return.py index dc42c163ca9..63125dcbb8f 100644 --- a/salt/returners/nagios_nrdp_return.py +++ b/salt/returners/nagios_nrdp_return.py @@ -48,7 +48,6 @@ To override individual configuration items, append --return_kwargs '{"key:": "va """ -# Import python libs import html import http.client import logging diff --git a/salt/returners/odbc.py b/salt/returners/odbc.py index 072f574bf68..f7393876739 100644 --- a/salt/returners/odbc.py +++ b/salt/returners/odbc.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Return data to an ODBC compliant server. This driver was developed with Microsoft SQL Server in mind, but theoretically @@ -123,17 +122,12 @@ To override individual configuration items, append --return_kwargs '{"key:": "va salt '*' test.ping --return odbc --return_kwargs '{"dsn": "dsn-name"}' """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import salt.returners - -# Import Salt libs import salt.utils.jid import salt.utils.json # FIXME We'll need to handle this differently for Windows. -# Import third party libs try: import pyodbc @@ -159,7 +153,7 @@ def _get_options(ret=None): attrs = {"dsn": "dsn", "user": "user", "passwd": "passwd"} _options = salt.returners.get_returner_options( - "returner.{0}".format(__virtualname__), + "returner.{}".format(__virtualname__), ret, attrs, __salt__=__salt__, @@ -177,7 +171,7 @@ def _get_conn(ret=None): user = _options.get("user") passwd = _options.get("passwd") - return pyodbc.connect("DSN={0};UID={1};PWD={2}".format(dsn, user, passwd)) + return pyodbc.connect("DSN={};UID={};PWD={}".format(dsn, user, passwd)) def _close_conn(conn): diff --git a/salt/returners/pgjsonb.py b/salt/returners/pgjsonb.py index a56fcfb13b7..f9ff5aec678 100644 --- a/salt/returners/pgjsonb.py +++ b/salt/returners/pgjsonb.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Return data to a PostgreSQL server with json data stored in Pg's jsonb data type @@ -160,27 +159,20 @@ To override individual configuration items, append --return_kwargs '{"key:": "va salt '*' test.ping --return pgjsonb --return_kwargs '{"db": "another-salt"}' """ -from __future__ import absolute_import, print_function, unicode_literals import logging import sys import time - -# Import python libs from contextlib import contextmanager import salt.exceptions - -# Import salt libs import salt.returners import salt.utils.jid -from salt.ext import six # Let's not allow PyLint complain about string substitution # pylint: disable=W1321,E1321 -# Import third party libs try: import psycopg2 import psycopg2.extras @@ -232,7 +224,7 @@ def _get_options(ret=None): } _options = salt.returners.get_returner_options( - "returner.{0}".format(__virtualname__), + "returner.{}".format(__virtualname__), ret, attrs, __salt__=__salt__, @@ -256,7 +248,7 @@ def _get_serv(ret=None, commit=False): # effectively connect w/o SSL. ssl_options = { k: v - for k, v in six.iteritems(_options) + for k, v in _options.items() if k in ["sslmode", "sslcert", "sslkey", "sslrootcert", "sslcrl"] } conn = psycopg2.connect( @@ -286,9 +278,9 @@ def _get_serv(ret=None, commit=False): yield cursor except psycopg2.DatabaseError as err: error = err.args - sys.stderr.write(six.text_type(error)) + sys.stderr.write(str(error)) cursor.execute("ROLLBACK") - six.reraise(*sys.exc_info()) + raise else: if commit: cursor.execute("COMMIT") @@ -476,7 +468,7 @@ def _purge_jobs(timestamp): cursor.execute("COMMIT") except psycopg2.DatabaseError as err: error = err.args - sys.stderr.write(six.text_type(error)) + sys.stderr.write(str(error)) cursor.execute("ROLLBACK") raise err @@ -486,7 +478,7 @@ def _purge_jobs(timestamp): cursor.execute("COMMIT") except psycopg2.DatabaseError as err: error = err.args - sys.stderr.write(six.text_type(error)) + sys.stderr.write(str(error)) cursor.execute("ROLLBACK") raise err @@ -496,7 +488,7 @@ def _purge_jobs(timestamp): cursor.execute("COMMIT") except psycopg2.DatabaseError as err: error = err.args - sys.stderr.write(six.text_type(error)) + sys.stderr.write(str(error)) cursor.execute("ROLLBACK") raise err @@ -516,7 +508,7 @@ def _archive_jobs(timestamp): for table_name in source_tables: try: tmp_table_name = table_name + "_archive" - sql = "create table IF NOT exists {0} (LIKE {1})".format( + sql = "create table IF NOT exists {} (LIKE {})".format( tmp_table_name, table_name ) cursor.execute(sql) @@ -524,19 +516,19 @@ def _archive_jobs(timestamp): target_tables[table_name] = tmp_table_name except psycopg2.DatabaseError as err: error = err.args - sys.stderr.write(six.text_type(error)) + sys.stderr.write(str(error)) cursor.execute("ROLLBACK") raise err try: - sql = "insert into {0} select * from {1} where jid in (select distinct jid from salt_returns where alter_time < %s)".format( + sql = "insert into {} select * from {} where jid in (select distinct jid from salt_returns where alter_time < %s)".format( target_tables["jids"], "jids" ) cursor.execute(sql, (timestamp,)) cursor.execute("COMMIT") except psycopg2.DatabaseError as err: error = err.args - sys.stderr.write(six.text_type(error)) + sys.stderr.write(str(error)) cursor.execute("ROLLBACK") raise err except Exception as e: # pylint: disable=broad-except @@ -544,26 +536,26 @@ def _archive_jobs(timestamp): raise try: - sql = "insert into {0} select * from {1} where alter_time < %s".format( + sql = "insert into {} select * from {} where alter_time < %s".format( target_tables["salt_returns"], "salt_returns" ) cursor.execute(sql, (timestamp,)) cursor.execute("COMMIT") except psycopg2.DatabaseError as err: error = err.args - sys.stderr.write(six.text_type(error)) + sys.stderr.write(str(error)) cursor.execute("ROLLBACK") raise err try: - sql = "insert into {0} select * from {1} where alter_time < %s".format( + sql = "insert into {} select * from {} where alter_time < %s".format( target_tables["salt_events"], "salt_events" ) cursor.execute(sql, (timestamp,)) cursor.execute("COMMIT") except psycopg2.DatabaseError as err: error = err.args - sys.stderr.write(six.text_type(error)) + sys.stderr.write(str(error)) cursor.execute("ROLLBACK") raise err @@ -579,7 +571,7 @@ def clean_old_jobs(): if __opts__.get("keep_jobs", False) and int(__opts__.get("keep_jobs", 0)) > 0: try: with _get_serv() as cur: - sql = "select (NOW() - interval '{0}' hour) as stamp;".format( + sql = "select (NOW() - interval '{}' hour) as stamp;".format( __opts__["keep_jobs"] ) cur.execute(sql) diff --git a/salt/returners/postgres.py b/salt/returners/postgres.py index 5c3cffb685b..d441cab1f6a 100644 --- a/salt/returners/postgres.py +++ b/salt/returners/postgres.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Return data to a postgresql server @@ -126,24 +125,16 @@ To override individual configuration items, append --return_kwargs '{"key:": "va salt '*' test.ping --return postgres --return_kwargs '{"db": "another-salt"}' """ -from __future__ import absolute_import, print_function, unicode_literals import logging - -# Import python libs import sys from contextlib import contextmanager import salt.exceptions import salt.returners - -# Import Salt libs import salt.utils.jid import salt.utils.json -# Import third party libs -from salt.ext import six - try: import psycopg2 @@ -183,7 +174,7 @@ def _get_options(ret=None): } _options = salt.returners.get_returner_options( - "returner.{0}".format(__virtualname__), + "returner.{}".format(__virtualname__), ret, attrs, __salt__=__salt__, @@ -222,9 +213,9 @@ def _get_serv(ret=None, commit=False): yield cursor except psycopg2.DatabaseError as err: error = err.args - sys.stderr.write(six.text_type(error)) + sys.stderr.write(str(error)) cursor.execute("ROLLBACK") - six.reraise(*sys.exc_info()) + raise else: if commit: cursor.execute("COMMIT") diff --git a/salt/returners/postgres_local_cache.py b/salt/returners/postgres_local_cache.py index 4ce82120ea1..7e1a5c0e8b5 100644 --- a/salt/returners/postgres_local_cache.py +++ b/salt/returners/postgres_local_cache.py @@ -113,7 +113,6 @@ import sys import salt.utils.jid import salt.utils.json -import salt.utils.stringutils try: import psycopg2 @@ -232,8 +231,7 @@ def returner(load): sql = """INSERT INTO salt_returns (fun, jid, return, id, success) VALUES (%s, %s, %s, %s, %s)""" - ret = str(load["return"]) - job_ret = {"return": ret} + job_ret = {"return": str(str(load["return"]), "utf-8", "replace")} if "retcode" in load: job_ret["retcode"] = load["retcode"] if "success" in load: diff --git a/salt/returners/pushover_returner.py b/salt/returners/pushover_returner.py index 17bd091513f..fe76f52e1c7 100644 --- a/salt/returners/pushover_returner.py +++ b/salt/returners/pushover_returner.py @@ -81,17 +81,12 @@ To override individual configuration items, append --return_kwargs '{"key:": "va import logging import pprint +import urllib.parse import salt.returners import salt.utils.pushover from salt.exceptions import SaltInvocationError -# pylint: disable=import-error,no-name-in-module,redefined-builtin -from salt.ext.six.moves.urllib.parse import urlencode as _urlencode - -# pylint: enable=import-error,no-name-in-module,redefined-builtin - - log = logging.getLogger(__name__) __virtualname__ = "pushover" @@ -200,7 +195,7 @@ def _post_message( function="message", method="POST", header_dict={"Content-Type": "application/x-www-form-urlencoded"}, - data=_urlencode(parameters), + data=urllib.parse.urlencode(parameters), opts=__opts__, ) diff --git a/salt/returners/rawfile_json.py b/salt/returners/rawfile_json.py index 990befe1ded..b6181a95944 100644 --- a/salt/returners/rawfile_json.py +++ b/salt/returners/rawfile_json.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Take data from salt and "return" it into a raw file containing the json, with one line per event. @@ -17,8 +16,6 @@ noise, so you may wish to configure batch processing and/or configure the to restrict the events that are written. """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals, with_statement import logging @@ -62,7 +59,7 @@ def returner(ret): try: with salt.utils.files.flopen(opts["filename"], "a") as logfile: salt.utils.json.dump(ret, logfile) - logfile.write(str("\n")) # future lint: disable=blacklisted-function + logfile.write("\n") # future lint: disable=blacklisted-function except Exception: # pylint: disable=broad-except log.error("Could not write to rawdata_json file %s", opts["filename"]) raise @@ -81,7 +78,7 @@ def event_return(events): with salt.utils.files.flopen(opts["filename"], "a") as logfile: for event in events: salt.utils.json.dump(event, logfile) - logfile.write(str("\n")) # future lint: disable=blacklisted-function + logfile.write("\n") # future lint: disable=blacklisted-function except Exception: # pylint: disable=broad-except log.error("Could not write to rawdata_json file %s", opts["filename"]) raise diff --git a/salt/returners/sentry_return.py b/salt/returners/sentry_return.py index 759db264fa9..e61f9eaf643 100644 --- a/salt/returners/sentry_return.py +++ b/salt/returners/sentry_return.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Salt returner that reports execution results back to sentry. The returner will inspect the payload to identify errors and flag them as such. @@ -41,14 +40,10 @@ tags, allowing tagging of events in the sentry ui. To report only errors to sentry, set report_errors_only: true. """ -from __future__ import absolute_import, print_function, unicode_literals -# Import Python libs import logging -# Import Salt libs import salt.utils.jid -from salt.ext import six try: from raven import Client @@ -93,7 +88,7 @@ def _ret_is_not_error(result): is_staterun = all("-" in key for key in result_dict.keys()) if is_staterun: failed_states = {} - for state_id, state_result in six.iteritems(result_dict): + for state_id, state_result in result_dict.items(): if not state_result["result"]: failed_states[state_id] = state_result @@ -111,9 +106,7 @@ def _ret_is_not_error(result): def _get_message(ret): if not ret.get("fun_args"): return "salt func: {}".format(ret["fun"]) - arg_string = " ".join( - [arg for arg in ret["fun_args"] if isinstance(arg, six.string_types)] - ) + arg_string = " ".join([arg for arg in ret["fun_args"] if isinstance(arg, str)]) kwarg_string = "" if isinstance(ret["fun_args"], list) and len(ret["fun_args"]) > 0: kwargs = ret["fun_args"][-1] diff --git a/salt/returners/slack_webhook_return.py b/salt/returners/slack_webhook_return.py index 65f9e042449..aa14df6df24 100644 --- a/salt/returners/slack_webhook_return.py +++ b/salt/returners/slack_webhook_return.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Return salt data via Slack using Incoming Webhooks @@ -56,27 +55,14 @@ append '--return_config alternative' to the salt command. salt '*' test.ping --return slack_webhook --return_config alternative """ -from __future__ import absolute_import, print_function, unicode_literals import json - -# Import Python libs import logging +import urllib.parse -# pylint: disable=import-error,no-name-in-module,redefined-builtin -import salt.ext.six.moves.http_client - -# Import Salt Libs import salt.returners import salt.utils.http import salt.utils.yaml -from salt.ext import six -from salt.ext.six.moves import map, range -from salt.ext.six.moves.urllib.parse import urlencode as _urlencode -from salt.ext.six.moves.urllib.parse import urljoin as _urljoin - -# pylint: enable=import-error,no-name-in-module,redefined-builtin - log = logging.getLogger(__name__) @@ -142,7 +128,7 @@ def _sprinkle(config_str): """ parts = [x for sub in config_str.split("{") for x in sub.split("}")] for i in range(1, len(parts), 2): - parts[i] = six.text_type(__grains__.get(parts[i], "")) + parts[i] = str(__grains__.get(parts[i], "")) return "".join(parts) @@ -345,9 +331,9 @@ def _post_message(webhook, author_icon, title, report): payload = _generate_payload(author_icon, title, report) - data = _urlencode({"payload": json.dumps(payload, ensure_ascii=False)}) + data = urllib.parse.urlencode({"payload": json.dumps(payload, ensure_ascii=False)}) - webhook_url = _urljoin("https://hooks.slack.com/services/", webhook) + webhook_url = urllib.parse.urljoin("https://hooks.slack.com/services/", webhook) query_result = salt.utils.http.query(webhook_url, "POST", data=data) # Sometimes the status is not available, so status 200 is assumed when it is not present diff --git a/salt/returners/sms_return.py b/salt/returners/sms_return.py index 55ddf0638e4..cafe9d06d76 100644 --- a/salt/returners/sms_return.py +++ b/salt/returners/sms_return.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - """ Return data by SMS. @@ -28,7 +26,6 @@ To use the sms returner, append '--return sms' to the salt command. salt '*' test.ping --return sms """ -from __future__ import absolute_import, print_function, unicode_literals import logging @@ -89,7 +86,7 @@ def returner(ret): try: message = client.messages.create( - body="Minion: {0}\nCmd: {1}\nSuccess: {2}\n\nJid: {3}".format( + body="Minion: {}\nCmd: {}\nSuccess: {}\n\nJid: {}".format( ret["id"], ret["fun"], ret["success"], ret["jid"] ), to=receiver, diff --git a/salt/returners/smtp_return.py b/salt/returners/smtp_return.py index 2574572a4a0..7e366956902 100644 --- a/salt/returners/smtp_return.py +++ b/salt/returners/smtp_return.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Return salt data via email @@ -105,9 +104,8 @@ Also you need to create additional file ``/srv/salt/templates/email.j2`` with em This configuration enables Salt Master to send an email when accepting or rejecting minions keys. """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals +import io import logging import os import smtplib @@ -116,9 +114,6 @@ from email.utils import formatdate import salt.loader import salt.returners import salt.utils.jid - -# Import Salt libs -from salt.ext import six from salt.template import compile_template try: @@ -191,11 +186,11 @@ def returner(ret): for field in fields: if field in ret: - subject += " {0}".format(ret[field]) + subject += " {}".format(ret[field]) subject = compile_template( ":string:", rend, renderer, blacklist, whitelist, input_data=subject, **ret ) - if isinstance(subject, six.moves.StringIO): + if isinstance(subject, io.StringIO): subject = subject.read() log.debug("smtp_return: Subject is '%s'", subject) @@ -219,29 +214,29 @@ def returner(ret): if gpgowner: if HAS_GNUPG: gpg = gnupg.GPG( - gnupghome=os.path.expanduser("~{0}/.gnupg".format(gpgowner)), + gnupghome=os.path.expanduser("~{}/.gnupg".format(gpgowner)), options=["--trust-model always"], ) encrypted_data = gpg.encrypt(content, to_addrs) if encrypted_data.ok: log.debug("smtp_return: Encryption successful") - content = six.text_type(encrypted_data) + content = str(encrypted_data) else: log.error( "smtp_return: Encryption failed, only an error message will be sent" ) - content = "Encryption failed, the return data was not sent.\r\n\r\n{0}\r\n{1}".format( + content = "Encryption failed, the return data was not sent.\r\n\r\n{}\r\n{}".format( encrypted_data.status, encrypted_data.stderr ) else: log.error( "gnupg python module is required in order to user gpgowner in smtp returner ; ignoring gpgowner configuration for now" ) - if isinstance(content, six.moves.StringIO): + if isinstance(content, io.StringIO): content = content.read() message = ( - "From: {0}\r\n" "To: {1}\r\n" "Date: {2}\r\n" "Subject: {3}\r\n" "\r\n" "{4}" + "From: {}\r\n" "To: {}\r\n" "Date: {}\r\n" "Subject: {}\r\n" "\r\n" "{}" ).format( from_addr, ", ".join(to_addrs), formatdate(localtime=True), subject, content ) diff --git a/salt/returners/sqlite3_return.py b/salt/returners/sqlite3_return.py index dc9cec27851..f76de25e4d8 100644 --- a/salt/returners/sqlite3_return.py +++ b/salt/returners/sqlite3_return.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Insert minion return data into a sqlite3 database @@ -80,22 +79,14 @@ To override individual configuration items, append --return_kwargs '{"key:": "va salt '*' test.ping --return sqlite3 --return_kwargs '{"db": "/var/lib/salt/another-salt.db"}' """ -from __future__ import absolute_import, print_function, unicode_literals import datetime - -# Import python libs import logging import salt.returners - -# Import Salt libs import salt.utils.jid import salt.utils.json -# Import 3rd-party libs -from salt.ext import six - # Better safe than sorry here. Even though sqlite3 is included in python try: import sqlite3 @@ -172,8 +163,8 @@ def returner(ret): "fun": ret["fun"], "jid": ret["jid"], "id": ret["id"], - "fun_args": six.text_type(ret["fun_args"]) if ret.get("fun_args") else None, - "date": six.text_type(datetime.datetime.now()), + "fun_args": str(ret["fun_args"]) if ret.get("fun_args") else None, + "date": str(datetime.datetime.now()), "full_ret": salt.utils.json.dumps(ret["return"]), "success": ret.get("success", ""), }, @@ -228,7 +219,7 @@ def get_jid(jid): log.debug("query result: %s", data) ret = {} if data and len(data) > 1: - ret = {six.text_type(data[0]): {"return": salt.utils.json.loads(data[1])}} + ret = {str(data[0]): {"return": salt.utils.json.loads(data[1])}} log.debug("ret: %s", ret) _close_conn(conn) return ret diff --git a/salt/returners/syslog_return.py b/salt/returners/syslog_return.py index d994ee4166e..e8db27bd400 100644 --- a/salt/returners/syslog_return.py +++ b/salt/returners/syslog_return.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Return data to the host operating system's syslog facility @@ -86,18 +85,13 @@ To override individual configuration items, append implmentation's documentation to determine how to adjust this limit. """ -from __future__ import absolute_import, print_function, unicode_literals import logging import salt.returners - -# Import Salt libs import salt.utils.jid import salt.utils.json -from salt.ext import six -# Import python libs try: import syslog @@ -158,7 +152,7 @@ def _verify_options(options): # Sanity check tag if "tag" in options: - if not isinstance(options["tag"], six.string_types): + if not isinstance(options["tag"], str): log.error("tag must be a string") return False if len(options["tag"]) > 32: diff --git a/salt/returners/telegram_return.py b/salt/returners/telegram_return.py index d6055b775f2..5414ca3d940 100644 --- a/salt/returners/telegram_return.py +++ b/salt/returners/telegram_return.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Return salt data via Telegram. @@ -22,12 +21,9 @@ To use the Telegram return, append '--return telegram' to the salt command. salt '*' test.ping --return telegram """ -from __future__ import absolute_import, print_function, unicode_literals -# Import Python libs import logging -# Import Salt Libs import salt.returners log = logging.getLogger(__name__) @@ -81,11 +77,11 @@ def returner(ret): returns = ret.get("return") message = ( - "id: {0}\r\n" - "function: {1}\r\n" - "function args: {2}\r\n" - "jid: {3}\r\n" - "return: {4}\r\n" + "id: {}\r\n" + "function: {}\r\n" + "function args: {}\r\n" + "jid: {}\r\n" + "return: {}\r\n" ).format( ret.get("id"), ret.get("fun"), ret.get("fun_args"), ret.get("jid"), returns ) diff --git a/salt/returners/xmpp_return.py b/salt/returners/xmpp_return.py index 672819de08f..2b779e0934a 100644 --- a/salt/returners/xmpp_return.py +++ b/salt/returners/xmpp_return.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Return salt data via xmpp @@ -67,13 +66,10 @@ To override individual configuration items, append --return_kwargs '{"key:": "va salt '*' test.ping --return xmpp --return_kwargs '{"recipient": "someone-else@xmpp.example.com"}' """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import logging import pprint -# Import salt libs import salt.returners from salt.utils.versions import LooseVersion as _LooseVersion @@ -84,7 +80,7 @@ try: HAS_LIBS = True except ImportError: - class _ClientXMPP(object): + class _ClientXMPP: """ Fake class in order not to raise errors """ @@ -138,7 +134,7 @@ def __virtual__(): return ( False, "Could not import xmpp returner; sleekxmpp python client is not " - "installed or is older than version '{0}'.".format(min_version), + "installed or is older than version '{}'.".format(min_version), ) @@ -146,7 +142,7 @@ class SendMsgBot(_ClientXMPP): def __init__(self, jid, password, recipient, msg): # PyLint wrongly reports an error when calling super, hence the above # disable call - super(SendMsgBot, self).__init__(jid, password) + super().__init__(jid, password) self.recipient = recipient self.msg = msg @@ -185,11 +181,11 @@ def returner(ret): return message = ( - "id: {0}\r\n" - "function: {1}\r\n" - "function args: {2}\r\n" - "jid: {3}\r\n" - "return: {4}\r\n" + "id: {}\r\n" + "function: {}\r\n" + "function args: {}\r\n" + "jid: {}\r\n" + "return: {}\r\n" ).format( ret.get("id"), ret.get("fun"), diff --git a/salt/returners/zabbix_return.py b/salt/returners/zabbix_return.py index 0936b53f546..ce751c50b7d 100644 --- a/salt/returners/zabbix_return.py +++ b/salt/returners/zabbix_return.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Return salt data to Zabbix @@ -17,14 +16,9 @@ To use the Zabbix returner, append '--return zabbix' to the salt command. ex: salt '*' test.ping --return zabbix """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import os -# Import Salt libs -from salt.ext import six - # Define the module's virtual name __virtualname__ = "zabbix" @@ -78,12 +72,12 @@ def returner(ret): job_minion_id = ret["id"] if type(ret["return"]) is dict: - for state, item in six.iteritems(ret["return"]): + for state, item in ret["return"].items(): if "comment" in item and "name" in item and item["result"] is False: errors = True zabbix_send( "salt.trap.high", - "SALT:\nname: {0}\ncomment: {1}".format( + "SALT:\nname: {}\ncomment: {}".format( item["name"], item["comment"] ), ) @@ -91,10 +85,10 @@ def returner(ret): changes = True zabbix_send( "salt.trap.warning", - "SALT:\nname: {0}\ncomment: {1}".format( + "SALT:\nname: {}\ncomment: {}".format( item["name"], item["comment"] ), ) if not changes and not errors: - zabbix_send("salt.trap.info", "SALT {0} OK".format(job_minion_id)) + zabbix_send("salt.trap.info", "SALT {} OK".format(job_minion_id)) diff --git a/salt/roster/ansible.py b/salt/roster/ansible.py index f17316bdd7f..7beaaf20757 100644 --- a/salt/roster/ansible.py +++ b/salt/roster/ansible.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Read in an Ansible inventory file or script @@ -87,13 +86,10 @@ This is the format that an inventory script needs to output to work with ansible Any of the [groups] or direct hostnames will return. The 'all' is special, and returns everything. """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import copy import fnmatch -# Import Salt libs import salt.utils.path from salt.roster import get_roster_file @@ -122,7 +118,7 @@ def targets(tgt, tgt_type="glob", **kwargs): Default: /etc/salt/roster """ inventory = __runner__["salt.cmd"]( - "cmd.run", "ansible-inventory -i {0} --list".format(get_roster_file(__opts__)) + "cmd.run", "ansible-inventory -i {} --list".format(get_roster_file(__opts__)) ) __context__["inventory"] = __utils__["json.loads"]( __utils__["stringutils.to_str"](inventory) diff --git a/salt/roster/cloud.py b/salt/roster/cloud.py index 9b92433632d..7b9305fbd0c 100644 --- a/salt/roster/cloud.py +++ b/salt/roster/cloud.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Use the cloud cache on the master to derive IPv4 addresses based on minion ID. @@ -18,19 +17,14 @@ usually located at /etc/salt/cloud. For example, add the following: sudo: True """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import copy import os import salt.config - -# Import Salt libs import salt.loader import salt.utils.cloud import salt.utils.validate.net -from salt.ext.six import string_types def targets(tgt, tgt_type="glob", **kwargs): # pylint: disable=W0613 @@ -60,7 +54,7 @@ def targets(tgt, tgt_type="glob", **kwargs): # pylint: disable=W0613 for item in (public_ips, private_ips): if isinstance(item, list): ip_list = ip_list + item - elif isinstance(item, string_types): + elif isinstance(item, str): ip_list.append(item) roster_order = __opts__.get("roster_order", ("public", "private", "local")) @@ -70,7 +64,7 @@ def targets(tgt, tgt_type="glob", **kwargs): # pylint: disable=W0613 ret[minion_id].update({"host": preferred_ip}) ssh_username = salt.utils.cloud.ssh_usernames(vm_, cloud_opts) - if isinstance(ssh_username, string_types): + if isinstance(ssh_username, str): ret[minion_id]["user"] = ssh_username elif isinstance(ssh_username, list): if ssh_username[0] != "root": diff --git a/salt/roster/clustershell.py b/salt/roster/clustershell.py index c319ca2b4ce..1d07bf4adc4 100644 --- a/salt/roster/clustershell.py +++ b/salt/roster/clustershell.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ This roster resolves hostname in a pdsh/clustershell style. @@ -12,15 +11,10 @@ When you want to use host globs for target matching, use ``--roster clustershell """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import copy import socket -from salt.ext import six -from salt.ext.six.moves import map # pylint: disable=import-error,redefined-builtin - REQ_ERROR = None try: from ClusterShell.NodeSet import NodeSet @@ -40,13 +34,13 @@ def targets(tgt, tgt_type="glob", **kwargs): ports = __opts__["ssh_scan_ports"] if not isinstance(ports, list): # Comma-separate list of integers - ports = list(map(int, six.text_type(ports).split(","))) + ports = list(map(int, str(ports).split(","))) hosts = list(NodeSet(tgt)) - host_addrs = dict([(h, socket.gethostbyname(h)) for h in hosts]) + host_addrs = {h: socket.gethostbyname(h) for h in hosts} for host, addr in host_addrs.items(): - addr = six.text_type(addr) + addr = str(addr) ret[host] = copy.deepcopy(__opts__.get("roster_defaults", {})) for port in ports: try: @@ -56,6 +50,6 @@ def targets(tgt, tgt_type="glob", **kwargs): sock.shutdown(socket.SHUT_RDWR) sock.close() ret[host].update({"host": addr, "port": port}) - except socket.error: + except OSError: pass return ret diff --git a/salt/roster/flat.py b/salt/roster/flat.py index 85cc49d9dda..440b0e0073a 100644 --- a/salt/roster/flat.py +++ b/salt/roster/flat.py @@ -1,16 +1,11 @@ -# -*- coding: utf-8 -*- """ Read in the roster from a flat file using the renderer system """ -from __future__ import absolute_import, print_function, unicode_literals import logging import salt.config - -# Import Salt libs import salt.loader -from salt.ext import six from salt.roster import get_roster_file from salt.template import compile_template @@ -36,5 +31,5 @@ def targets(tgt, tgt_type="glob", **kwargs): ) conditioned_raw = {} for minion in raw: - conditioned_raw[six.text_type(minion)] = salt.config.apply_sdb(raw[minion]) + conditioned_raw[str(minion)] = salt.config.apply_sdb(raw[minion]) return __utils__["roster_matcher.targets"](conditioned_raw, tgt, tgt_type, "ipv4") diff --git a/salt/roster/range.py b/salt/roster/range.py index af432a76485..3f039dcef42 100644 --- a/salt/roster/range.py +++ b/salt/roster/range.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ This roster resolves targets from a range server. @@ -11,7 +10,6 @@ When you want to use a range query for target matching, use ``--roster range``. salt-ssh --roster range '%%%example.range.cluster' test.ping """ -from __future__ import absolute_import, print_function, unicode_literals import copy import fnmatch diff --git a/salt/roster/scan.py b/salt/roster/scan.py index 2dc008ddaf2..49d64bcabca 100644 --- a/salt/roster/scan.py +++ b/salt/roster/scan.py @@ -8,7 +8,6 @@ import socket import salt.utils.network from salt._compat import ipaddress -from salt.ext.six.moves import map # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) diff --git a/salt/roster/sshconfig.py b/salt/roster/sshconfig.py index 963fab886c7..fef4c06262a 100644 --- a/salt/roster/sshconfig.py +++ b/salt/roster/sshconfig.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Parses roster entries out of Host directives from SSH config @@ -6,20 +5,15 @@ Parses roster entries out of Host directives from SSH config salt-ssh --roster sshconfig '*' -r "echo hi" """ -from __future__ import absolute_import, print_function, unicode_literals import collections import fnmatch import logging - -# Import python libs import os import re -# Import Salt libs import salt.utils.files import salt.utils.stringutils -from salt.ext import six log = logging.getLogger(__name__) @@ -37,9 +31,9 @@ def _get_ssh_config_file(opts): """ ssh_config_file = opts.get("ssh_config_file") if not os.path.isfile(ssh_config_file): - raise IOError("Cannot find SSH config file") + raise OSError("Cannot find SSH config file") if not os.access(ssh_config_file, os.R_OK): - raise IOError("Cannot access SSH config file: {}".format(ssh_config_file)) + raise OSError("Cannot access SSH config file: {}".format(ssh_config_file)) return ssh_config_file @@ -108,7 +102,7 @@ def targets(tgt, tgt_type="glob", **kwargs): return matched -class RosterMatcher(object): +class RosterMatcher: """ Matcher for the roster data structure """ @@ -123,7 +117,7 @@ class RosterMatcher(object): Execute the correct tgt_type routine and return """ try: - return getattr(self, "ret_{0}_minions".format(self.tgt_type))() + return getattr(self, "ret_{}_minions".format(self.tgt_type))() except AttributeError: return {} @@ -143,7 +137,7 @@ class RosterMatcher(object): """ Return the configured ip """ - if isinstance(self.raw[minion], six.string_types): + if isinstance(self.raw[minion], str): return {"host": self.raw[minion]} if isinstance(self.raw[minion], dict): return self.raw[minion] diff --git a/salt/roster/terraform.py b/salt/roster/terraform.py index 4dfdf4d9e98..d3ee3e84d9b 100644 --- a/salt/roster/terraform.py +++ b/salt/roster/terraform.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Dynamic roster from terraform current state =========================================== @@ -54,13 +53,10 @@ examples. .. _Terraform Salt: https://github.com/dmacvicar/terraform-provider-salt """ -# Import Python libs -from __future__ import absolute_import, unicode_literals import logging import os.path -# Import Salt libs import salt.utils.files import salt.utils.json @@ -142,7 +138,7 @@ def _parse_state_file(state_file_path="terraform.tfstate"): for module in modules: resources = module.get("resources", []) - for resource_name, resource in salt.ext.six.iteritems(resources): + for resource_name, resource in resources.items(): roster_entry = None if resource["type"] == "salt_host": roster_entry = _handle_salt_host_resource(resource) diff --git a/salt/runners/asam.py b/salt/runners/asam.py index 8d355f88103..3ff7aef17b7 100644 --- a/salt/runners/asam.py +++ b/salt/runners/asam.py @@ -35,13 +35,15 @@ import logging HAS_LIBS = False try: import requests - from salt.ext.six.moves.html_parser import HTMLParser # pylint: disable=E0611 + import html.parser HAS_LIBS = True - class ASAMHTMLParser(HTMLParser): # fix issue #30477 + # pylint: disable=abstract-method + + class ASAMHTMLParser(html.parser.HTMLParser): # fix issue #30477 def __init__(self): - HTMLParser.__init__(self) + html.parser.HTMLParser.__init__(self) self.data = [] def handle_starttag(self, tag, attrs): @@ -52,6 +54,8 @@ try: return self.data.append(attr[1]) + # pylint: enable=abstract-method + except ImportError: pass diff --git a/salt/runners/auth.py b/salt/runners/auth.py index 901dc47c97b..7485ef55a44 100644 --- a/salt/runners/auth.py +++ b/salt/runners/auth.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Authentication runner for creating, deleting, and managing eauth tokens. @@ -6,12 +5,9 @@ Authentication runner for creating, deleting, and managing eauth tokens. """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import os -# Import Salt libs import salt.auth import salt.exceptions import salt.netapi diff --git a/salt/runners/cloud.py b/salt/runners/cloud.py index 4e21b217677..03dff733eba 100644 --- a/salt/runners/cloud.py +++ b/salt/runners/cloud.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ The Salt Cloud Runner ===================== @@ -6,13 +5,10 @@ The Salt Cloud Runner This runner wraps the functionality of salt cloud making salt cloud routines available to all internal apis via the runner system """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import logging import os -# Import Salt libs import salt.cloud import salt.utils.args from salt.exceptions import SaltCloudConfigError diff --git a/salt/runners/config.py b/salt/runners/config.py index f1994aba536..9790f25a321 100644 --- a/salt/runners/config.py +++ b/salt/runners/config.py @@ -1,9 +1,7 @@ -# -*- coding: utf-8 -*- """ This runner is designed to mirror the execution module config.py, but for master settings """ -from __future__ import absolute_import, print_function, unicode_literals import salt.utils.data import salt.utils.sdb diff --git a/salt/runners/drac.py b/salt/runners/drac.py index 45e3cb56582..f5e9d39ed7d 100644 --- a/salt/runners/drac.py +++ b/salt/runners/drac.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage Dell DRAC from the Master @@ -13,12 +12,9 @@ configuration file. """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import logging -# Import 3rd-party libs try: import paramiko diff --git a/salt/runners/error.py b/salt/runners/error.py index 39ec047dc1c..45d03378660 100644 --- a/salt/runners/error.py +++ b/salt/runners/error.py @@ -1,15 +1,10 @@ -# -*- coding: utf-8 -*- """ Error generator to enable integration testing of salt runner error handling """ -from __future__ import absolute_import, print_function, unicode_literals -# Import salt libs import salt.utils.error -# Import python libs - def error(name=None, message=""): """ diff --git a/salt/runners/event.py b/salt/runners/event.py index 1eacd0b4527..7a97e82dc41 100644 --- a/salt/runners/event.py +++ b/salt/runners/event.py @@ -1,10 +1,8 @@ -# -*- coding: utf-8 -*- """ Module for sending events using the runner system. .. versionadded:: 2016.11.0 """ -from __future__ import absolute_import, print_function, unicode_literals import logging diff --git a/salt/runners/f5.py b/salt/runners/f5.py index 2d9ad4d9f67..bac50c00cd9 100644 --- a/salt/runners/f5.py +++ b/salt/runners/f5.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Runner to provide F5 Load Balancer functionality @@ -17,12 +16,9 @@ Runner to provide F5 Load Balancer functionality username: admin password: secret """ -from __future__ import absolute_import, print_function, unicode_literals -# Import salt libs from salt.exceptions import CommandExecutionError -# Import third party libs try: import pycontrol.pycontrol as f5 @@ -37,7 +33,7 @@ def __virtual__(): return True -class F5Mgmt(object): +class F5Mgmt: def __init__(self, lb, username, password): self.lb = lb self.username = username @@ -57,7 +53,7 @@ class F5Mgmt(object): wsdls=["LocalLB.VirtualServer", "LocalLB.Pool"], ) except Exception: # pylint: disable=broad-except - raise Exception("Unable to connect to {0}".format(self.lb)) + raise Exception("Unable to connect to {}".format(self.lb)) return True @@ -128,7 +124,7 @@ class F5Mgmt(object): ) except Exception as e: # pylint: disable=broad-except raise Exception( - "Unable to create `{0}` virtual server\n\n{1}".format(name, e) + "Unable to create `{}` virtual server\n\n{}".format(name, e) ) return True @@ -148,7 +144,7 @@ class F5Mgmt(object): pool_names=[name], lb_methods=[supported_method], members=[[]] ) except Exception as e: # pylint: disable=broad-except - raise Exception("Unable to create `{0}` pool\n\n{1}".format(name, e)) + raise Exception("Unable to create `{}` pool\n\n{}".format(name, e)) else: raise Exception("Unsupported method") return True @@ -158,7 +154,7 @@ class F5Mgmt(object): Add a node to a pool """ if not self.check_pool(pool_name): - raise CommandExecutionError("{0} pool does not exists".format(pool_name)) + raise CommandExecutionError("{} pool does not exists".format(pool_name)) members_seq = self.bigIP.LocalLB.Pool.typefactory.create( "Common.IPPortDefinitionSequence" @@ -178,7 +174,7 @@ class F5Mgmt(object): ) except Exception as e: # pylint: disable=broad-except raise Exception( - "Unable to add `{0}` to `{1}`\n\n{2}".format(name, pool_name, e) + "Unable to add `{}` to `{}`\n\n{}".format(name, pool_name, e) ) return True @@ -233,7 +229,7 @@ def create_vs(lb, name, ip, port, protocol, profile, pool_name): if __opts__["load_balancers"].get(lb, None): (username, password) = list(__opts__["load_balancers"][lb].values()) else: - raise Exception("Unable to find `{0}` load balancer".format(lb)) + raise Exception("Unable to find `{}` load balancer".format(lb)) F5 = F5Mgmt(lb, username, password) F5.create_vs(name, ip, port, protocol, profile, pool_name) @@ -254,7 +250,7 @@ def create_pool(lb, name, method="ROUND_ROBIN"): if __opts__["load_balancers"].get(lb, None): (username, password) = list(__opts__["load_balancers"][lb].values()) else: - raise Exception("Unable to find `{0}` load balancer".format(lb)) + raise Exception("Unable to find `{}` load balancer".format(lb)) F5 = F5Mgmt(lb, username, password) F5.create_pool(name, method) return True @@ -273,7 +269,7 @@ def add_pool_member(lb, name, port, pool_name): if __opts__["load_balancers"].get(lb, None): (username, password) = list(__opts__["load_balancers"][lb].values()) else: - raise Exception("Unable to find `{0}` load balancer".format(lb)) + raise Exception("Unable to find `{}` load balancer".format(lb)) F5 = F5Mgmt(lb, username, password) F5.add_pool_member(name, port, pool_name) return True @@ -292,7 +288,7 @@ def check_pool(lb, name): if __opts__["load_balancers"].get(lb, None): (username, password) = list(__opts__["load_balancers"][lb].values()) else: - raise Exception("Unable to find `{0}` load balancer".format(lb)) + raise Exception("Unable to find `{}` load balancer".format(lb)) F5 = F5Mgmt(lb, username, password) return F5.check_pool(name) @@ -310,7 +306,7 @@ def check_virtualserver(lb, name): if __opts__["load_balancers"].get(lb, None): (username, password) = list(__opts__["load_balancers"][lb].values()) else: - raise Exception("Unable to find `{0}` load balancer".format(lb)) + raise Exception("Unable to find `{}` load balancer".format(lb)) F5 = F5Mgmt(lb, username, password) return F5.check_virtualserver(name) @@ -328,6 +324,6 @@ def check_member_pool(lb, member, pool_name): if __opts__["load_balancers"].get(lb, None): (username, password) = list(__opts__["load_balancers"][lb].values()) else: - raise Exception("Unable to find `{0}` load balancer".format(lb)) + raise Exception("Unable to find `{}` load balancer".format(lb)) F5 = F5Mgmt(lb, username, password) return F5.check_member_pool(member, pool_name) diff --git a/salt/runners/git_pillar.py b/salt/runners/git_pillar.py index bb7535f6c2e..f727385f21f 100644 --- a/salt/runners/git_pillar.py +++ b/salt/runners/git_pillar.py @@ -1,13 +1,9 @@ -# -*- coding: utf-8 -*- """ Runner module to directly manage the git external pillar """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import logging -# Import salt libs import salt.pillar.git_pillar import salt.utils.gitfs from salt.exceptions import SaltRunnerError diff --git a/salt/runners/http.py b/salt/runners/http.py index 910c1b6df8d..a97e18aba60 100644 --- a/salt/runners/http.py +++ b/salt/runners/http.py @@ -1,16 +1,12 @@ -# -*- coding: utf-8 -*- """ Module for making various web calls. Primarily designed for webhooks and the like, but also useful for basic http testing. .. versionadded:: 2015.5.0 """ -from __future__ import absolute_import, print_function, unicode_literals -# Import Python libs import logging -# Import salt libs import salt.utils.http log = logging.getLogger(__name__) diff --git a/salt/runners/launchd.py b/salt/runners/launchd.py index e2812edc2e8..ce9be4e3a9c 100644 --- a/salt/runners/launchd.py +++ b/salt/runners/launchd.py @@ -1,10 +1,7 @@ -# -*- coding: utf-8 -*- """ Manage launchd plist files """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import os import sys @@ -51,7 +48,7 @@ def write_launchd_plist(program): supported_programs = ["salt-master", "salt-minion"] if program not in supported_programs: - sys.stderr.write("Supported programs: '{0}'\n".format(supported_programs)) + sys.stderr.write("Supported programs: '{}'\n".format(supported_programs)) sys.exit(-1) return plist_sample_text.format( diff --git a/salt/runners/mattermost.py b/salt/runners/mattermost.py index 5fcd1762979..a94c9e614d5 100644 --- a/salt/runners/mattermost.py +++ b/salt/runners/mattermost.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Module for sending messages to Mattermost @@ -15,24 +14,17 @@ Module for sending messages to Mattermost api_url: https://example.com """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import logging -# Import Salt libs import salt.utils.json -# Import Salt libs # pylint: disable=import-error,no-name-in-module,redefined-builtin import salt.utils.mattermost # pylint: enable=import-error,no-name-in-module from salt.exceptions import SaltInvocationError -# Import 3rd-party libs -from salt.ext import six - log = logging.getLogger(__name__) __virtualname__ = "mattermost" @@ -138,7 +130,7 @@ def post_message(message, channel=None, username=None, api_url=None, hook=None): log.debug("Parameters: %s", parameters) data = salt.utils.json.dumps(parameters) result = salt.utils.mattermost.query( - api_url=api_url, hook=hook, data=str("payload={0}").format(data) + api_url=api_url, hook=hook, data="payload={}".format(data) ) # future lint: blacklisted-function if result: @@ -174,9 +166,9 @@ def post_event(event, channel=None, username=None, api_url=None, hook=None): log.debug("Event: %s", event) log.debug("Event data: %s", event["data"]) - message = "tag: {0}\r\n".format(event["tag"]) - for key, value in six.iteritems(event["data"]): - message += "{0}: {1}\r\n".format(key, value) + message = "tag: {}\r\n".format(event["tag"]) + for key, value in event["data"].items(): + message += "{}: {}\r\n".format(key, value) result = post_message( message, channel=channel, username=username, api_url=api_url, hook=hook ) diff --git a/salt/runners/mine.py b/salt/runners/mine.py index 8dbc41e13ac..77a0325effb 100644 --- a/salt/runners/mine.py +++ b/salt/runners/mine.py @@ -1,13 +1,9 @@ -# -*- coding: utf-8 -*- """ A runner to access data from the salt mine """ -from __future__ import absolute_import, print_function, unicode_literals -# Import Python Libs import logging -# Import salt libs import salt.daemons.masterapi log = logging.getLevelName(__name__) diff --git a/salt/runners/pagerduty.py b/salt/runners/pagerduty.py index 5148ae8d2f8..b8e83c16b0c 100644 --- a/salt/runners/pagerduty.py +++ b/salt/runners/pagerduty.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Runner Module for Firing Events via PagerDuty @@ -15,14 +14,11 @@ Runner Module for Firing Events via PagerDuty pagerduty.api_key: F3Rbyjbve43rfFWf2214 pagerduty.subdomain: mysubdomain """ -from __future__ import absolute_import, print_function, unicode_literals -# Import salt libs import salt.utils.functools import salt.utils.json import salt.utils.pagerduty import salt.utils.yaml -from salt.ext import six def __virtual__(): @@ -162,9 +158,9 @@ def create_event( """ trigger_url = "https://events.pagerduty.com/generic/2010-04-15/create_event.json" - if isinstance(details, six.string_types): + if isinstance(details, str): details = salt.utils.yaml.safe_load(details) - if isinstance(details, six.string_types): + if isinstance(details, str): details = {"details": details} ret = salt.utils.json.loads( diff --git a/salt/runners/pkg.py b/salt/runners/pkg.py index 03caf1fc3d8..6a4a06e6109 100644 --- a/salt/runners/pkg.py +++ b/salt/runners/pkg.py @@ -1,21 +1,13 @@ -# -*- coding: utf-8 -*- """ Package helper functions using ``salt.modules.pkg`` .. versionadded:: 2015.8.0 """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import salt.minion - -# Import salt libs import salt.output -# Import 3rd-party libs -from salt.ext import six - def _get_returner(returner_types): """ @@ -41,17 +33,17 @@ def list_upgrades(jid, style="group", outputter="nested", ext_source=None): (__opts__["ext_job_cache"], ext_source, __opts__["master_job_cache"]) ) - data = mminion.returners["{0}.get_jid".format(returner)](jid) + data = mminion.returners["{}.get_jid".format(returner)](jid) pkgs = {} if style == "group": for minion in data: results = data[minion]["return"] - for pkg, pkgver in six.iteritems(results): - if pkg not in six.iterkeys(pkgs): + for pkg, pkgver in results.items(): + if pkg not in pkgs.keys(): pkgs[pkg] = {pkgver: {"hosts": []}} - if pkgver not in six.iterkeys(pkgs[pkg]): + if pkgver not in pkgs[pkg].keys(): pkgs[pkg].update({pkgver: {"hosts": []}}) pkgs[pkg][pkgver]["hosts"].append(minion) diff --git a/salt/runners/queue.py b/salt/runners/queue.py index 2d7405d4165..fd1df461e8e 100644 --- a/salt/runners/queue.py +++ b/salt/runners/queue.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ General management and processing of queues. ============================================ @@ -62,13 +61,9 @@ run them. And it will do this every minute, unless there are any jobs that are still running from the last time the process_runner task was executed. """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals -# Import salt libs import salt.loader from salt.exceptions import SaltInvocationError -from salt.ext import six from salt.utils.event import get_event, tagify @@ -86,9 +81,9 @@ def insert(queue, items, backend="sqlite"): salt-run queue.insert myqueue "['item1', 'item2', 'item3']" backend=sqlite """ queue_funcs = salt.loader.queues(__opts__) - cmd = "{0}.insert".format(backend) + cmd = "{}.insert".format(backend) if cmd not in queue_funcs: - raise SaltInvocationError('Function "{0}" is not available'.format(cmd)) + raise SaltInvocationError('Function "{}" is not available'.format(cmd)) ret = queue_funcs[cmd](items=items, queue=queue) return ret @@ -106,9 +101,9 @@ def delete(queue, items, backend="sqlite"): salt-run queue.delete myqueue "['item1', 'item2', 'item3']" """ queue_funcs = salt.loader.queues(__opts__) - cmd = "{0}.delete".format(backend) + cmd = "{}.delete".format(backend) if cmd not in queue_funcs: - raise SaltInvocationError('Function "{0}" is not available'.format(cmd)) + raise SaltInvocationError('Function "{}" is not available'.format(cmd)) ret = queue_funcs[cmd](items=items, queue=queue) return ret @@ -125,9 +120,9 @@ def list_queues(backend="sqlite"): salt-run queue.list_queues backend=sqlite """ queue_funcs = salt.loader.queues(__opts__) - cmd = "{0}.list_queues".format(backend) + cmd = "{}.list_queues".format(backend) if cmd not in queue_funcs: - raise SaltInvocationError('Function "{0}" is not available'.format(cmd)) + raise SaltInvocationError('Function "{}" is not available'.format(cmd)) ret = queue_funcs[cmd]() return ret @@ -144,9 +139,9 @@ def list_length(queue, backend="sqlite"): salt-run queue.list_length myqueue backend=sqlite """ queue_funcs = salt.loader.queues(__opts__) - cmd = "{0}.list_length".format(backend) + cmd = "{}.list_length".format(backend) if cmd not in queue_funcs: - raise SaltInvocationError('Function "{0}" is not available'.format(cmd)) + raise SaltInvocationError('Function "{}" is not available'.format(cmd)) ret = queue_funcs[cmd](queue=queue) return ret @@ -163,9 +158,9 @@ def list_items(queue, backend="sqlite"): salt-run queue.list_items myqueue backend=sqlite """ queue_funcs = salt.loader.queues(__opts__) - cmd = "{0}.list_items".format(backend) + cmd = "{}.list_items".format(backend) if cmd not in queue_funcs: - raise SaltInvocationError('Function "{0}" is not available'.format(cmd)) + raise SaltInvocationError('Function "{}" is not available'.format(cmd)) ret = queue_funcs[cmd](queue=queue) return ret @@ -185,9 +180,9 @@ def pop(queue, quantity=1, backend="sqlite", is_runner=False): salt-run queue.pop myqueue all backend=sqlite """ queue_funcs = salt.loader.queues(__opts__) - cmd = "{0}.pop".format(backend) + cmd = "{}.pop".format(backend) if cmd not in queue_funcs: - raise SaltInvocationError('Function "{0}" is not available'.format(cmd)) + raise SaltInvocationError('Function "{}" is not available'.format(cmd)) ret = queue_funcs[cmd](quantity=quantity, queue=queue, is_runner=is_runner) return ret @@ -218,7 +213,7 @@ def process_queue(queue, quantity=1, backend="sqlite", is_runner=False): queue=queue, quantity=quantity, backend=backend, is_runner=is_runner ) except SaltInvocationError as exc: - error_txt = "{0}".format(exc) + error_txt = "{}".format(exc) __jid_event__.fire_event({"errors": error_txt}, "progress") return False @@ -271,7 +266,7 @@ def insert_runner(fun, args=None, kwargs=None, queue=None, backend=None): """ if args is None: args = [] - elif isinstance(args, six.string_types): + elif isinstance(args, str): args = args.split(",") if kwargs is None: kwargs = {} diff --git a/salt/runners/sdb.py b/salt/runners/sdb.py index 06d94172e40..eef6641abb4 100644 --- a/salt/runners/sdb.py +++ b/salt/runners/sdb.py @@ -1,10 +1,7 @@ -# coding: utf-8 """ Runner for setting and querying data via the sdb API on the master """ -from __future__ import absolute_import, print_function, unicode_literals -# Import salt libs import salt.utils.sdb __func_alias__ = { diff --git a/salt/runners/spacewalk.py b/salt/runners/spacewalk.py index 40f73bb4927..7720f9c9998 100644 --- a/salt/runners/spacewalk.py +++ b/salt/runners/spacewalk.py @@ -31,8 +31,7 @@ master configuration at ``/etc/salt/master`` or ``/etc/salt/master.d/spacewalk.c import atexit import logging - -from salt.ext import six +import xmlrpc.client log = logging.getLogger(__name__) @@ -99,9 +98,7 @@ def _get_client_and_key(url, user, password, verbose=0): Return the client object and session key for the client """ session = {} - session["client"] = six.moves.xmlrpc_client.Server( - url, verbose=verbose, use_datetime=True - ) + session["client"] = xmlrpc.client.Server(url, verbose=verbose, use_datetime=True) session["key"] = session["client"].auth.login(user, password) return session diff --git a/salt/runners/ssh.py b/salt/runners/ssh.py index 0a6ab3f2a03..90ac4cfc02d 100644 --- a/salt/runners/ssh.py +++ b/salt/runners/ssh.py @@ -1,14 +1,10 @@ -# -*- coding: utf-8 -*- """ A Runner module interface on top of the salt-ssh Python API. This allows for programmatic use from salt-api, the Reactor, Orchestrate, etc. """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals -# Import Salt Libs import salt.client.ssh.client diff --git a/salt/runners/test.py b/salt/runners/test.py index b405c63df12..cfef23d68d4 100644 --- a/salt/runners/test.py +++ b/salt/runners/test.py @@ -1,15 +1,9 @@ -# -*- coding: utf-8 -*- """ This runner is used only for test purposes and servers no production purpose """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import time -from salt.ext import six -from salt.ext.six.moves import range - def arg(*args, **kwargs): """ @@ -17,7 +11,7 @@ def arg(*args, **kwargs): Kwargs will be filtered for 'private' keynames. """ - kwargs = dict((k, v) for k, v in six.iteritems(kwargs) if not k.startswith("__")) + kwargs = {k: v for k, v in kwargs.items() if not k.startswith("__")} ret = { "args": args, @@ -87,7 +81,7 @@ def stream(): ret = True for i in range(1, 100): __jid_event__.fire_event( - {"message": "Runner is {0}% done".format(i)}, "progress" + {"message": "Runner is {}% done".format(i)}, "progress" ) time.sleep(0.1) return ret diff --git a/salt/runners/thin.py b/salt/runners/thin.py index 1de863039fd..593342e8697 100644 --- a/salt/runners/thin.py +++ b/salt/runners/thin.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ The thin runner is used to manage the salt thin systems. @@ -7,10 +6,7 @@ in a standalone way. This runner has tools which generate the standalone salt system for easy consumption. """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals -# Import Salt libs import salt.utils.thin diff --git a/salt/runners/venafiapi.py b/salt/runners/venafiapi.py index 43ac2e91cfe..a7c4d8f74f4 100644 --- a/salt/runners/venafiapi.py +++ b/salt/runners/venafiapi.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Support for Venafi @@ -24,11 +23,8 @@ Support for Venafi trust_bundle: "/opt/venafi/bundle.pem" """ -from __future__ import absolute_import, print_function, unicode_literals import logging - -# Import Salt libs import sys import time @@ -39,9 +35,6 @@ import salt.utils.json import salt.utils.stringutils from salt.exceptions import CommandExecutionError -# Import 3rd-party libs -from salt.ext import six - try: import vcert from vcert.common import CertificateRequest @@ -116,7 +109,7 @@ def request( log.info("Requesting Venafi certificate") if zone is None: - log.error(msg=str("Missing zone parameter")) + log.error(msg="Missing zone parameter") sys.exit(1) if key_password is not None: @@ -244,7 +237,7 @@ def del_cached_domain(domains): salt-run venafi.del_cached_domain domain1.example.com,domain2.example.com """ cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR) - if isinstance(domains, six.string_types): + if isinstance(domains, str): domains = domains.split(",") if not isinstance(domains, list): raise CommandExecutionError( diff --git a/salt/runners/vistara.py b/salt/runners/vistara.py index 4d5f03cc312..b0086569fe0 100644 --- a/salt/runners/vistara.py +++ b/salt/runners/vistara.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Vistara Runner @@ -20,12 +19,9 @@ For example ``/etc/salt/master.d/_vistara.conf``: """ -from __future__ import absolute_import, print_function, unicode_literals -# Import Python libs import logging -# Import Salt libs import salt.output # See https://docs.saltstack.com/en/latest/topics/tutorials/http.html @@ -102,7 +98,7 @@ def delete_device(name, safety_on=True): if not access_token: return "Vistara access token not available" - query_string = "dnsName:{0}".format(name) + query_string = "dnsName:{}".format(name) devices = _search_devices(query_string, config["client_id"], access_token) @@ -113,7 +109,7 @@ def delete_device(name, safety_on=True): if safety_on and device_count != 1: return ( - "Expected to delete 1 device and found {0}. " + "Expected to delete 1 device and found {}. " "Set safety_on=False to override.".format(device_count) ) @@ -131,7 +127,7 @@ def delete_device(name, safety_on=True): def _search_devices(query_string, client_id, access_token): - authstring = "Bearer {0}".format(access_token) + authstring = "Bearer {}".format(access_token) headers = { "Authorization": authstring, @@ -142,7 +138,7 @@ def _search_devices(query_string, client_id, access_token): params = {"queryString": query_string} method = "GET" - url = "https://api.vistara.io/api/v2/tenants/{0}/devices/search".format(client_id) + url = "https://api.vistara.io/api/v2/tenants/{}/devices/search".format(client_id) resp = salt.utils.http.query( url=url, method=method, header_dict=headers, params=params, opts=__opts__ @@ -160,7 +156,7 @@ def _search_devices(query_string, client_id, access_token): def _delete_resource(device_id, client_id, access_token): - authstring = "Bearer {0}".format(access_token) + authstring = "Bearer {}".format(access_token) headers = { "Authorization": authstring, @@ -169,7 +165,7 @@ def _delete_resource(device_id, client_id, access_token): } method = "DELETE" - url = "https://api.vistara.io/api/v2/tenants/{0}/rtype/DEVICE/resource/{1}".format( + url = "https://api.vistara.io/api/v2/tenants/{}/rtype/DEVICE/resource/{}".format( client_id, device_id ) diff --git a/salt/sdb/cache.py b/salt/sdb/cache.py index ea4eb20aae3..837fcba8ff1 100644 --- a/salt/sdb/cache.py +++ b/salt/sdb/cache.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ cache Module @@ -45,8 +44,6 @@ it must be specified in the URI: master_ip: sdb://mastercloudcache/public_ips?bank=cloud/active/ec2/my-ec2-conf/saltmaster """ -# import python libs -from __future__ import absolute_import, print_function, unicode_literals import salt.cache diff --git a/salt/sdb/consul.py b/salt/sdb/consul.py index acf71c2d6a1..1db699f7094 100644 --- a/salt/sdb/consul.py +++ b/salt/sdb/consul.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Consul sdb Module @@ -27,7 +26,6 @@ requires very little. For example: The ``driver`` refers to the Consul module, all other options are optional. For option details see: https://python-consul.readthedocs.io/en/latest/#consul """ -from __future__ import absolute_import, print_function, unicode_literals from salt.exceptions import CommandExecutionError diff --git a/salt/sdb/couchdb.py b/salt/sdb/couchdb.py index 40465a3b9e3..978385f9788 100644 --- a/salt/sdb/couchdb.py +++ b/salt/sdb/couchdb.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ CouchDB sdb Module @@ -36,7 +35,6 @@ Additional contributions to build true map-reduce functionality into this module would be welcome. """ -from __future__ import absolute_import, print_function, unicode_literals # Import Python libraries import logging diff --git a/salt/sdb/env.py b/salt/sdb/env.py index d0a76bd6d6b..0a4ad6bc978 100644 --- a/salt/sdb/env.py +++ b/salt/sdb/env.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Environment sdb Module @@ -57,9 +56,7 @@ in the environment: ..snip """ -from __future__ import absolute_import, print_function, unicode_literals -# Import Python libs import os __func_alias__ = {"set_": "set"} diff --git a/salt/sdb/keyring_db.py b/salt/sdb/keyring_db.py index dca0c693d43..08304610f42 100644 --- a/salt/sdb/keyring_db.py +++ b/salt/sdb/keyring_db.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Keyring Database Module @@ -44,9 +43,7 @@ https://pypi.python.org/pypi/keyring .. versionadded:: 2014.1.4 """ -from __future__ import absolute_import, print_function, unicode_literals -# import python libs import logging try: diff --git a/salt/sdb/memcached.py b/salt/sdb/memcached.py index bb8128ba2de..060fdfb10fc 100644 --- a/salt/sdb/memcached.py +++ b/salt/sdb/memcached.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Memcached sdb Module @@ -30,12 +29,9 @@ and ``mymemcached`` refers to the name that will appear in the URI: password: sdb://mymemcached/mykey """ -from __future__ import absolute_import, print_function, unicode_literals -# import python libs import logging -# import Salt libs import salt.utils.memcached DEFAULT_HOST = "127.0.0.1" diff --git a/salt/sdb/redis_sdb.py b/salt/sdb/redis_sdb.py index 9f8388b6deb..1419e3813c8 100644 --- a/salt/sdb/redis_sdb.py +++ b/salt/sdb/redis_sdb.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Redis SDB module ================ @@ -24,7 +23,6 @@ The ``driver`` refers to the Redis module, all other options are optional. For option details see: https://redis-py.readthedocs.io/en/latest/. """ -from __future__ import absolute_import, print_function, unicode_literals try: import redis diff --git a/salt/sdb/rest.py b/salt/sdb/rest.py index 2acc83f7255..f436fc5802b 100644 --- a/salt/sdb/rest.py +++ b/salt/sdb/rest.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Generic REST API SDB Module @@ -65,8 +64,6 @@ For instance: user: myuser """ -# import python libs -from __future__ import absolute_import, print_function, unicode_literals import logging diff --git a/salt/sdb/sqlite3.py b/salt/sdb/sqlite3.py index cf2095ce752..4e7ba8f7ea3 100644 --- a/salt/sdb/sqlite3.py +++ b/salt/sdb/sqlite3.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ SQLite sdb Module @@ -42,16 +41,11 @@ create the table(s) and get and set values. get_query: "SELECT d FROM advanced WHERE a=:key" set_query: "INSERT OR REPLACE INTO advanced (a, d) VALUES (:key, :value)" """ -from __future__ import absolute_import, print_function, unicode_literals import codecs - -# Import python libs import logging -# Import salt libs import salt.utils.msgpack -from salt.ext import six try: import sqlite3 @@ -112,8 +106,8 @@ def _connect(profile): for sql in stmts: cur.execute(sql) elif profile.get("create_table", True): - cur.execute(("CREATE TABLE {0} (key text, " "value blob)").format(table)) - cur.execute(("CREATE UNIQUE INDEX {0} ON {1} " "(key)").format(idx, table)) + cur.execute(("CREATE TABLE {} (key text, " "value blob)").format(table)) + cur.execute(("CREATE UNIQUE INDEX {} ON {} " "(key)").format(idx, table)) except sqlite3.OperationalError: pass @@ -127,15 +121,10 @@ def set_(key, value, profile=None): if not profile: return False conn, cur, table = _connect(profile) - if six.PY2: - # pylint: disable=undefined-variable - value = buffer(salt.utils.msgpack.packb(value)) - # pylint: enable=undefined-variable - else: - value = memoryview(salt.utils.msgpack.packb(value)) + value = memoryview(salt.utils.msgpack.packb(value)) q = profile.get( "set_query", - ("INSERT OR REPLACE INTO {0} VALUES " "(:key, :value)").format(table), + ("INSERT OR REPLACE INTO {} VALUES " "(:key, :value)").format(table), ) conn.execute(q, {"key": key, "value": value}) conn.commit() @@ -150,7 +139,7 @@ def get(key, profile=None): return None _, cur, table = _connect(profile) q = profile.get( - "get_query", ("SELECT value FROM {0} WHERE " "key=:key".format(table)) + "get_query", ("SELECT value FROM {} WHERE " "key=:key".format(table)) ) res = cur.execute(q, {"key": key}) res = res.fetchone() diff --git a/salt/sdb/tism.py b/salt/sdb/tism.py index 89ebd597f7d..8304c2079da 100644 --- a/salt/sdb/tism.py +++ b/salt/sdb/tism.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ tISM - the Immutable Secrets Manager SDB Module @@ -28,17 +27,12 @@ configuration. token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhZG1pbiI6MSwiZXhwIjoxNTg1MTExNDYwLCJqdGkiOiI3NnA5cWNiMWdtdmw4Iiwia2V5cyI6WyJBTEwiXX0.RtAhG6Uorf5xnSf4Ya_GwJnoHkCsql4r1_hiOeDSLzo """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import logging import salt.utils.http as http - -# Import Salt libs import salt.utils.json from salt.exceptions import SaltConfigurationError -from salt.ext import six log = logging.getLogger(__name__) @@ -75,6 +69,6 @@ def get(key, service=None, profile=None): # pylint: disable=W0613 "tism.get sdb decryption request failed with error %s", result.get("error", "unknown"), ) - return "ERROR" + six.text_type(result.get("status", "unknown")) + return "ERROR" + str(result.get("status", "unknown")) return decrypted diff --git a/salt/sdb/vault.py b/salt/sdb/vault.py index 164ec4f3e0c..82c2050f74a 100644 --- a/salt/sdb/vault.py +++ b/salt/sdb/vault.py @@ -39,7 +39,6 @@ The above URI is analogous to running the following vault command: $ vault read -field=mypassword secret/passwords """ -# import python libs import logging diff --git a/salt/sdb/yaml.py b/salt/sdb/yaml.py index 814d8a44e89..1411e6c2899 100644 --- a/salt/sdb/yaml.py +++ b/salt/sdb/yaml.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Pull sdb values from a YAML file @@ -42,8 +41,6 @@ embedded GPG-encrypted data using the :py:mod:`GPG renderer `. """ -# import python libs -from __future__ import absolute_import, print_function, unicode_literals import logging @@ -98,7 +95,7 @@ def _get_values(profile=None): ret = salt.utils.dictupdate.merge( ret, contents, **profile.get("merge", {}) ) - except IOError: + except OSError: log.error("File '%s' not found ", fname) except TypeError as exc: log.error("Error deserializing sdb file '%s': %s", fname, exc) diff --git a/salt/serializers/configparser.py b/salt/serializers/configparser.py index f391f36333b..a4eee099cc1 100644 --- a/salt/serializers/configparser.py +++ b/salt/serializers/configparser.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ salt.serializers.configparser ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -8,13 +7,9 @@ Implements a configparser serializer. """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals +import configparser +import io -import salt.ext.six.moves.configparser as configparser # pylint: disable=E0611 - -# Import Salt Libs -from salt.ext import six from salt.serializers import DeserializationError, SerializationError __all__ = ["deserialize", "serialize", "available"] @@ -30,23 +25,13 @@ def deserialize(stream_or_string, **options): :param options: options given to lower configparser module. """ - if six.PY3: - cp = configparser.ConfigParser(**options) - else: - cp = configparser.SafeConfigParser(**options) + cp = configparser.ConfigParser(**options) try: - if not isinstance(stream_or_string, (bytes, six.string_types)): - if six.PY3: - cp.read_file(stream_or_string) - else: - cp.readfp(stream_or_string) + if not isinstance(stream_or_string, (bytes, (str,))): + cp.read_file(stream_or_string) else: - if six.PY3: - cp.read_file(six.moves.StringIO(stream_or_string)) - else: - # python2's ConfigParser cannot parse a config from a string - cp.readfp(six.moves.StringIO(stream_or_string)) + cp.read_file(io.StringIO(stream_or_string)) data = {} for section_name in cp.sections(): section = {} @@ -69,21 +54,16 @@ def serialize(obj, **options): try: if not isinstance(obj, dict): raise TypeError( - "configparser can only serialize dictionaries, not {0}".format( - type(obj) - ) + "configparser can only serialize dictionaries, not {}".format(type(obj)) ) fp = options.pop("fp", None) - if six.PY3: - cp = configparser.ConfigParser(**options) - else: - cp = configparser.SafeConfigParser(**options) + cp = configparser.ConfigParser(**options) _read_dict(cp, obj) if fp: return cp.write(fp) else: - s = six.moves.StringIO() + s = io.StringIO() cp.write(s) return s.getvalue() except Exception as error: # pylint: disable=broad-except @@ -91,10 +71,7 @@ def serialize(obj, **options): def _is_defaultsect(section_name): - if six.PY3: - return section_name == configparser.DEFAULTSECT - else: # in py2 the check is done against lowercased section name - return section_name.upper() == configparser.DEFAULTSECT + return section_name == configparser.DEFAULTSECT def _read_dict(cp, dictionary): @@ -102,16 +79,12 @@ def _read_dict(cp, dictionary): Cribbed from python3's ConfigParser.read_dict function. """ for section, keys in dictionary.items(): - section = six.text_type(section) + section = str(section) - if _is_defaultsect(section): - if six.PY2: - section = configparser.DEFAULTSECT - else: - cp.add_section(section) + cp.add_section(section) for key, value in keys.items(): - key = cp.optionxform(six.text_type(key)) + key = cp.optionxform(str(key)) if value is not None: - value = six.text_type(value) + value = str(value) cp.set(section, key, value) diff --git a/salt/serializers/json.py b/salt/serializers/json.py index 45e791fa4f6..b06f4e73e36 100644 --- a/salt/serializers/json.py +++ b/salt/serializers/json.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ salt.serializers.json ~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -8,13 +7,8 @@ It's just a wrapper around json (or simplejson if available). """ -from __future__ import absolute_import, print_function, unicode_literals -# Import Salt libs import salt.utils.json - -# Import 3rd-party libs -from salt.ext import six from salt.serializers import DeserializationError, SerializationError try: @@ -37,7 +31,7 @@ def deserialize(stream_or_string, **options): """ try: - if not isinstance(stream_or_string, (bytes, six.string_types)): + if not isinstance(stream_or_string, (bytes, (str,))): return salt.utils.json.load(stream_or_string, _json_module=_json, **options) if isinstance(stream_or_string, bytes): diff --git a/salt/serializers/msgpack.py b/salt/serializers/msgpack.py index c89e00f9cb2..66af5bdf798 100644 --- a/salt/serializers/msgpack.py +++ b/salt/serializers/msgpack.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ salt.serializers.msgpack ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -6,17 +5,11 @@ Implements MsgPack serializer. """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import copy import logging -# Import Salt Libs import salt.utils.msgpack - -# Import 3rd-party libs -from salt.ext import six from salt.serializers import DeserializationError, SerializationError log = logging.getLogger(__name__) @@ -80,7 +73,7 @@ else: # msgpack.version < 0.2.0 tuples. """ if isinstance(obj, dict): - data = [(key, _encoder(value)) for key, value in six.iteritems(obj)] + data = [(key, _encoder(value)) for key, value in obj.items()] return dict(data) elif isinstance(obj, (list, tuple)): return [_encoder(value) for value in obj] diff --git a/salt/serializers/plist.py b/salt/serializers/plist.py index 3010ff30c8e..a833b4e7897 100644 --- a/salt/serializers/plist.py +++ b/salt/serializers/plist.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ salt.serializers.plist ~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/salt/serializers/python.py b/salt/serializers/python.py index d83d82e40cc..f105601d067 100644 --- a/salt/serializers/python.py +++ b/salt/serializers/python.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ salt.serializers.python ~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -7,7 +6,6 @@ Implements a Python serializer (via pprint.format) """ -from __future__ import absolute_import, unicode_literals import pprint diff --git a/salt/serializers/yaml.py b/salt/serializers/yaml.py index 1061d1180a4..8e7c8065f9d 100644 --- a/salt/serializers/yaml.py +++ b/salt/serializers/yaml.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ salt.serializers.yaml ~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -9,13 +8,11 @@ It also use C bindings if they are available. """ -from __future__ import absolute_import, print_function, unicode_literals import datetime import logging import yaml -from salt.ext import six from salt.serializers import DeserializationError, SerializationError from salt.utils.odict import OrderedDict from yaml.constructor import ConstructorError @@ -123,9 +120,6 @@ class Dumper(BaseDumper): # pylint: disable=W0232 Dumper.add_multi_representer(EncryptedString, EncryptedString.yaml_dumper) Dumper.add_multi_representer(type(None), Dumper.represent_none) Dumper.add_multi_representer(str, Dumper.represent_str) -if six.PY2: - Dumper.add_multi_representer(six.text_type, Dumper.represent_unicode) - Dumper.add_multi_representer(int, Dumper.represent_long) Dumper.add_multi_representer(bool, Dumper.represent_bool) Dumper.add_multi_representer(int, Dumper.represent_int) Dumper.add_multi_representer(float, Dumper.represent_float) diff --git a/salt/serializers/yamlex.py b/salt/serializers/yamlex.py index bf9b2782481..f0d7eb0950a 100644 --- a/salt/serializers/yamlex.py +++ b/salt/serializers/yamlex.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ salt.serializers.yamlex ~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -102,18 +101,12 @@ # pylint: disable=invalid-name,no-member,missing-docstring,no-self-use # pylint: disable=too-few-public-methods,too-many-public-methods -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import copy import datetime import logging -# Import 3rd-party libs import yaml -from salt.ext import six - -# Import Salt Libs from salt.serializers import DeserializationError, SerializationError from salt.utils.aggregation import Map, Sequence, aggregate from salt.utils.odict import OrderedDict @@ -129,17 +122,14 @@ available = True # prefer C bindings over python when available BaseLoader = getattr(yaml, "CSafeLoader", yaml.SafeLoader) -if six.PY3: - # CSafeDumper causes repr errors in python3, so use the pure Python one - try: - # Depending on how PyYAML was built, yaml.SafeDumper may actually be - # yaml.cyaml.CSafeDumper (i.e. the C dumper instead of pure Python). - BaseDumper = yaml.dumper.SafeDumper - except AttributeError: - # Here just in case, but yaml.dumper.SafeDumper should always exist - BaseDumper = yaml.SafeDumper -else: - BaseDumper = getattr(yaml, "CSafeDumper", yaml.SafeDumper) +# CSafeDumper causes repr errors in python3, so use the pure Python one +try: + # Depending on how PyYAML was built, yaml.SafeDumper may actually be + # yaml.cyaml.CSafeDumper (i.e. the C dumper instead of pure Python). + BaseDumper = yaml.dumper.SafeDumper +except AttributeError: + # Here just in case, but yaml.dumper.SafeDumper should always exist + BaseDumper = yaml.SafeDumper ERROR_MAP = { ("found character '\\t' " "that cannot start any token"): "Illegal tab character" @@ -217,7 +207,7 @@ class Loader(BaseLoader): # pylint: disable=W0232 raise ConstructorError( None, None, - "expected a mapping node, but found {0}".format(node.id), + "expected a mapping node, but found {}".format(node.id), node.start_mark, ) @@ -241,7 +231,7 @@ class Loader(BaseLoader): # pylint: disable=W0232 hash(key) except TypeError: err = ( - "While constructing a mapping {0} found unacceptable " "key {1}" + "While constructing a mapping {} found unacceptable " "key {}" ).format(node.start_mark, key_node.start_mark) raise ConstructorError(err) value = self.construct_object(value_node, deep=False) @@ -257,8 +247,6 @@ class Loader(BaseLoader): # pylint: disable=W0232 # Ensure obj is str, not py2 unicode or py3 bytes obj = self.construct_scalar(node) - if six.PY2: - obj = obj.encode("utf-8") return SLSString(obj) def construct_sls_int(self, node): @@ -408,15 +396,8 @@ class Dumper(BaseDumper): # pylint: disable=W0232 Dumper.add_multi_representer(type(None), Dumper.represent_none) -if six.PY2: - Dumper.add_multi_representer(six.binary_type, Dumper.represent_str) - Dumper.add_multi_representer(six.text_type, Dumper.represent_unicode) - # pylint: disable=incompatible-py3-code,undefined-variable - Dumper.add_multi_representer(long, Dumper.represent_long) - # pylint: enable=incompatible-py3-code,undefined-variable -else: - Dumper.add_multi_representer(six.binary_type, Dumper.represent_binary) - Dumper.add_multi_representer(six.text_type, Dumper.represent_str) +Dumper.add_multi_representer(bytes, Dumper.represent_binary) +Dumper.add_multi_representer(str, Dumper.represent_str) Dumper.add_multi_representer(bool, Dumper.represent_bool) Dumper.add_multi_representer(int, Dumper.represent_int) Dumper.add_multi_representer(float, Dumper.represent_float) diff --git a/salt/states/alias.py b/salt/states/alias.py index bc624ba1acd..6c2eb8959e1 100644 --- a/salt/states/alias.py +++ b/salt/states/alias.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Configuration of email aliases @@ -26,7 +25,6 @@ file from the default location, set the following in your minion config: aliases.file: /my/alias/file """ -from __future__ import absolute_import, print_function, unicode_literals def present(name, target): @@ -45,20 +43,20 @@ def present(name, target): ret = {"name": name, "changes": {}, "result": False, "comment": ""} if __salt__["aliases.has_target"](name, target): ret["result"] = True - ret["comment"] = "Alias {0} already present".format(name) + ret["comment"] = "Alias {} already present".format(name) return ret if __opts__["test"]: ret["result"] = None - ret["comment"] = "Alias {0} -> {1} is set to be added".format(name, target) + ret["comment"] = "Alias {} -> {} is set to be added".format(name, target) return ret if __salt__["aliases.set_target"](name, target): ret["changes"] = {"alias": name} ret["result"] = True - ret["comment"] = "Set email alias {0} -> {1}".format(name, target) + ret["comment"] = "Set email alias {} -> {}".format(name, target) return ret else: ret["result"] = False - ret["comment"] = "Failed to set alias {0} -> {1}".format(name, target) + ret["comment"] = "Failed to set alias {} -> {}".format(name, target) return ret @@ -72,18 +70,18 @@ def absent(name): ret = {"name": name, "changes": {}, "result": False, "comment": ""} if not __salt__["aliases.get_target"](name): ret["result"] = True - ret["comment"] = "Alias {0} already absent".format(name) + ret["comment"] = "Alias {} already absent".format(name) return ret if __opts__["test"]: ret["result"] = None - ret["comment"] = "Alias {0} is set to be removed".format(name) + ret["comment"] = "Alias {} is set to be removed".format(name) return ret if __salt__["aliases.rm_alias"](name): ret["changes"] = {"alias": name} ret["result"] = True - ret["comment"] = "Removed alias {0}".format(name) + ret["comment"] = "Removed alias {}".format(name) return ret else: ret["result"] = False - ret["comment"] = "Failed to remove alias {0}".format(name) + ret["comment"] = "Failed to remove alias {}".format(name) return ret diff --git a/salt/states/alternatives.py b/salt/states/alternatives.py index e2fbaba1e29..590771db1ad 100644 --- a/salt/states/alternatives.py +++ b/salt/states/alternatives.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Configuration of the alternatives system @@ -26,7 +25,6 @@ Control the alternatives system - path: {{ my_hadoop_conf }} """ -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"} @@ -73,13 +71,13 @@ def install(name, link, path, priority): } if __salt__["alternatives.check_exists"](name, path): - ret["comment"] = "Alternative {0} for {1} is already registered".format( + ret["comment"] = "Alternative {} for {} is already registered".format( path, name ) else: if __opts__["test"]: ret["comment"] = ( - "Alternative will be set for {0} to {1} with priority {2}" + "Alternative will be set for {} to {} with priority {}" ).format(name, path, priority) ret["result"] = None return ret @@ -88,11 +86,11 @@ def install(name, link, path, priority): if __salt__["alternatives.check_exists"](name, path): if __salt__["alternatives.check_installed"](name, path): ret["comment"] = ( - "Alternative for {0} set to path {1} with priority {2}" + "Alternative for {} set to path {} with priority {}" ).format(name, path, priority) else: ret["comment"] = ( - "Alternative {0} for {1} registered with priority {2} and not set to default" + "Alternative {} for {} registered with priority {} and not set to default" ).format(path, name, priority) ret["changes"] = { "name": name, @@ -102,9 +100,7 @@ def install(name, link, path, priority): } else: ret["result"] = False - ret["comment"] = ("Alternative for {0} not installed: {1}").format( - name, out - ) + ret["comment"] = ("Alternative for {} not installed: {}").format(name, out) return ret @@ -127,7 +123,7 @@ def remove(name, path): isinstalled = __salt__["alternatives.check_exists"](name, path) if isinstalled: if __opts__["test"]: - ret["comment"] = "Alternative for {0} will be removed".format(name) + ret["comment"] = "Alternative for {} will be removed".format(name) ret["result"] = None return ret __salt__["alternatives.remove"](name, path) @@ -135,25 +131,25 @@ def remove(name, path): if current: ret["result"] = True ret["comment"] = ( - "Alternative for {0} removed. Falling back to path {1}" + "Alternative for {} removed. Falling back to path {}" ).format(name, current) ret["changes"] = {"path": current} return ret - ret["comment"] = "Alternative for {0} removed".format(name) + ret["comment"] = "Alternative for {} removed".format(name) ret["changes"] = {} return ret current = __salt__["alternatives.show_current"](name) if current: ret["result"] = True - ret["comment"] = ("Alternative for {0} is set to it's default path {1}").format( + ret["comment"] = ("Alternative for {} is set to it's default path {}").format( name, current ) return ret ret["result"] = False - ret["comment"] = ("Alternative for {0} doesn't exist").format(name) + ret["comment"] = ("Alternative for {} doesn't exist").format(name) return ret @@ -175,11 +171,11 @@ def auto(name): display = __salt__["alternatives.display"](name) line = display.splitlines()[0] if line.endswith(" auto mode"): - ret["comment"] = "{0} already in auto mode".format(name) + ret["comment"] = "{} already in auto mode".format(name) return ret if __opts__["test"]: - ret["comment"] = "{0} will be put in auto mode".format(name) + ret["comment"] = "{} will be put in auto mode".format(name) ret["result"] = None return ret ret["changes"]["result"] = __salt__["alternatives.auto"](name) @@ -211,7 +207,7 @@ def set_(name, path): current = __salt__["alternatives.show_current"](name) if current == path: - ret["comment"] = "Alternative for {0} already set to {1}".format(name, path) + ret["comment"] = "Alternative for {} already set to {}".format(name, path) return ret display = __salt__["alternatives.display"](name) @@ -223,7 +219,7 @@ def set_(name, path): if isinstalled: if __opts__["test"]: - ret["comment"] = ("Alternative for {0} will be set to path {1}").format( + ret["comment"] = ("Alternative for {} will be set to path {}").format( name, path ) ret["result"] = None @@ -231,17 +227,15 @@ def set_(name, path): __salt__["alternatives.set"](name, path) current = __salt__["alternatives.show_current"](name) if current == path: - ret["comment"] = ("Alternative for {0} set to path {1}").format( - name, current - ) + ret["comment"] = ("Alternative for {} set to path {}").format(name, current) ret["changes"] = {"path": current} else: - ret["comment"] = "Alternative for {0} not updated".format(name) + ret["comment"] = "Alternative for {} not updated".format(name) return ret else: ret["result"] = False - ret["comment"] = ("Alternative {0} for {1} doesn't exist").format(path, name) + ret["comment"] = ("Alternative {} for {} doesn't exist").format(path, name) return ret diff --git a/salt/states/artifactory.py b/salt/states/artifactory.py index d9e7c2e97e3..2395fe7d6c4 100644 --- a/salt/states/artifactory.py +++ b/salt/states/artifactory.py @@ -1,16 +1,11 @@ -# -*- coding: utf-8 -*- """ This state downloads artifacts from artifactory. """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import logging -from salt.ext import six - log = logging.getLogger(__name__) @@ -90,7 +85,7 @@ def downloaded( if "test" in __opts__ and __opts__["test"] is True: fetch_result = {} fetch_result["status"] = True - fetch_result["comment"] = "Artifact would be downloaded from URL: {0}".format( + fetch_result["comment"] = "Artifact would be downloaded from URL: {}".format( artifact["artifactory_url"] ) fetch_result["changes"] = {} @@ -101,7 +96,7 @@ def downloaded( ) except Exception as exc: # pylint: disable=broad-except ret["result"] = False - ret["comment"] = six.text_type(exc) + ret["comment"] = str(exc) return ret log.debug("fetch_result = %s", fetch_result) diff --git a/salt/states/augeas.py b/salt/states/augeas.py index 8ae61b04573..a940f4c1db6 100644 --- a/salt/states/augeas.py +++ b/salt/states/augeas.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Configuration management using Augeas @@ -27,20 +26,15 @@ Augeas_ can be used to manage configuration files. known to resolve the issue. """ -from __future__ import absolute_import, print_function, unicode_literals import difflib import logging import os.path - -# Import python libs import re -# Import Salt libs import salt.utils.args import salt.utils.files import salt.utils.stringutils -from salt.ext import six from salt.modules.augeas_cfg import METHOD_MAP log = logging.getLogger(__name__) @@ -76,7 +70,7 @@ def _check_filepath(changes): cmd, arg = change_.split(" ", 1) if cmd not in METHOD_MAP: - error = "Command {0} is not supported (yet)".format(cmd) + error = "Command {} is not supported (yet)".format(cmd) raise ValueError(error) method = METHOD_MAP[cmd] parts = salt.utils.args.shlex_split(arg) @@ -88,7 +82,7 @@ def _check_filepath(changes): error = ( "Changes should be prefixed with " "/files if no context is provided," - " change: {0}".format(change_) + " change: {}".format(change_) ) raise ValueError(error) filename_ = re.sub("^/files|/$", "", filename_) @@ -97,7 +91,7 @@ def _check_filepath(changes): error = ( "Changes should be made to one " "file at a time, detected changes " - "to {0} and {1}".format(filename, filename_) + "to {} and {}".format(filename, filename_) ) raise ValueError(error) filename = filename_ @@ -106,10 +100,10 @@ def _check_filepath(changes): if "error" not in locals(): error = ( "Invalid formatted command, " - "see debug log for details: {0}".format(change_) + "see debug log for details: {}".format(change_) ) else: - error = six.text_type(err) + error = str(err) raise ValueError(error) filename = _workout_filename(filename) @@ -281,7 +275,7 @@ def change(name, context=None, changes=None, lens=None, load_path=None, **kwargs try: filename = _check_filepath(changes) except ValueError as err: - ret["comment"] = "Error: {0}".format(err) + ret["comment"] = "Error: {}".format(err) return ret else: filename = re.sub("^/files|/$", "", context) @@ -290,7 +284,7 @@ def change(name, context=None, changes=None, lens=None, load_path=None, **kwargs ret["result"] = True ret["comment"] = "Executing commands" if context: - ret["comment"] += ' in file "{0}":\n'.format(context) + ret["comment"] += ' in file "{}":\n'.format(context) ret["comment"] += "\n".join(changes) return ret @@ -305,7 +299,7 @@ def change(name, context=None, changes=None, lens=None, load_path=None, **kwargs ret["result"] = result["retval"] if ret["result"] is False: - ret["comment"] = "Error: {0}".format(result["error"]) + ret["comment"] = "Error: {}".format(result["error"]) return ret if filename is not None and os.path.isfile(filename): diff --git a/salt/states/bigip.py b/salt/states/bigip.py index 4efc96dbd06..f70740665e6 100644 --- a/salt/states/bigip.py +++ b/salt/states/bigip.py @@ -1,19 +1,12 @@ -# -*- coding: utf-8 -*- """ A state module designed to enforce load-balancing configurations for F5 Big-IP entities. :maturity: develop :platform: f5_bigip_11.6 """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals -# Import Salt libs import salt.utils.json -# Import 3rd-party libs -from salt.ext import six - # set up virtual function def __virtual__(): @@ -61,7 +54,7 @@ def _strip_key(dictionary, keyword): when there were no changes made to the entity. """ - for key, value in six.iteritems(dictionary): + for key, value in dictionary.items(): if key == keyword: dictionary[key] = None elif isinstance(value, dict): @@ -2775,7 +2768,7 @@ def create_monitor(hostname, username, password, monitor_type, name, **kwargs): "name": name, } - for key, value in six.iteritems(kwargs): + for key, value in kwargs.items(): params[key] = value return _test_output(ret, "create", params) @@ -2846,7 +2839,7 @@ def manage_monitor(hostname, username, password, monitor_type, name, **kwargs): "name": name, } - for key, value in six.iteritems(kwargs): + for key, value in kwargs.items(): params[key] = value return _test_output(ret, "manage", params) @@ -2927,7 +2920,7 @@ def modify_monitor(hostname, username, password, monitor_type, name, **kwargs): "name": name, } - for key, value in six.iteritems(kwargs): + for key, value in kwargs.items(): params[key] = value return _test_output(ret, "modify", params) @@ -3176,7 +3169,7 @@ def manage_profile(hostname, username, password, profile_type, name, **kwargs): "name": name, } - for key, value in six.iteritems(kwargs): + for key, value in kwargs.items(): params[key] = value return _test_output(ret, "manage", params) @@ -3257,7 +3250,7 @@ def modify_profile(hostname, username, password, profile_type, name, **kwargs): "name": name, } - for key, value in six.iteritems(kwargs): + for key, value in kwargs.items(): params[key] = value return _test_output(ret, "modify", params) diff --git a/salt/states/blockdev.py b/salt/states/blockdev.py index 3c52584c68d..2fc7ba46c3c 100644 --- a/salt/states/blockdev.py +++ b/salt/states/blockdev.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of Block Devices @@ -20,18 +19,13 @@ A state module to manage blockdevices .. versionadded:: 2014.7.0 """ -from __future__ import absolute_import, print_function, unicode_literals import logging - -# Import python libs import os import os.path import time -# Import salt libs import salt.utils.path -from salt.ext.six.moves import range __virtualname__ = "blockdev" @@ -48,7 +42,7 @@ def __virtual__(): return ( False, ( - "Cannot load the {0} state module: " + "Cannot load the {} state module: " "disk execution module not found".format(__virtualname__) ), ) @@ -86,10 +80,10 @@ def tuned(name, **kwargs): if not __salt__["file.is_blkdev"]: ret["comment"] = ( - "Changes to {0} cannot be applied. " "Not a block device. " + "Changes to {} cannot be applied. " "Not a block device. " ).format(name) elif __opts__["test"]: - ret["comment"] = "Changes to {0} will be applied ".format(name) + ret["comment"] = "Changes to {} will be applied ".format(name) ret["result"] = None return ret else: @@ -109,19 +103,17 @@ def tuned(name, **kwargs): if key == "read-write": old = not old new = not new - changeset[key] = "Changed from {0} to {1}".format(old, new) + changeset[key] = "Changed from {} to {}".format(old, new) if changes: if changeset: - ret["comment"] = ("Block device {0} " "successfully modified ").format( + ret["comment"] = ("Block device {} " "successfully modified ").format( name ) ret["changes"] = changeset else: - ret["comment"] = "Block device {0} already in correct state".format( - name - ) + ret["comment"] = "Block device {} already in correct state".format(name) else: - ret["comment"] = "Failed to modify block device {0}".format(name) + ret["comment"] = "Failed to modify block device {}".format(name) ret["result"] = False return ret @@ -147,13 +139,13 @@ def formatted(name, fs_type="ext4", force=False, **kwargs): """ ret = { "changes": {}, - "comment": "{0} already formatted with {1}".format(name, fs_type), + "comment": "{} already formatted with {}".format(name, fs_type), "name": name, "result": False, } if not os.path.exists(name): - ret["comment"] = "{0} does not exist".format(name) + ret["comment"] = "{} does not exist".format(name) return ret current_fs = _checkblk(name) @@ -161,12 +153,12 @@ def formatted(name, fs_type="ext4", force=False, **kwargs): if current_fs == fs_type: ret["result"] = True return ret - elif not salt.utils.path.which("mkfs.{0}".format(fs_type)): - ret["comment"] = "Invalid fs_type: {0}".format(fs_type) + elif not salt.utils.path.which("mkfs.{}".format(fs_type)): + ret["comment"] = "Invalid fs_type: {}".format(fs_type) ret["result"] = False return ret elif __opts__["test"]: - ret["comment"] = "Changes to {0} will be applied ".format(name) + ret["comment"] = "Changes to {} will be applied ".format(name) ret["result"] = None return ret @@ -182,9 +174,7 @@ def formatted(name, fs_type="ext4", force=False, **kwargs): current_fs = _checkblk(name) if current_fs == fs_type: - ret["comment"] = ("{0} has been formatted " "with {1}").format( - name, fs_type - ) + ret["comment"] = ("{} has been formatted " "with {}").format(name, fs_type) ret["changes"] = {"new": fs_type, "old": current_fs} ret["result"] = True return ret @@ -195,7 +185,7 @@ def formatted(name, fs_type="ext4", force=False, **kwargs): else: break - ret["comment"] = "Failed to format {0}".format(name) + ret["comment"] = "Failed to format {}".format(name) ret["result"] = False return ret diff --git a/salt/states/boto3_elasticache.py b/salt/states/boto3_elasticache.py index 0eea912ed2f..759a45cd8f1 100644 --- a/salt/states/boto3_elasticache.py +++ b/salt/states/boto3_elasticache.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage Elasticache with boto3 ============================= @@ -88,9 +87,6 @@ passed in as a dict, or as a string to pull from pillars or minion config: key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals - def __virtual__(): """ @@ -428,7 +424,7 @@ def cache_cluster_present( contains a dict with region, key and keyid. """ ret = {"name": name, "result": True, "comment": "", "changes": {}} - args = dict([(k, v) for k, v in args.items() if not k.startswith("_")]) + args = {k: v for k, v in args.items() if not k.startswith("_")} current = __salt__["boto3_elasticache." "describe_cache_clusters"]( name, region=region, key=key, keyid=keyid, profile=profile ) @@ -448,7 +444,7 @@ def cache_cluster_present( else: create_args[k] = v if __opts__["test"]: - ret["comment"] = "Cache cluster {0} would be created.".format(name) + ret["comment"] = "Cache cluster {} would be created.".format(name) ret["result"] = None return ret created = __salt__["boto3_elasticache." "create_cache_cluster"]( @@ -465,12 +461,12 @@ def cache_cluster_present( new = __salt__["boto3_elasticache." "describe_cache_clusters"]( name, region=region, key=key, keyid=keyid, profile=profile ) - ret["comment"] = "Cache cluster {0} was created.".format(name) + ret["comment"] = "Cache cluster {} was created.".format(name) ret["changes"]["old"] = None ret["changes"]["new"] = new[0] else: ret["result"] = False - ret["comment"] = "Failed to create {0} cache cluster.".format(name) + ret["comment"] = "Failed to create {} cache cluster.".format(name) if check_update: # Refresh this in case we're updating from 'only_on_modify' above... @@ -480,7 +476,7 @@ def cache_cluster_present( need_update = _diff_cache_cluster(updated["CacheClusters"][0], args) if need_update: if __opts__["test"]: - ret["comment"] = "Cache cluster {0} would be modified.".format(name) + ret["comment"] = "Cache cluster {} would be modified.".format(name) ret["result"] = None return ret modified = __salt__["boto3_elasticache." "modify_cache_cluster"]( @@ -500,14 +496,14 @@ def cache_cluster_present( if ret["comment"]: # 'create' just ran... ret["comment"] += " ... and then immediately modified." else: - ret["comment"] = "Cache cluster {0} was modified.".format(name) + ret["comment"] = "Cache cluster {} was modified.".format(name) ret["changes"]["old"] = current ret["changes"]["new"] = new[0] else: ret["result"] = False - ret["comment"] = "Failed to modify cache cluster {0}.".format(name) + ret["comment"] = "Failed to modify cache cluster {}.".format(name) else: - ret["comment"] = "Cache cluster {0} is in the desired state.".format(name) + ret["comment"] = "Cache cluster {} is in the desired state.".format(name) return ret @@ -550,13 +546,13 @@ def cache_cluster_absent( that contains a dict with region, key and keyid. """ ret = {"name": name, "result": True, "comment": "", "changes": {}} - args = dict([(k, v) for k, v in args.items() if not k.startswith("_")]) + args = {k: v for k, v in args.items() if not k.startswith("_")} exists = __salt__["boto3_elasticache." "cache_cluster_exists"]( name, region=region, key=key, keyid=keyid, profile=profile ) if exists: if __opts__["test"]: - ret["comment"] = "Cache cluster {0} would be removed.".format(name) + ret["comment"] = "Cache cluster {} would be removed.".format(name) ret["result"] = None return ret deleted = __salt__["boto3_elasticache." "delete_cache_cluster"]( @@ -573,9 +569,9 @@ def cache_cluster_absent( ret["changes"]["new"] = None else: ret["result"] = False - ret["comment"] = "Failed to delete {0} cache cluster.".format(name) + ret["comment"] = "Failed to delete {} cache cluster.".format(name) else: - ret["comment"] = "Cache cluster {0} already absent.".format(name) + ret["comment"] = "Cache cluster {} already absent.".format(name) return ret @@ -884,7 +880,7 @@ def replication_group_present( that contains a dict with region, key and keyid. """ ret = {"name": name, "result": True, "comment": "", "changes": {}} - args = dict([(k, v) for k, v in args.items() if not k.startswith("_")]) + args = {k: v for k, v in args.items() if not k.startswith("_")} current = __salt__["boto3_elasticache." "describe_replication_groups"]( name, region=region, key=key, keyid=keyid, profile=profile ) @@ -900,7 +896,7 @@ def replication_group_present( else: create_args[k] = v if __opts__["test"]: - ret["comment"] = "Replication group {0} would be created.".format(name) + ret["comment"] = "Replication group {} would be created.".format(name) ret["result"] = None return ret created = __salt__["boto3_elasticache." "create_replication_group"]( @@ -917,12 +913,12 @@ def replication_group_present( new = __salt__["boto3_elasticache." "describe_replication_groups"]( name, region=region, key=key, keyid=keyid, profile=profile ) - ret["comment"] = "Replication group {0} was created.".format(name) + ret["comment"] = "Replication group {} was created.".format(name) ret["changes"]["old"] = None ret["changes"]["new"] = new[0] else: ret["result"] = False - ret["comment"] = "Failed to create {0} replication group.".format(name) + ret["comment"] = "Failed to create {} replication group.".format(name) if check_update: # Refresh this in case we're updating from 'only_on_modify' above... @@ -932,7 +928,7 @@ def replication_group_present( need_update = _diff_replication_group(updated, args) if need_update: if __opts__["test"]: - ret["comment"] = "Replication group {0} would be modified.".format(name) + ret["comment"] = "Replication group {} would be modified.".format(name) ret["result"] = None return ret modified = __salt__["boto3_elasticache." "modify_replication_group"]( @@ -952,14 +948,14 @@ def replication_group_present( if ret["comment"]: # 'create' just ran... ret["comment"] += " ... and then immediately modified." else: - ret["comment"] = "Replication group {0} was modified.".format(name) + ret["comment"] = "Replication group {} was modified.".format(name) ret["changes"]["old"] = current[0] if current else None ret["changes"]["new"] = new[0] else: ret["result"] = False - ret["comment"] = "Failed to modify replication group {0}.".format(name) + ret["comment"] = "Failed to modify replication group {}.".format(name) else: - ret["comment"] = "Replication group {0} is in the desired state.".format( + ret["comment"] = "Replication group {} is in the desired state.".format( name ) return ret @@ -1008,13 +1004,13 @@ def replication_group_absent( that contains a dict with region, key and keyid. """ ret = {"name": name, "result": True, "comment": "", "changes": {}} - args = dict([(k, v) for k, v in args.items() if not k.startswith("_")]) + args = {k: v for k, v in args.items() if not k.startswith("_")} exists = __salt__["boto3_elasticache." "replication_group_exists"]( name, region=region, key=key, keyid=keyid, profile=profile ) if exists: if __opts__["test"]: - ret["comment"] = "Replication group {0} would be removed.".format(name) + ret["comment"] = "Replication group {} would be removed.".format(name) ret["result"] = None return ret deleted = __salt__["boto3_elasticache." "delete_replication_group"]( @@ -1031,9 +1027,9 @@ def replication_group_absent( ret["changes"]["new"] = None else: ret["result"] = False - ret["comment"] = "Failed to delete {0} replication group.".format(name) + ret["comment"] = "Failed to delete {} replication group.".format(name) else: - ret["comment"] = "Replication group {0} already absent.".format(name) + ret["comment"] = "Replication group {} already absent.".format(name) return ret @@ -1108,7 +1104,7 @@ def cache_subnet_group_present( contains a dict with region, key and keyid. """ ret = {"name": name, "result": True, "comment": "", "changes": {}} - args = dict([(k, v) for k, v in args.items() if not k.startswith("_")]) + args = {k: v for k, v in args.items() if not k.startswith("_")} current = __salt__["boto3_elasticache." "describe_cache_subnet_groups"]( name, region=region, key=key, keyid=keyid, profile=profile ) @@ -1117,7 +1113,7 @@ def cache_subnet_group_present( else: check_update = False if __opts__["test"]: - ret["comment"] = "Cache subnet group {0} would be created.".format(name) + ret["comment"] = "Cache subnet group {} would be created.".format(name) ret["result"] = None return ret created = __salt__["boto3_elasticache." "create_cache_subnet_group"]( @@ -1133,20 +1129,18 @@ def cache_subnet_group_present( new = __salt__["boto3_elasticache." "describe_cache_subnet_groups"]( name, region=region, key=key, keyid=keyid, profile=profile ) - ret["comment"] = "Cache subnet group {0} was created.".format(name) + ret["comment"] = "Cache subnet group {} was created.".format(name) ret["changes"]["old"] = None ret["changes"]["new"] = new[0] else: ret["result"] = False - ret["comment"] = "Failed to create {0} cache subnet group.".format(name) + ret["comment"] = "Failed to create {} cache subnet group.".format(name) if check_update: need_update = _diff_cache_subnet_group(current, args) if need_update: if __opts__["test"]: - ret["comment"] = "Cache subnet group {0} would be modified.".format( - name - ) + ret["comment"] = "Cache subnet group {} would be modified.".format(name) ret["result"] = None return ret modified = __salt__["boto3_elasticache." "modify_cache_subnet_group"]( @@ -1162,14 +1156,14 @@ def cache_subnet_group_present( new = __salt__["boto3_elasticache." "describe_cache_subnet_groups"]( name, region=region, key=key, keyid=keyid, profile=profile ) - ret["comment"] = "Cache subnet group {0} was modified.".format(name) + ret["comment"] = "Cache subnet group {} was modified.".format(name) ret["changes"]["old"] = current["CacheSubetGroups"][0] ret["changes"]["new"] = new[0] else: ret["result"] = False - ret["comment"] = "Failed to modify cache subnet group {0}.".format(name) + ret["comment"] = "Failed to modify cache subnet group {}.".format(name) else: - ret["comment"] = "Cache subnet group {0} is in the desired state.".format( + ret["comment"] = "Cache subnet group {} is in the desired state.".format( name ) return ret @@ -1202,13 +1196,13 @@ def cache_subnet_group_absent( that contains a dict with region, key and keyid. """ ret = {"name": name, "result": True, "comment": "", "changes": {}} - args = dict([(k, v) for k, v in args.items() if not k.startswith("_")]) + args = {k: v for k, v in args.items() if not k.startswith("_")} exists = __salt__["boto3_elasticache." "cache_subnet_group_exists"]( name, region=region, key=key, keyid=keyid, profile=profile ) if exists: if __opts__["test"]: - ret["comment"] = "Cache subnet group {0} would be removed.".format(name) + ret["comment"] = "Cache subnet group {} would be removed.".format(name) ret["result"] = None return ret deleted = __salt__["boto3_elasticache." "delete_cache_subnet_group"]( @@ -1219,7 +1213,7 @@ def cache_subnet_group_absent( ret["changes"]["new"] = None else: ret["result"] = False - ret["comment"] = "Failed to delete {0} cache_subnet group.".format(name) + ret["comment"] = "Failed to delete {} cache_subnet group.".format(name) else: - ret["comment"] = "Cache subnet group {0} already absent.".format(name) + ret["comment"] = "Cache subnet group {} already absent.".format(name) return ret diff --git a/salt/states/boto3_route53.py b/salt/states/boto3_route53.py index 0b986b5b497..4023d4d58f1 100644 --- a/salt/states/boto3_route53.py +++ b/salt/states/boto3_route53.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage Route53 records with Boto 3 @@ -64,16 +63,12 @@ passed in as a dict, or as a string to pull from pillars or minion config: # pylint: disable=W0106 # pylint: disable=E1320 -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals import logging import uuid import salt.utils.data import salt.utils.dictupdate - -# Import Salt Libs from salt.exceptions import SaltInvocationError log = logging.getLogger(__name__) # pylint: disable=W1699 @@ -188,7 +183,7 @@ def hosted_zone_present( VPCs = [v for v in VPCs if v["region"] == VPCRegion] if not VPCs: ret["comment"] = ( - "A VPC matching given criteria (vpc: {0} / vpc_region: {1}) not " + "A VPC matching given criteria (vpc: {} / vpc_region: {}) not " "found.".format(VPCName or VPCId, VPCRegion) ) log.error(ret["comment"]) @@ -196,8 +191,8 @@ def hosted_zone_present( return ret if len(VPCs) > 1: ret["comment"] = ( - "Multiple VPCs matching given criteria (vpc: {0} / vpc_region: " - "{1}) found: {2}.".format( + "Multiple VPCs matching given criteria (vpc: {} / vpc_region: " + "{}) found: {}.".format( VPCName or VPCId, VPCRegion, ", ".join([v["id"] for v in VPCs]) ) ) @@ -248,7 +243,7 @@ def hosted_zone_present( update_comment = True if not (create or add_vpcs or del_vpcs or update_comment): - ret["comment"] = "Hostd Zone {0} already in desired state".format(Name) + ret["comment"] = "Hostd Zone {} already in desired state".format(Name) return ret if create: diff --git a/salt/states/boto3_sns.py b/salt/states/boto3_sns.py index 513521469da..d58c0a59bee 100644 --- a/salt/states/boto3_sns.py +++ b/salt/states/boto3_sns.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage SNS Topics ================= @@ -62,14 +61,12 @@ Passing in a profile keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs """ -from __future__ import absolute_import, print_function, unicode_literals import copy import logging import re import salt.utils.json -from salt.ext import six log = logging.getLogger(__name__) @@ -138,11 +135,11 @@ def topic_present( something_changed = False current = __salt__["boto3_sns.describe_topic"](name, region, key, keyid, profile) if current: - ret["comment"] = "AWS SNS topic {0} present.".format(name) + ret["comment"] = "AWS SNS topic {} present.".format(name) TopicArn = current["TopicArn"] else: if __opts__["test"]: - ret["comment"] = "AWS SNS topic {0} would be created.".format(name) + ret["comment"] = "AWS SNS topic {} would be created.".format(name) ret["result"] = None return ret else: @@ -150,12 +147,12 @@ def topic_present( name, region=region, key=key, keyid=keyid, profile=profile ) if TopicArn: - ret["comment"] = "AWS SNS topic {0} created with ARN {1}.".format( + ret["comment"] = "AWS SNS topic {} created with ARN {}.".format( name, TopicArn ) something_changed = True else: - ret["comment"] = "Failed to create AWS SNS topic {0}".format(name) + ret["comment"] = "Failed to create AWS SNS topic {}".format(name) log.error(ret["comment"]) ret["result"] = False return ret @@ -177,15 +174,13 @@ def topic_present( if _json_objs_equal(want_val, curr_val): continue if __opts__["test"]: - ret["comment"] += " Attribute {0} would be updated on topic {1}.".format( + ret["comment"] += " Attribute {} would be updated on topic {}.".format( attr, TopicArn ) ret["result"] = None continue want_val = ( - want_val - if isinstance(want_val, six.string_types) - else salt.utils.json.dumps(want_val) + want_val if isinstance(want_val, str) else salt.utils.json.dumps(want_val) ) if __salt__["boto3_sns.set_topic_attributes"]( TopicArn, @@ -196,12 +191,12 @@ def topic_present( keyid=keyid, profile=profile, ): - ret["comment"] += " Attribute {0} set to {1} on topic {2}.".format( + ret["comment"] += " Attribute {} set to {} on topic {}.".format( attr, want_val, TopicArn ) something_changed = True else: - ret["comment"] += " Failed to update {0} on topic {1}.".format( + ret["comment"] += " Failed to update {} on topic {}.".format( attr, TopicArn ) ret["result"] = False @@ -241,7 +236,7 @@ def topic_present( prot = sub["Protocol"] endp = sub["Endpoint"] if __opts__["test"]: - msg = " Subscription {0}:{1} would be set on topic {2}.".format( + msg = " Subscription {}:{} would be set on topic {}.".format( prot, endp, TopicArn ) ret["comment"] += msg @@ -251,11 +246,11 @@ def topic_present( TopicArn, prot, endp, region=region, key=key, keyid=keyid, profile=profile ) if subbed: - msg = " Subscription {0}:{1} set on topic {2}.".format(prot, endp, TopicArn) + msg = " Subscription {}:{} set on topic {}.".format(prot, endp, TopicArn) ret["comment"] += msg something_changed = True else: - msg = " Failed to set subscription {0}:{1} on topic {2}.".format( + msg = " Failed to set subscription {}:{} on topic {}.".format( prot, endp, TopicArn ) ret["comment"] += msg @@ -263,7 +258,7 @@ def topic_present( return ret for sub in unsubscribe: if __opts__["test"]: - msg = " Subscription {0} would be removed from topic {1}.".format( + msg = " Subscription {} would be removed from topic {}.".format( sub, TopicArn ) ret["comment"] += msg @@ -273,12 +268,12 @@ def topic_present( sub, region=region, key=key, keyid=keyid, profile=profile ) if unsubbed: - ret["comment"] += " Subscription {0} removed from topic {1}.".format( + ret["comment"] += " Subscription {} removed from topic {}.".format( sub, TopicArn ) something_changed = True else: - msg = " Failed to remove subscription {0} from topic {1}.".format( + msg = " Failed to remove subscription {} from topic {}.".format( sub, TopicArn ) ret["comment"] += msg @@ -323,13 +318,13 @@ def topic_absent( something_changed = False current = __salt__["boto3_sns.describe_topic"](name, region, key, keyid, profile) if not current: - ret["comment"] = "AWS SNS topic {0} absent.".format(name) + ret["comment"] = "AWS SNS topic {} absent.".format(name) else: TopicArn = current["TopicArn"] if __opts__["test"]: - ret["comment"] = "AWS SNS topic {0} would be removed.".format(TopicArn) + ret["comment"] = "AWS SNS topic {} would be removed.".format(TopicArn) if unsubscribe: - ret["comment"] += " {0} subscription(s) would be removed.".format( + ret["comment"] += " {} subscription(s) would be removed.".format( len(current["Subscriptions"]) ) ret["result"] = None @@ -358,7 +353,7 @@ def topic_absent( else: ret[ "comment" - ] = "Failed to delete subscription {0} for SNS topic {1}".format( + ] = "Failed to delete subscription {} for SNS topic {}".format( sub, TopicArn ) ret["result"] = False @@ -366,15 +361,15 @@ def topic_absent( if not __salt__["boto3_sns.delete_topic"]( TopicArn, region=region, key=key, keyid=keyid, profile=profile ): - ret["comment"] = "Failed to delete SNS topic {0}".format(TopicArn) + ret["comment"] = "Failed to delete SNS topic {}".format(TopicArn) log.error(ret["comment"]) ret["result"] = False else: - ret["comment"] = "AWS SNS topic {0} deleted.".format(TopicArn) + ret["comment"] = "AWS SNS topic {} deleted.".format(TopicArn) if unsubscribe: ret["comment"] += " ".join( [ - "Subscription {0} deleted".format(s) + "Subscription {} deleted".format(s) for s in current["Subscriptions"] ] ) @@ -390,9 +385,9 @@ def topic_absent( def _json_objs_equal(left, right): left = __utils__["boto3.ordered"]( - salt.utils.json.loads(left) if isinstance(left, six.string_types) else left + salt.utils.json.loads(left) if isinstance(left, str) else left ) right = __utils__["boto3.ordered"]( - salt.utils.json.loads(right) if isinstance(right, six.string_types) else right + salt.utils.json.loads(right) if isinstance(right, str) else right ) return left == right diff --git a/salt/states/boto_apigateway.py b/salt/states/boto_apigateway.py index 15fec0b29b1..10e1cb85768 100644 --- a/salt/states/boto_apigateway.py +++ b/salt/states/boto_apigateway.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage Apigateway Rest APIs =========================== @@ -51,22 +50,16 @@ config: """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals import hashlib import logging import os import re -# Import Salt Libs import salt.utils.files import salt.utils.json import salt.utils.yaml -# Import 3rd-party libs -from salt.ext import six - log = logging.getLogger(__name__) @@ -297,11 +290,11 @@ def present( # just reassociate the stage_name to the given deployment label. if __opts__["test"]: ret["comment"] = ( - "[stage: {0}] will be reassociated to an already available " - "deployment that matched the given [api_name: {1}] " - "and [swagger_file: {2}].\n" + "[stage: {}] will be reassociated to an already available " + "deployment that matched the given [api_name: {}] " + "and [swagger_file: {}].\n" "Stage variables will be set " - "to {3}.".format(stage_name, api_name, swagger_file, stage_vars) + "to {}.".format(stage_name, api_name, swagger_file, stage_vars) ) ret["result"] = None return ret @@ -311,11 +304,11 @@ def present( # already at desired state for the stage, swagger_file, and api_name if __opts__["test"]: ret["comment"] = ( - "[stage: {0}] is already at desired state with an associated " - "deployment matching the given [api_name: {1}] " - "and [swagger_file: {2}].\n" + "[stage: {}] is already at desired state with an associated " + "deployment matching the given [api_name: {}] " + "and [swagger_file: {}].\n" "Stage variables will be set " - "to {3}.".format(stage_name, api_name, swagger_file, stage_vars) + "to {}.".format(stage_name, api_name, swagger_file, stage_vars) ) ret["result"] = None return swagger.overwrite_stage_variables(ret, stage_vars) @@ -325,12 +318,12 @@ def present( # and finally create a new deployment and tie the stage_name to this new deployment if __opts__["test"]: ret["comment"] = ( - "There is no deployment matching the given [api_name: {0}] " - "and [swagger_file: {1}]. A new deployment will be " - "created and the [stage_name: {2}] will then be associated " + "There is no deployment matching the given [api_name: {}] " + "and [swagger_file: {}]. A new deployment will be " + "created and the [stage_name: {}] will then be associated " "to the newly created deployment.\n" "Stage variables will be set " - "to {3}.".format(api_name, swagger_file, stage_name, stage_vars) + "to {}.".format(api_name, swagger_file, stage_name, stage_vars) ) ret["result"] = None return ret @@ -355,9 +348,9 @@ def present( ret = swagger.publish_api(ret, stage_vars) - except (ValueError, IOError) as e: + except (ValueError, OSError) as e: ret["result"] = False - ret["comment"] = "{0}".format(e.args) + ret["comment"] = "{}".format(e.args) return ret @@ -371,7 +364,7 @@ def _get_stage_variables(stage_variables): if stage_variables is None: return ret - if isinstance(stage_variables, six.string_types): + if isinstance(stage_variables, str): if stage_variables in __opts__: ret = __opts__[stage_variables] master_opts = __pillar__.get("master", {}) @@ -442,18 +435,18 @@ def absent( swagger = _Swagger(api_name, stage_name, "", None, None, None, common_args) if not swagger.restApiId: - ret["comment"] = "[Rest API: {0}] does not exist.".format(api_name) + ret["comment"] = "[Rest API: {}] does not exist.".format(api_name) return ret if __opts__["test"]: if nuke_api: ret["comment"] = ( - "[stage: {0}] will be deleted, if there are no other " - "active stages, the [api: {1} will also be " + "[stage: {}] will be deleted, if there are no other " + "active stages, the [api: {} will also be " "deleted.".format(stage_name, api_name) ) else: - ret["comment"] = "[stage: {0}] will be deleted.".format(stage_name) + ret["comment"] = "[stage: {}] will be deleted.".format(stage_name) ret["result"] = None return ret @@ -465,9 +458,9 @@ def absent( if nuke_api and swagger.no_more_deployments_remain(): ret = swagger.delete_api(ret) - except (ValueError, IOError) as e: + except (ValueError, OSError) as e: ret["result"] = False - ret["comment"] = "{0}".format(e.args) + ret["comment"] = "{}".format(e.args) return ret @@ -485,7 +478,7 @@ def _gen_md5_filehash(fname, *args): _hash.update(chunk) for extra_arg in args: - _hash.update(six.b(str(extra_arg))) + _hash.update(str(extra_arg).encode()) return _hash.hexdigest() @@ -536,7 +529,7 @@ def _object_reducer( """ result = {} if isinstance(o, dict): - for k, v in six.iteritems(o): + for k, v in o.items(): if isinstance(v, dict): reduced = v if k == "variables" else _object_reducer(v, names) if reduced or _name_matches(k, names): @@ -572,11 +565,11 @@ def _log_error_and_abort(ret, obj): ret["result"] = False ret["abort"] = True if "error" in obj: - ret["comment"] = "{0}".format(obj.get("error")) + ret["comment"] = "{}".format(obj.get("error")) return ret -class _Swagger(object): +class _Swagger: """ this is a helper class that holds the swagger definition file and the associated logic related to how to interpret the file and apply it to AWS Api Gateway. @@ -716,7 +709,7 @@ class _Swagger(object): } ) - class SwaggerParameter(object): + class SwaggerParameter: """ This is a helper class for the Swagger Parameter Object """ @@ -735,7 +728,7 @@ class _Swagger(object): if _location in _Swagger.SwaggerParameter.LOCATIONS: return _location raise ValueError( - "Unsupported parameter location: {0} in Parameter Object".format( + "Unsupported parameter location: {} in Parameter Object".format( _location ) ) @@ -748,14 +741,14 @@ class _Swagger(object): _name = self._paramdict.get("name") if _name: if self.location == "header": - return "method.request.header.{0}".format(_name) + return "method.request.header.{}".format(_name) elif self.location == "query": - return "method.request.querystring.{0}".format(_name) + return "method.request.querystring.{}".format(_name) elif self.location == "path": - return "method.request.path.{0}".format(_name) + return "method.request.path.{}".format(_name) return None raise ValueError( - "Parameter must have a name: {0}".format( + "Parameter must have a name: {}".format( _dict_to_json_pretty(self._paramdict) ) ) @@ -772,19 +765,17 @@ class _Swagger(object): schema_name = _schema.get("$ref").split("/")[-1] return schema_name raise ValueError( - ( - "Body parameter must have a JSON reference " - "to the schema definition due to Amazon API restrictions: {0}".format( - self.name - ) + "Body parameter must have a JSON reference " + "to the schema definition due to Amazon API restrictions: {}".format( + self.name ) ) raise ValueError( - "Body parameter must have a schema: {0}".format(self.name) + "Body parameter must have a schema: {}".format(self.name) ) return None - class SwaggerMethodResponse(object): + class SwaggerMethodResponse: """ Helper class for Swagger Method Response Object """ @@ -802,10 +793,8 @@ class _Swagger(object): if "$ref" in _schema: return _schema.get("$ref").split("/")[-1] raise ValueError( - ( - "Method response must have a JSON reference " - "to the schema definition: {0}".format(_schema) - ) + "Method response must have a JSON reference " + "to the schema definition: {}".format(_schema) ) return None @@ -846,9 +835,7 @@ class _Swagger(object): self._cfg = salt.utils.yaml.safe_load(sf) self._swagger_version = "" else: - raise IOError( - "Invalid swagger file path, {0}".format(swagger_file_path) - ) + raise OSError("Invalid swagger file path, {}".format(swagger_file_path)) self._validate_swagger_file() @@ -869,7 +856,7 @@ class _Swagger(object): to handle response code mapping/integration """ for path, ops in paths: - for opname, opobj in six.iteritems(ops): + for opname, opobj in ops.items(): if opname not in _Swagger.SWAGGER_OPERATION_NAMES: continue @@ -877,7 +864,7 @@ class _Swagger(object): raise ValueError( "missing mandatory responses field in path item object" ) - for rescode, resobj in six.iteritems(opobj.get("responses")): + for rescode, resobj in opobj.get("responses").items(): if not self._is_http_error_rescode( str(rescode) ): # future lint: disable=blacklisted-function @@ -886,35 +873,33 @@ class _Swagger(object): # only check for response code from 400-599 if "schema" not in resobj: raise ValueError( - "missing schema field in path {0}, " - "op {1}, response {2}".format(path, opname, rescode) + "missing schema field in path {}, " + "op {}, response {}".format(path, opname, rescode) ) schemaobj = resobj.get("schema") if "$ref" not in schemaobj: raise ValueError( "missing $ref field under schema in " - "path {0}, op {1}, response {2}".format( - path, opname, rescode - ) + "path {}, op {}, response {}".format(path, opname, rescode) ) schemaobjref = schemaobj.get("$ref", "/") modelname = schemaobjref.split("/")[-1] if modelname not in mods: raise ValueError( - "model schema {0} reference not found " + "model schema {} reference not found " "under /definitions".format(schemaobjref) ) model = mods.get(modelname) if model.get("type") != "object": raise ValueError( - "model schema {0} must be type object".format(modelname) + "model schema {} must be type object".format(modelname) ) if "properties" not in model: raise ValueError( - "model schema {0} must have properties fields".format( + "model schema {} must have properties fields".format( modelname ) ) @@ -922,7 +907,7 @@ class _Swagger(object): modelprops = model.get("properties") if "errorMessage" not in modelprops: raise ValueError( - "model schema {0} must have errorMessage as a property to " + "model schema {} must have errorMessage as a property to " "match AWS convention. If pattern is not set, .+ will " "be used".format(modelname) ) @@ -939,7 +924,7 @@ class _Swagger(object): return True except Exception: # pylint: disable=broad-except raise ValueError( - "Invalid lambda_funcname_format {0}. Please review " + "Invalid lambda_funcname_format {}. Please review " "documentation for known substitutable keys".format( self._lambda_funcname_format ) @@ -961,19 +946,19 @@ class _Swagger(object): field not in _Swagger.SWAGGER_OBJ_V2_FIELDS and not _Swagger.VENDOR_EXT_PATTERN.match(field) ): - raise ValueError("Invalid Swagger Object Field: {0}".format(field)) + raise ValueError("Invalid Swagger Object Field: {}".format(field)) # check for Required Swagger fields by Saltstack boto apigateway state for field in _Swagger.SWAGGER_OBJ_V2_FIELDS_REQUIRED: if field not in self._cfg: - raise ValueError("Missing Swagger Object Field: {0}".format(field)) + raise ValueError("Missing Swagger Object Field: {}".format(field)) # check for Swagger Version self._swagger_version = self._cfg.get("swagger") if self._swagger_version not in _Swagger.SWAGGER_VERSIONS_SUPPORTED: raise ValueError( - "Unsupported Swagger version: {0}," - "Supported versions are {1}".format( + "Unsupported Swagger version: {}," + "Supported versions are {}".format( self._swagger_version, _Swagger.SWAGGER_VERSIONS_SUPPORTED ) ) @@ -1059,9 +1044,9 @@ class _Swagger(object): for path in paths: if not path.startswith("/"): raise ValueError( - "Path object {0} should start with /. Please fix it".format(path) + "Path object {} should start with /. Please fix it".format(path) ) - return six.iteritems(paths) + return paths.items() @property def basePath(self): @@ -1252,8 +1237,8 @@ class _Swagger(object): self.restApiId = apis[0].get("id") else: raise ValueError( - "Multiple APIs matching given name {0} and " - "description {1}".format(self.rest_api_name, self.info_json) + "Multiple APIs matching given name {} and " + "description {}".format(self.rest_api_name, self.info_json) ) def delete_stage(self, ret): @@ -1272,7 +1257,7 @@ class _Swagger(object): if not result.get("deleted"): ret["abort"] = True ret["result"] = False - ret["comment"] = "delete_stage delete_api_stage, {0}".format( + ret["comment"] = "delete_stage delete_api_stage, {}".format( result.get("error") ) else: @@ -1288,16 +1273,16 @@ class _Swagger(object): ret["result"] = False ret[ "comment" - ] = "delete_stage delete_api_deployment, {0}".format( + ] = "delete_stage delete_api_deployment, {}".format( result.get("error") ) else: - ret["comment"] = "stage {0} has been deleted.\n".format( + ret["comment"] = "stage {} has been deleted.\n".format( self._stage_name ) else: # no matching stage_name/deployment found - ret["comment"] = "stage {0} does not exist".format(self._stage_name) + ret["comment"] = "stage {} does not exist".format(self._stage_name) return ret @@ -1316,8 +1301,8 @@ class _Swagger(object): deployed_label_json = self._get_current_deployment_label() if deployed_label_json == self.deployment_label_json: ret["comment"] = ( - "Already at desired state, the stage {0} is already at the desired " - "deployment label:\n{1}".format( + "Already at desired state, the stage {} is already at the desired " + "deployment label:\n{}".format( self._stage_name, deployed_label_json ) ) @@ -1412,9 +1397,7 @@ class _Swagger(object): if self.restApiId: res = self._cleanup_api() if not res.get("deleted"): - ret["comment"] = "Failed to cleanup restAreId {0}".format( - self.restApiId - ) + ret["comment"] = "Failed to cleanup restAreId {}".format(self.restApiId) ret["abort"] = True ret["result"] = False return ret @@ -1430,7 +1413,7 @@ class _Swagger(object): ret["result"] = False ret["abort"] = True if "error" in response: - ret["comment"] = "Failed to create rest api: {0}.".format( + ret["comment"] = "Failed to create rest api: {}.".format( response["error"]["message"] ) return ret @@ -1454,7 +1437,7 @@ class _Swagger(object): ) if exists_response.get("exists"): if __opts__["test"]: - ret["comment"] = "Rest API named {0} is set to be deleted.".format( + ret["comment"] = "Rest API named {} is set to be deleted.".format( self.rest_api_name ) ret["result"] = None @@ -1470,7 +1453,7 @@ class _Swagger(object): ret["result"] = False ret["abort"] = True if "error" in delete_api_response: - ret["comment"] = "Failed to delete rest api: {0}.".format( + ret["comment"] = "Failed to delete rest api: {}.".format( delete_api_response["error"]["message"] ) return ret @@ -1479,7 +1462,7 @@ class _Swagger(object): else: ret["comment"] = ( "api already absent for swagger file: " - "{0}, desc: {1}".format(self.rest_api_name, self.info_json) + "{}, desc: {}".format(self.rest_api_name, self.info_json) ) return ret @@ -1489,7 +1472,7 @@ class _Swagger(object): Helper function to reference models created on aws apigw """ model_name = r.split("/")[-1] - return "https://apigateway.amazonaws.com/restapis/{0}/models/{1}".format( + return "https://apigateway.amazonaws.com/restapis/{}/models/{}".format( self.restApiId, model_name ) @@ -1529,7 +1512,7 @@ class _Swagger(object): # need to walk each property object properties = obj_schema.get("properties") if properties: - for _, prop_obj_schema in six.iteritems(properties): + for _, prop_obj_schema in properties.items(): dep_models_list.extend( self._build_dependent_model_list(prop_obj_schema) ) @@ -1540,7 +1523,7 @@ class _Swagger(object): Helper function to build a map of model to their list of model reference dependencies """ ret = {} - for model, schema in six.iteritems(self._models()): + for model, schema in self._models().items(): dep_list = self._build_dependent_model_list(schema) ret[model] = dep_list return ret @@ -1553,7 +1536,7 @@ class _Swagger(object): if not models_dict: return next_model - for model, dependencies in six.iteritems(models_dict): + for model, dependencies in models_dict.items(): if dependencies == []: next_model = model break @@ -1561,12 +1544,12 @@ class _Swagger(object): if next_model is None: raise ValueError( "incomplete model definitions, models in dependency " - "list not defined: {0}".format(models_dict) + "list not defined: {}".format(models_dict) ) # remove the model from other depednencies before returning models_dict.pop(next_model) - for model, dep_list in six.iteritems(models_dict): + for model, dep_list in models_dict.items(): if next_model in dep_list: dep_list.remove(next_model) @@ -1587,7 +1570,7 @@ class _Swagger(object): _schema.update( { "$schema": _Swagger.JSON_SCHEMA_DRAFT_4, - "title": "{0} Schema".format(model), + "title": "{} Schema".format(model), } ) @@ -1611,8 +1594,8 @@ class _Swagger(object): ret["abort"] = True if "error" in update_model_schema_response: ret["comment"] = ( - "Failed to update existing model {0} with schema {1}, " - "error: {2}".format( + "Failed to update existing model {} with schema {}, " + "error: {}".format( model, _dict_to_json_pretty(schema), update_model_schema_response["error"]["message"], @@ -1636,8 +1619,8 @@ class _Swagger(object): ret["abort"] = True if "error" in create_model_response: ret["comment"] = ( - "Failed to create model {0}, schema {1}, " - "error: {2}".format( + "Failed to create model {}, schema {}, " + "error: {}".format( model, _dict_to_json_pretty(schema), create_model_response["error"]["message"], @@ -1688,14 +1671,14 @@ class _Swagger(object): if not lambda_desc.get("function"): raise ValueError( - "Could not find lambda function {0} in " - "regions [{1}, {2}].".format(lambda_name, lambda_region, apigw_region) + "Could not find lambda function {} in " + "regions [{}, {}].".format(lambda_name, lambda_region, apigw_region) ) lambda_arn = lambda_desc.get("function").get("FunctionArn") lambda_uri = ( - "arn:aws:apigateway:{0}:lambda:path/2015-03-31" - "/functions/{1}/invocations".format(apigw_region, lambda_arn) + "arn:aws:apigateway:{}:lambda:path/2015-03-31" + "/functions/{}/invocations".format(apigw_region, lambda_arn) ) return lambda_uri @@ -1731,7 +1714,7 @@ class _Swagger(object): def _find_patterns(self, o): result = [] if isinstance(o, dict): - for k, v in six.iteritems(o): + for k, v in o.items(): if isinstance(v, dict): result.extend(self._find_patterns(v)) else: @@ -1779,11 +1762,11 @@ class _Swagger(object): method_response_params = {} method_integration_response_params = {} for header in method_response.headers: - response_header = "method.response.header.{0}".format(header) + response_header = "method.response.header.{}".format(header) method_response_params[response_header] = False header_data = method_response.headers.get(header) method_integration_response_params[response_header] = ( - "'{0}'".format(header_data.get("default")) + "'{}'".format(header_data.get("default")) if "default" in header_data else "'*'" ) @@ -1890,7 +1873,7 @@ class _Swagger(object): ret = _log_changes(ret, "_deploy_method.create_api_integration", integration) if "responses" in method_data: - for response, response_data in six.iteritems(method_data["responses"]): + for response, response_data in method_data["responses"].items(): httpStatus = str(response) # future lint: disable=blacklisted-function method_response = self._parse_method_response( method_name.lower(), @@ -1930,7 +1913,7 @@ class _Swagger(object): ) else: raise ValueError( - "No responses specified for {0} {1}".format(resource_path, method_name) + "No responses specified for {} {}".format(resource_path, method_name) ) return ret @@ -1971,7 +1954,7 @@ class _Swagger(object): ret = _log_error_and_abort(ret, resource) return ret ret = _log_changes(ret, "deploy_resources", resource) - for method, method_data in six.iteritems(pathData): + for method, method_data in pathData.items(): if method in _Swagger.SWAGGER_OPERATION_NAMES: ret = self._deploy_method( ret, @@ -2066,7 +2049,7 @@ def usage_plan_present( if not existing["plans"]: # plan does not exist, we need to create it if __opts__["test"]: - ret["comment"] = "a new usage plan {0} would be created".format( + ret["comment"] = "a new usage plan {} would be created".format( plan_name ) ret["result"] = None @@ -2081,13 +2064,13 @@ def usage_plan_present( ) if "error" in result: ret["result"] = False - ret["comment"] = "Failed to create a usage plan {0}, {1}".format( + ret["comment"] = "Failed to create a usage plan {}, {}".format( plan_name, result["error"] ) return ret ret["changes"]["old"] = {"plan": None} - ret["comment"] = "A new usage plan {0} has been created".format(plan_name) + ret["comment"] = "A new usage plan {} has been created".format(plan_name) else: # need an existing plan modified to match given value @@ -2108,14 +2091,14 @@ def usage_plan_present( break if not needs_updating: - ret["comment"] = "usage plan {0} is already in a correct state".format( + ret["comment"] = "usage plan {} is already in a correct state".format( plan_name ) ret["result"] = True return ret if __opts__["test"]: - ret["comment"] = "a new usage plan {0} would be updated".format( + ret["comment"] = "a new usage plan {} would be updated".format( plan_name ) ret["result"] = None @@ -2126,13 +2109,13 @@ def usage_plan_present( ) if "error" in result: ret["result"] = False - ret["comment"] = "Failed to update a usage plan {0}, {1}".format( + ret["comment"] = "Failed to update a usage plan {}, {}".format( plan_name, result["error"] ) return ret ret["changes"]["old"] = {"plan": plan} - ret["comment"] = "usage plan {0} has been updated".format(plan_name) + ret["comment"] = "usage plan {} has been updated".format(plan_name) newstate = __salt__["boto_apigateway.describe_usage_plans"]( name=plan_name, **common_args @@ -2144,9 +2127,9 @@ def usage_plan_present( ret["changes"]["new"] = {"plan": newstate["plans"][0]} - except (ValueError, IOError) as e: + except (ValueError, OSError) as e: ret["result"] = False - ret["comment"] = "{0}".format(e.args) + ret["comment"] = "{}".format(e.args) return ret @@ -2187,11 +2170,11 @@ def usage_plan_absent(name, plan_name, region=None, key=None, keyid=None, profil return ret if not existing["plans"]: - ret["comment"] = "Usage plan {0} does not exist already".format(plan_name) + ret["comment"] = "Usage plan {} does not exist already".format(plan_name) return ret if __opts__["test"]: - ret["comment"] = "Usage plan {0} exists and would be deleted".format( + ret["comment"] = "Usage plan {} exists and would be deleted".format( plan_name ) ret["result"] = None @@ -2202,18 +2185,18 @@ def usage_plan_absent(name, plan_name, region=None, key=None, keyid=None, profil if "error" in result: ret["result"] = False - ret["comment"] = "Failed to delete usage plan {0}, {1}".format( + ret["comment"] = "Failed to delete usage plan {}, {}".format( plan_name, result ) return ret - ret["comment"] = "Usage plan {0} has been deleted".format(plan_name) + ret["comment"] = "Usage plan {} has been deleted".format(plan_name) ret["changes"]["old"] = {"plan": existing["plans"][0]} ret["changes"]["new"] = {"plan": None} - except (ValueError, IOError) as e: + except (ValueError, OSError) as e: ret["result"] = False - ret["comment"] = "{0}".format(e.args) + ret["comment"] = "{}".format(e.args) return ret @@ -2269,7 +2252,7 @@ def usage_plan_association_present( return ret if not existing["plans"]: - ret["comment"] = "Usage plan {0} does not exist".format(plan_name) + ret["comment"] = "Usage plan {} does not exist".format(plan_name) ret["result"] = False return ret @@ -2299,7 +2282,7 @@ def usage_plan_association_present( if "error" in result: ret[ "comment" - ] = "Failed to associate a usage plan {0} to the apis {1}, {2}".format( + ] = "Failed to associate a usage plan {} to the apis {}, {}".format( plan_name, stages_to_add, result["error"] ) ret["result"] = False @@ -2309,9 +2292,9 @@ def usage_plan_association_present( ret["changes"]["old"] = plan_stages ret["changes"]["new"] = result.get("result", {}).get("apiStages", []) - except (ValueError, IOError) as e: + except (ValueError, OSError) as e: ret["result"] = False - ret["comment"] = "{0}".format(e.args) + ret["comment"] = "{}".format(e.args) return ret @@ -2369,7 +2352,7 @@ def usage_plan_association_absent( return ret if not existing["plans"]: - ret["comment"] = "Usage plan {0} does not exist".format(plan_name) + ret["comment"] = "Usage plan {} does not exist".format(plan_name) ret["result"] = False return ret @@ -2385,7 +2368,7 @@ def usage_plan_association_absent( plan_stages = plan.get("apiStages", []) if not plan_stages: - ret["comment"] = "Usage plan {0} has no associated stages already".format( + ret["comment"] = "Usage plan {} has no associated stages already".format( plan_name ) return ret @@ -2405,7 +2388,7 @@ def usage_plan_association_absent( if "error" in result: ret[ "comment" - ] = "Failed to disassociate a usage plan {0} from the apis {1}, {2}".format( + ] = "Failed to disassociate a usage plan {} from the apis {}, {}".format( plan_name, stages_to_remove, result["error"] ) ret["result"] = False @@ -2415,8 +2398,8 @@ def usage_plan_association_absent( ret["changes"]["old"] = plan_stages ret["changes"]["new"] = result.get("result", {}).get("apiStages", []) - except (ValueError, IOError) as e: + except (ValueError, OSError) as e: ret["result"] = False - ret["comment"] = "{0}".format(e.args) + ret["comment"] = "{}".format(e.args) return ret diff --git a/salt/states/boto_asg.py b/salt/states/boto_asg.py index 140fcc75522..66c844ec225 100644 --- a/salt/states/boto_asg.py +++ b/salt/states/boto_asg.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage Autoscale Groups ======================= @@ -192,18 +191,14 @@ Overriding the alarm values on the resource: threshold: 50.0 """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import copy import hashlib import logging -# Import Salt libs import salt.utils.dictupdate as dictupdate import salt.utils.stringutils from salt.exceptions import SaltInvocationError -from salt.ext import six log = logging.getLogger(__name__) @@ -451,11 +446,11 @@ def present( "subnet", name=i, region=region, key=key, keyid=keyid, profile=profile ) if "error" in r: - ret["comment"] = "Error looking up subnet ids: {0}".format(r["error"]) + ret["comment"] = "Error looking up subnet ids: {}".format(r["error"]) ret["result"] = False return ret if "id" not in r: - ret["comment"] = "Subnet {0} does not exist.".format(i) + ret["comment"] = "Subnet {} does not exist.".format(i) ret["result"] = False return ret vpc_zone_identifier.append(r["id"]) @@ -604,7 +599,7 @@ def present( if "min_adjustment_step" not in policy: policy["min_adjustment_step"] = None if scheduled_actions: - for s_name, action in six.iteritems(scheduled_actions): + for s_name, action in scheduled_actions.items(): if "end_time" not in action: action["end_time"] = None config = { @@ -635,7 +630,7 @@ def present( if scheduled_actions is None: config["scheduled_actions"] = {} # allow defaults on start_time - for s_name, action in six.iteritems(scheduled_actions): + for s_name, action in scheduled_actions.items(): if "start_time" not in action: asg_action = asg["scheduled_actions"].get(s_name, {}) if "start_time" in asg_action: @@ -643,7 +638,7 @@ def present( proposed = {} # note: do not loop using "key, value" - this can modify the value of # the aws access key - for asg_property, value in six.iteritems(config): + for asg_property, value in config.items(): # Only modify values being specified; introspection is difficult # otherwise since it's hard to track default values, which will # always be returned from AWS. @@ -819,7 +814,7 @@ def _alarms_present( tmp = dictupdate.update(tmp, alarms) # set alarms, using boto_cloudwatch_alarm.present merged_return_value = {"name": name, "result": True, "comment": "", "changes": {}} - for _, info in six.iteritems(tmp): + for _, info in tmp.items(): # add asg to name and description info["name"] = name + " " + info["name"] info["attributes"]["description"] = ( @@ -837,7 +832,7 @@ def _alarms_present( if "scaling_policy" not in action: scaling_policy_actions_only = False if ":self:" in action: - action = action.replace(":self:", ":{0}:".format(name)) + action = action.replace(":self:", ":{}:".format(name)) new_actions.append(action) info["attributes"][action_type] = new_actions # skip alarms that only have actions for scaling policy, if min_size == max_size for this ASG @@ -900,7 +895,7 @@ def absent( ret["comment"] = "Autoscale group set to be deleted." ret["result"] = None if remove_lc: - msg = "Launch configuration {0} is set to be deleted.".format( + msg = "Launch configuration {} is set to be deleted.".format( asg["launch_config_name"] ) ret["comment"] = " ".join([ret["comment"], msg]) diff --git a/salt/states/boto_cloudfront.py b/salt/states/boto_cloudfront.py index c046b65d2d6..70536a05c68 100644 --- a/salt/states/boto_cloudfront.py +++ b/salt/states/boto_cloudfront.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage CloudFront distributions @@ -44,8 +43,6 @@ either passed in as a dict, or a string to pull from pillars or minion config: :depends: boto3 """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals import difflib import logging @@ -115,7 +112,7 @@ def present( ) if "error" in res: ret["result"] = False - ret["comment"] = "Error checking distribution {0}: {1}".format( + ret["comment"] = "Error checking distribution {}: {}".format( name, res["error"], ) return ret @@ -124,7 +121,7 @@ def present( if old is None: if __opts__["test"]: ret["result"] = None - ret["comment"] = "Distribution {0} set for creation.".format(name) + ret["comment"] = "Distribution {} set for creation.".format(name) ret["changes"] = {"old": None, "new": name} return ret @@ -133,13 +130,13 @@ def present( ) if "error" in res: ret["result"] = False - ret["comment"] = "Error creating distribution {0}: {1}".format( + ret["comment"] = "Error creating distribution {}: {}".format( name, res["error"], ) return ret ret["result"] = True - ret["comment"] = "Created distribution {0}.".format(name) + ret["comment"] = "Created distribution {}.".format(name) ret["changes"] = {"old": None, "new": name} return ret else: @@ -175,13 +172,13 @@ def present( any_changes = bool("old" in diffed_config or "new" in diffed_config) if not any_changes: ret["result"] = True - ret["comment"] = "Distribution {0} has correct config.".format(name,) + ret["comment"] = "Distribution {} has correct config.".format(name,) return ret if __opts__["test"]: ret["result"] = None ret["comment"] = "\n".join( - ["Distribution {0} set for new config:".format(name), changes_diff] + ["Distribution {} set for new config:".format(name), changes_diff] ) ret["changes"] = {"diff": changes_diff} return ret @@ -191,12 +188,12 @@ def present( ) if "error" in res: ret["result"] = False - ret["comment"] = "Error updating distribution {0}: {1}".format( + ret["comment"] = "Error updating distribution {}: {}".format( name, res["error"], ) return ret ret["result"] = True - ret["comment"] = "Updated distribution {0}.".format(name) + ret["comment"] = "Updated distribution {}.".format(name) ret["changes"] = {"diff": changes_diff} return ret diff --git a/salt/states/boto_cloudtrail.py b/salt/states/boto_cloudtrail.py index ef0ebd04015..5699ef2033d 100644 --- a/salt/states/boto_cloudtrail.py +++ b/salt/states/boto_cloudtrail.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage CloudTrail Objects ========================= @@ -52,8 +51,6 @@ config: """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals import logging import os @@ -61,9 +58,6 @@ import os.path import salt.utils.data -# Import Salt Libs -from salt.ext import six - log = logging.getLogger(__name__) @@ -166,12 +160,12 @@ def present( if "error" in r: ret["result"] = False - ret["comment"] = "Failed to create trail: {0}.".format(r["error"]["message"]) + ret["comment"] = "Failed to create trail: {}.".format(r["error"]["message"]) return ret if not r.get("exists"): if __opts__["test"]: - ret["comment"] = "CloudTrail {0} is set to be created.".format(Name) + ret["comment"] = "CloudTrail {} is set to be created.".format(Name) ret["result"] = None return ret r = __salt__["boto_cloudtrail.create"]( @@ -192,16 +186,14 @@ def present( ) if not r.get("created"): ret["result"] = False - ret["comment"] = "Failed to create trail: {0}.".format( - r["error"]["message"] - ) + ret["comment"] = "Failed to create trail: {}.".format(r["error"]["message"]) return ret _describe = __salt__["boto_cloudtrail.describe"]( Name, region=region, key=key, keyid=keyid, profile=profile ) ret["changes"]["old"] = {"trail": None} ret["changes"]["new"] = _describe - ret["comment"] = "CloudTrail {0} created.".format(Name) + ret["comment"] = "CloudTrail {} created.".format(Name) if LoggingEnabled: r = __salt__["boto_cloudtrail.start_logging"]( @@ -209,7 +201,7 @@ def present( ) if "error" in r: ret["result"] = False - ret["comment"] = "Failed to create trail: {0}.".format( + ret["comment"] = "Failed to create trail: {}.".format( r["error"]["message"] ) ret["changes"] = {} @@ -224,7 +216,7 @@ def present( ) if not r.get("tagged"): ret["result"] = False - ret["comment"] = "Failed to create trail: {0}.".format( + ret["comment"] = "Failed to create trail: {}.".format( r["error"]["message"] ) ret["changes"] = {} @@ -233,7 +225,7 @@ def present( return ret ret["comment"] = os.linesep.join( - [ret["comment"], "CloudTrail {0} is present.".format(Name)] + [ret["comment"], "CloudTrail {} is present.".format(Name)] ) ret["changes"] = {} # trail exists, ensure config matches @@ -242,7 +234,7 @@ def present( ) if "error" in _describe: ret["result"] = False - ret["comment"] = "Failed to update trail: {0}.".format( + ret["comment"] = "Failed to update trail: {}.".format( _describe["error"]["message"] ) ret["changes"] = {} @@ -268,7 +260,7 @@ def present( "LoggingEnabled": "LoggingEnabled", } - for invar, outvar in six.iteritems(bucket_vars): + for invar, outvar in bucket_vars.items(): if _describe[outvar] != locals()[invar]: need_update = True ret["changes"].setdefault("new", {})[invar] = locals()[invar] @@ -286,7 +278,7 @@ def present( if need_update: if __opts__["test"]: - msg = "CloudTrail {0} set to be modified.".format(Name) + msg = "CloudTrail {} set to be modified.".format(Name) ret["comment"] = msg ret["result"] = None return ret @@ -310,9 +302,7 @@ def present( ) if not r.get("updated"): ret["result"] = False - ret["comment"] = "Failed to update trail: {0}.".format( - r["error"]["message"] - ) + ret["comment"] = "Failed to update trail: {}.".format(r["error"]["message"]) ret["changes"] = {} return ret @@ -322,7 +312,7 @@ def present( ) if not r.get("started"): ret["result"] = False - ret["comment"] = "Failed to update trail: {0}.".format( + ret["comment"] = "Failed to update trail: {}.".format( r["error"]["message"] ) ret["changes"] = {} @@ -333,7 +323,7 @@ def present( ) if not r.get("stopped"): ret["result"] = False - ret["comment"] = "Failed to update trail: {0}.".format( + ret["comment"] = "Failed to update trail: {}.".format( r["error"]["message"] ) ret["changes"] = {} @@ -342,7 +332,7 @@ def present( if bool(tagchange): adds = {} removes = {} - for k, diff in six.iteritems(tagchange): + for k, diff in tagchange.items(): if diff.get("new", "") != "": # there's an update for this key adds[k] = Tags[k] @@ -401,15 +391,15 @@ def absent(name, Name, region=None, key=None, keyid=None, profile=None): ) if "error" in r: ret["result"] = False - ret["comment"] = "Failed to delete trail: {0}.".format(r["error"]["message"]) + ret["comment"] = "Failed to delete trail: {}.".format(r["error"]["message"]) return ret if r and not r["exists"]: - ret["comment"] = "CloudTrail {0} does not exist.".format(Name) + ret["comment"] = "CloudTrail {} does not exist.".format(Name) return ret if __opts__["test"]: - ret["comment"] = "CloudTrail {0} is set to be removed.".format(Name) + ret["comment"] = "CloudTrail {} is set to be removed.".format(Name) ret["result"] = None return ret r = __salt__["boto_cloudtrail.delete"]( @@ -417,9 +407,9 @@ def absent(name, Name, region=None, key=None, keyid=None, profile=None): ) if not r["deleted"]: ret["result"] = False - ret["comment"] = "Failed to delete trail: {0}.".format(r["error"]["message"]) + ret["comment"] = "Failed to delete trail: {}.".format(r["error"]["message"]) return ret ret["changes"]["old"] = {"trail": Name} ret["changes"]["new"] = {"trail": None} - ret["comment"] = "CloudTrail {0} deleted.".format(Name) + ret["comment"] = "CloudTrail {} deleted.".format(Name) return ret diff --git a/salt/states/boto_cloudwatch_alarm.py b/salt/states/boto_cloudwatch_alarm.py index 5cabd7713d2..a3737765dff 100644 --- a/salt/states/boto_cloudwatch_alarm.py +++ b/salt/states/boto_cloudwatch_alarm.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage Cloudwatch alarms @@ -53,15 +52,9 @@ as a passed in dict, or as a string to pull from pillars or minion config: - arn:aws:sns:us-east-1:1111111:myalerting-action """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals -# Import Salt libs import salt.utils.data -# Import 3rd-party libs -from salt.ext import six - def __virtual__(): """ @@ -111,15 +104,15 @@ def present(name, attributes, region=None, key=None, keyid=None, profile=None): # AWS type transformations difference = [] if alarm_details: - for k, v in six.iteritems(attributes): + for k, v in attributes.items(): if k not in alarm_details: - difference.append("{0}={1} (new)".format(k, v)) + difference.append("{}={} (new)".format(k, v)) continue v = salt.utils.data.decode(v) v2 = salt.utils.data.decode(alarm_details[k]) if v == v2: continue - if isinstance(v, six.string_types) and v == v2: + if isinstance(v, str) and v == v2: continue if isinstance(v, float) and v == float(v2): continue @@ -127,7 +120,7 @@ def present(name, attributes, region=None, key=None, keyid=None, profile=None): continue if isinstance(v, list) and sorted(v) == sorted(v2): continue - difference.append("{0}='{1}' was: '{2}'".format(k, v, v2)) + difference.append("{}='{}' was: '{}'".format(k, v, v2)) else: difference.append("new alarm") create_or_update_alarm_args = { @@ -141,10 +134,10 @@ def present(name, attributes, region=None, key=None, keyid=None, profile=None): if alarm_details: # alarm is present. update, or do nothing # check to see if attributes matches is_present. If so, do nothing. if len(difference) == 0: - ret["comment"] = "alarm {0} present and matching".format(name) + ret["comment"] = "alarm {} present and matching".format(name) return ret if __opts__["test"]: - msg = "alarm {0} is to be created/updated.".format(name) + msg = "alarm {} is to be created/updated.".format(name) ret["comment"] = msg ret["result"] = None return ret @@ -155,10 +148,10 @@ def present(name, attributes, region=None, key=None, keyid=None, profile=None): ret["changes"]["diff"] = difference else: ret["result"] = False - ret["comment"] = "Failed to create {0} alarm".format(name) + ret["comment"] = "Failed to create {} alarm".format(name) else: # alarm is absent. create it. if __opts__["test"]: - msg = "alarm {0} is to be created/updated.".format(name) + msg = "alarm {} is to be created/updated.".format(name) ret["comment"] = msg ret["result"] = None return ret @@ -169,7 +162,7 @@ def present(name, attributes, region=None, key=None, keyid=None, profile=None): ret["changes"]["new"] = attributes else: ret["result"] = False - ret["comment"] = "Failed to create {0} alarm".format(name) + ret["comment"] = "Failed to create {} alarm".format(name) return ret @@ -201,7 +194,7 @@ def absent(name, region=None, key=None, keyid=None, profile=None): if is_present: if __opts__["test"]: - ret["comment"] = "alarm {0} is set to be removed.".format(name) + ret["comment"] = "alarm {} is set to be removed.".format(name) ret["result"] = None return ret deleted = __salt__["boto_cloudwatch.delete_alarm"]( @@ -212,8 +205,8 @@ def absent(name, region=None, key=None, keyid=None, profile=None): ret["changes"]["new"] = None else: ret["result"] = False - ret["comment"] = "Failed to delete {0} alarm.".format(name) + ret["comment"] = "Failed to delete {} alarm.".format(name) else: - ret["comment"] = "{0} does not exist in {1}.".format(name, region) + ret["comment"] = "{} does not exist in {}.".format(name, region) return ret diff --git a/salt/states/boto_cloudwatch_event.py b/salt/states/boto_cloudwatch_event.py index 82b7c1a8f1a..4a421549bfc 100644 --- a/salt/states/boto_cloudwatch_event.py +++ b/salt/states/boto_cloudwatch_event.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage CloudTrail Objects ========================= @@ -52,18 +51,12 @@ config: """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import logging import os -# Import Salt libs import salt.utils.json -# Import 3rd-party libs -from salt.ext import six - log = logging.getLogger(__name__) @@ -137,7 +130,7 @@ def present( Name = Name if Name else name - if isinstance(Targets, six.string_types): + if isinstance(Targets, str): Targets = salt.utils.json.loads(Targets) if Targets is None: Targets = [] @@ -148,14 +141,14 @@ def present( if "error" in r: ret["result"] = False - ret["comment"] = "Failed to create event rule: {0}.".format( + ret["comment"] = "Failed to create event rule: {}.".format( r["error"]["message"] ) return ret if not r.get("exists"): if __opts__["test"]: - ret["comment"] = "CloudWatch event rule {0} is set to be created.".format( + ret["comment"] = "CloudWatch event rule {} is set to be created.".format( Name ) ret["result"] = None @@ -174,7 +167,7 @@ def present( ) if not r.get("created"): ret["result"] = False - ret["comment"] = "Failed to create event rule: {0}.".format( + ret["comment"] = "Failed to create event rule: {}.".format( r["error"]["message"] ) return ret @@ -183,14 +176,14 @@ def present( ) if "error" in _describe: ret["result"] = False - ret["comment"] = "Failed to create event rule: {0}.".format( + ret["comment"] = "Failed to create event rule: {}.".format( _describe["error"]["message"] ) ret["changes"] = {} return ret ret["changes"]["old"] = {"rule": None} ret["changes"]["new"] = _describe - ret["comment"] = "CloudTrail {0} created.".format(Name) + ret["comment"] = "CloudTrail {} created.".format(Name) if bool(Targets): r = __salt__["boto_cloudwatch_event.put_targets"]( @@ -203,7 +196,7 @@ def present( ) if "error" in r: ret["result"] = False - ret["comment"] = "Failed to create event rule: {0}.".format( + ret["comment"] = "Failed to create event rule: {}.".format( r["error"]["message"] ) ret["changes"] = {} @@ -212,7 +205,7 @@ def present( return ret ret["comment"] = os.linesep.join( - [ret["comment"], "CloudWatch event rule {0} is present.".format(Name)] + [ret["comment"], "CloudWatch event rule {} is present.".format(Name)] ) ret["changes"] = {} # trail exists, ensure config matches @@ -221,7 +214,7 @@ def present( ) if "error" in _describe: ret["result"] = False - ret["comment"] = "Failed to update event rule: {0}.".format( + ret["comment"] = "Failed to update event rule: {}.".format( _describe["error"]["message"] ) ret["changes"] = {} @@ -233,7 +226,7 @@ def present( ) if "error" in r: ret["result"] = False - ret["comment"] = "Failed to update event rule: {0}.".format( + ret["comment"] = "Failed to update event rule: {}.".format( r["error"]["message"] ) ret["changes"] = {} @@ -249,7 +242,7 @@ def present( "State": "State", "Targets": "Targets", } - for invar, outvar in six.iteritems(rule_vars): + for invar, outvar in rule_vars.items(): if _describe[outvar] != locals()[invar]: need_update = True ret["changes"].setdefault("new", {})[invar] = locals()[invar] @@ -257,7 +250,7 @@ def present( if need_update: if __opts__["test"]: - msg = "CloudWatch event rule {0} set to be modified.".format(Name) + msg = "CloudWatch event rule {} set to be modified.".format(Name) ret["comment"] = msg ret["result"] = None return ret @@ -279,7 +272,7 @@ def present( ) if not r.get("created"): ret["result"] = False - ret["comment"] = "Failed to update event rule: {0}.".format( + ret["comment"] = "Failed to update event rule: {}.".format( r["error"]["message"] ) ret["changes"] = {} @@ -304,7 +297,7 @@ def present( ) if "error" in r: ret["result"] = False - ret["comment"] = "Failed to update event rule: {0}.".format( + ret["comment"] = "Failed to update event rule: {}.".format( r["error"]["message"] ) ret["changes"] = {} @@ -320,7 +313,7 @@ def present( ) if "error" in r: ret["result"] = False - ret["comment"] = "Failed to update event rule: {0}.".format( + ret["comment"] = "Failed to update event rule: {}.".format( r["error"]["message"] ) ret["changes"] = {} @@ -362,17 +355,17 @@ def absent(name, Name=None, region=None, key=None, keyid=None, profile=None): ) if "error" in r: ret["result"] = False - ret["comment"] = "Failed to delete event rule: {0}.".format( + ret["comment"] = "Failed to delete event rule: {}.".format( r["error"]["message"] ) return ret if r and not r["exists"]: - ret["comment"] = "CloudWatch event rule {0} does not exist.".format(Name) + ret["comment"] = "CloudWatch event rule {} does not exist.".format(Name) return ret if __opts__["test"]: - ret["comment"] = "CloudWatch event rule {0} is set to be removed.".format(Name) + ret["comment"] = "CloudWatch event rule {} is set to be removed.".format(Name) ret["result"] = None return ret @@ -382,7 +375,7 @@ def absent(name, Name=None, region=None, key=None, keyid=None, profile=None): ) if not r.get("targets"): ret["result"] = False - ret["comment"] = "Failed to delete event rule: {0}.".format( + ret["comment"] = "Failed to delete event rule: {}.".format( r["error"]["message"] ) return ret @@ -393,13 +386,13 @@ def absent(name, Name=None, region=None, key=None, keyid=None, profile=None): ) if "error" in r: ret["result"] = False - ret["comment"] = "Failed to delete event rule: {0}.".format( + ret["comment"] = "Failed to delete event rule: {}.".format( r["error"]["message"] ) return ret if r.get("failures"): ret["result"] = False - ret["comment"] = "Failed to delete event rule: {0}.".format(r["failures"]) + ret["comment"] = "Failed to delete event rule: {}.".format(r["failures"]) return ret r = __salt__["boto_cloudwatch_event.delete"]( @@ -407,11 +400,11 @@ def absent(name, Name=None, region=None, key=None, keyid=None, profile=None): ) if not r["deleted"]: ret["result"] = False - ret["comment"] = "Failed to delete event rule: {0}.".format( + ret["comment"] = "Failed to delete event rule: {}.".format( r["error"]["message"] ) return ret ret["changes"]["old"] = {"rule": Name} ret["changes"]["new"] = {"rule": None} - ret["comment"] = "CloudWatch event rule {0} deleted.".format(Name) + ret["comment"] = "CloudWatch event rule {} deleted.".format(Name) return ret diff --git a/salt/states/boto_cognitoidentity.py b/salt/states/boto_cognitoidentity.py index cf338e3c7f4..0a38fec9b05 100644 --- a/salt/states/boto_cognitoidentity.py +++ b/salt/states/boto_cognitoidentity.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage CognitoIdentity Functions ================================ @@ -46,15 +45,9 @@ config: """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals import logging -from salt.ext.six import string_types - -# Import Salt Libs - log = logging.getLogger(__name__) @@ -70,14 +63,14 @@ def __virtual__(): def _get_object(objname, objtype): """ Helper function to retrieve objtype from pillars if objname - is string_types, used for SupportedLoginProviders and + is str, used for SupportedLoginProviders and OpenIdConnectProviderARNs. """ ret = None if objname is None: return ret - if isinstance(objname, string_types): + if isinstance(objname, str): if objname in __opts__: ret = __opts__[objname] master_opts = __pillar__.get("master", {}) @@ -105,10 +98,10 @@ def _role_present( ) if r.get("error"): ret["result"] = False - failure_comment = "Failed to get existing identity pool roles: " "{0}".format( + failure_comment = "Failed to get existing identity pool roles: " "{}".format( r["error"].get("message", r["error"]) ) - ret["comment"] = "{0}\n{1}".format(ret["comment"], failure_comment) + ret["comment"] = "{}\n{}".format(ret["comment"], failure_comment) return existing_identity_pool_role = r.get("identity_pool_roles")[0].get("Roles", {}) @@ -120,10 +113,10 @@ def _role_present( ) if not r.get("set"): ret["result"] = False - failure_comment = "Failed to set roles: " "{0}".format( + failure_comment = "Failed to set roles: " "{}".format( r["error"].get("message", r["error"]) ) - ret["comment"] = "{0}\n{1}".format(ret["comment"], failure_comment) + ret["comment"] = "{}\n{}".format(ret["comment"], failure_comment) return updated_identity_pool_role = r.get("roles") @@ -134,11 +127,9 @@ def _role_present( ret["changes"]["new"] = dict() ret["changes"]["old"]["Roles"] = existing_identity_pool_role ret["changes"]["new"]["Roles"] = r.get("roles") - ret["comment"] = "{0}\n{1}".format( - ret["comment"], "identity pool roles updated." - ) + ret["comment"] = "{}\n{}".format(ret["comment"], "identity pool roles updated.") else: - ret["comment"] = "{0}\n{1}".format( + ret["comment"] = "{}\n{}".format( ret["comment"], "identity pool roles is already current." ) @@ -216,7 +207,7 @@ def pool_present( if r.get("error"): ret["result"] = False - ret["comment"] = "Failed to describe identity pools {0}".format( + ret["comment"] = "Failed to describe identity pools {}".format( r["error"]["message"] ) return ret @@ -227,7 +218,7 @@ def pool_present( ret["comment"] = ( "More than one identity pool for the given name matched " "Cannot execute pool_present function.\n" - "Matched Identity Pools:\n{0}".format(identity_pools) + "Matched Identity Pools:\n{}".format(identity_pools) ) return ret existing_identity_pool = None if identity_pools is None else identity_pools[0] @@ -239,13 +230,13 @@ def pool_present( if __opts__["test"]: if identity_pools is None: - ret["comment"] = "A new identity pool named {0} will be " "created.".format( + ret["comment"] = "A new identity pool named {} will be " "created.".format( IdentityPoolName ) else: ret["comment"] = ( - "An existing identity pool named {0} with id " - "{1}will be updated.".format(IdentityPoolName, IdentityPoolId) + "An existing identity pool named {} with id " + "{}will be updated.".format(IdentityPoolName, IdentityPoolId) ) ret["result"] = None return ret @@ -270,12 +261,12 @@ def pool_present( updated_identity_pool = r.get("identity_pool") IdentityPoolId = updated_identity_pool.get("IdentityPoolId") ret["comment"] = ( - "A new identity pool with name {0}, id {1} " + "A new identity pool with name {}, id {} " "is created.".format(IdentityPoolName, IdentityPoolId) ) else: ret["result"] = False - ret["comment"] = "Failed to add a new identity pool: " "{0}".format( + ret["comment"] = "Failed to add a new identity pool: " "{}".format( r["error"].get("message", r["error"]) ) return ret @@ -288,14 +279,14 @@ def pool_present( if r.get("updated"): updated_identity_pool = r.get("identity_pool") ret["comment"] = ( - "Existing identity pool with name {0}, id {1} " + "Existing identity pool with name {}, id {} " "is updated.".format(IdentityPoolName, IdentityPoolId) ) else: ret["result"] = False ret["comment"] = ( - "Failed to update an existing identity pool {0} {1}: " - "{2}".format( + "Failed to update an existing identity pool {} {}: " + "{}".format( IdentityPoolName, IdentityPoolId, r["error"].get("message", r["error"]), @@ -306,7 +297,7 @@ def pool_present( if existing_identity_pool != updated_identity_pool: ret["changes"]["old"] = dict() ret["changes"]["new"] = dict() - change_key = "Identity Pool Name {0}".format(IdentityPoolName) + change_key = "Identity Pool Name {}".format(IdentityPoolName) ret["changes"]["old"][change_key] = existing_identity_pool ret["changes"]["new"][change_key] = updated_identity_pool else: @@ -371,7 +362,7 @@ def pool_absent( if r.get("error"): ret["result"] = False - ret["comment"] = "Failed to describe identity pools {0}".format( + ret["comment"] = "Failed to describe identity pools {}".format( r["error"]["message"] ) return ret @@ -380,7 +371,7 @@ def pool_absent( if identity_pools is None: ret["result"] = True - ret["comment"] = "No matching identity pool for the given name {0}".format( + ret["comment"] = "No matching identity pool for the given name {}".format( IdentityPoolName ) return ret @@ -390,14 +381,14 @@ def pool_absent( ret["comment"] = ( "More than one identity pool for the given name matched " "and RemoveAllMatched flag is False.\n" - "Matched Identity Pools:\n{0}".format(identity_pools) + "Matched Identity Pools:\n{}".format(identity_pools) ) return ret if __opts__["test"]: ret["comment"] = ( "The following matched identity pools will be " - "deleted.\n{0}".format(identity_pools) + "deleted.\n{}".format(identity_pools) ) ret["result"] = None return ret @@ -409,28 +400,28 @@ def pool_absent( ) if r.get("error"): ret["result"] = False - failure_comment = "Failed to delete identity pool {0}: " "{1}".format( + failure_comment = "Failed to delete identity pool {}: " "{}".format( IdentityPoolId, r["error"].get("message", r["error"]) ) - ret["comment"] = "{0}\n{1}".format(ret["comment"], failure_comment) + ret["comment"] = "{}\n{}".format(ret["comment"], failure_comment) return ret if r.get("deleted"): if not ret["changes"]: ret["changes"]["old"] = dict() ret["changes"]["new"] = dict() - change_key = "Identity Pool Id {0}".format(IdentityPoolId) + change_key = "Identity Pool Id {}".format(IdentityPoolId) ret["changes"]["old"][change_key] = IdentityPoolName ret["changes"]["new"][change_key] = None - ret["comment"] = "{0}\n{1}".format( - ret["comment"], "{0} deleted".format(change_key) + ret["comment"] = "{}\n{}".format( + ret["comment"], "{} deleted".format(change_key) ) else: ret["result"] = False - failure_comment = "Identity Pool Id {0} not deleted, returned count 0".format( + failure_comment = "Identity Pool Id {} not deleted, returned count 0".format( IdentityPoolId ) - ret["comment"] = "{0}\n{1}".format(ret["comment"], failure_comment) + ret["comment"] = "{}\n{}".format(ret["comment"], failure_comment) return ret return ret diff --git a/salt/states/boto_datapipeline.py b/salt/states/boto_datapipeline.py index 5273c205404..90ad339b16e 100644 --- a/salt/states/boto_datapipeline.py +++ b/salt/states/boto_datapipeline.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage Data Pipelines @@ -49,18 +48,13 @@ config: myDDBTableName: my-dynamo-table """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import copy import datetime import difflib -# Import Salt lobs import salt.utils.data import salt.utils.json -from salt.ext import six -from salt.ext.six.moves import zip def __virtual__(): @@ -139,13 +133,11 @@ def present( profile=profile, ) if present: - ret["comment"] = "AWS data pipeline {0} present".format(name) + ret["comment"] = "AWS data pipeline {} present".format(name) return ret if __opts__["test"]: - ret["comment"] = "Data pipeline {0} is set to be created or updated".format( - name - ) + ret["comment"] = "Data pipeline {} is set to be created or updated".format(name) ret["result"] = None return ret @@ -154,7 +146,7 @@ def present( ) if "error" in result_create_pipeline: ret["result"] = False - ret["comment"] = "Failed to create data pipeline {0}: {1}".format( + ret["comment"] = "Failed to create data pipeline {}: {}".format( name, result_create_pipeline["error"] ) return ret @@ -183,7 +175,7 @@ def present( ) if "error" in result_delete_pipeline: ret["result"] = False - ret["comment"] = "Failed to delete data pipeline {0}: {1}".format( + ret["comment"] = "Failed to delete data pipeline {}: {}".format( pipeline_id, result_delete_pipeline["error"] ) return ret @@ -193,7 +185,7 @@ def present( ) if "error" in result_create_pipeline: ret["result"] = False - ret["comment"] = "Failed to create data pipeline {0}: {1}".format( + ret["comment"] = "Failed to create data pipeline {}: {}".format( name, result_create_pipeline["error"] ) return ret @@ -220,7 +212,7 @@ def present( if "error" in result_pipeline_definition: # Still erroring after possible retry ret["result"] = False - ret["comment"] = "Failed to create data pipeline {0}: {1}".format( + ret["comment"] = "Failed to create data pipeline {}: {}".format( name, result_pipeline_definition["error"] ) return ret @@ -230,7 +222,7 @@ def present( ) if "error" in result_activate_pipeline: ret["result"] = False - ret["comment"] = "Failed to create data pipeline {0}: {1}".format( + ret["comment"] = "Failed to create data pipeline {}: {}".format( name, result_pipeline_definition["error"] ) return ret @@ -250,10 +242,10 @@ def present( if not old_pipeline_definition: ret["changes"]["new"] = "Pipeline created." - ret["comment"] = "Data pipeline {0} created".format(name) + ret["comment"] = "Data pipeline {} created".format(name) else: ret["changes"]["diff"] = _diff(old_pipeline_definition, new_pipeline_definition) - ret["comment"] = "Data pipeline {0} updated".format(name) + ret["comment"] = "Data pipeline {} updated".format(name) return ret @@ -438,7 +430,7 @@ def _standardize(structure): mutating_helper(each) elif isinstance(structure, dict): structure = dict(structure) - for k, v in six.iteritems(structure): + for k, v in structure.items(): mutating_helper(k) mutating_helper(v) @@ -508,7 +500,7 @@ def _dict_to_list_ids(objects): while still satisfying the boto api. """ list_with_ids = [] - for key, value in six.iteritems(objects): + for key, value in objects.items(): element = {"id": key} element.update(value) list_with_ids.append(element) @@ -542,7 +534,7 @@ def _properties_from_dict(d, key_name="key"): ] """ fields = [] - for key, value in six.iteritems(d): + for key, value in d.items(): if isinstance(value, dict): fields.append({key_name: key, "refValue": value["ref"]}) else: @@ -578,7 +570,7 @@ def absent(name, region=None, key=None, keyid=None, profile=None): if "error" not in result_pipeline_id: pipeline_id = result_pipeline_id["result"] if __opts__["test"]: - ret["comment"] = "Data pipeline {0} set to be deleted.".format(name) + ret["comment"] = "Data pipeline {} set to be deleted.".format(name) ret["result"] = None return ret else: @@ -588,6 +580,6 @@ def absent(name, region=None, key=None, keyid=None, profile=None): ret["changes"]["old"] = {"pipeline_id": pipeline_id} ret["changes"]["new"] = None else: - ret["comment"] = "AWS data pipeline {0} absent.".format(name) + ret["comment"] = "AWS data pipeline {} absent.".format(name) return ret diff --git a/salt/states/boto_dynamodb.py b/salt/states/boto_dynamodb.py index af262b4abb9..bc8e7c1e65b 100644 --- a/salt/states/boto_dynamodb.py +++ b/salt/states/boto_dynamodb.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage DynamoDB Tables ====================== @@ -154,8 +153,6 @@ Setting the alarms in a pillar: threshold_percent: 0.90 period: 900 """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import copy import datetime @@ -165,9 +162,6 @@ import sys import salt.utils.dictupdate as dictupdate -# Import salt libs -from salt.ext import six - logging.basicConfig( level=logging.INFO, format="%(asctime)s %(name)s %(levelname)s %(message)s", @@ -290,7 +284,7 @@ def present( if not table_exists: if __opts__["test"]: ret["result"] = None - ret["comment"] = "DynamoDB table {0} would be created.".format(name) + ret["comment"] = "DynamoDB table {} would be created.".format(name) return ret else: is_created = __salt__["boto_dynamodb.create_table"]( @@ -310,11 +304,11 @@ def present( ) if not is_created: ret["result"] = False - ret["comment"] = "Failed to create table {0}".format(name) + ret["comment"] = "Failed to create table {}".format(name) _add_changes(ret, changes_old, changes_new) return ret - comments.append("DynamoDB table {0} was successfully created".format(name)) + comments.append("DynamoDB table {} was successfully created".format(name)) changes_new["table"] = name changes_new["read_capacity_units"] = read_capacity_units changes_new["write_capacity_units"] = write_capacity_units @@ -325,7 +319,7 @@ def present( changes_new["local_indexes"] = local_indexes changes_new["global_indexes"] = global_indexes else: - comments.append("DynamoDB table {0} exists".format(name)) + comments.append("DynamoDB table {} exists".format(name)) # Ensure DynamoDB table provisioned throughput matches description = __salt__["boto_dynamodb.describe"](name, region, key, keyid, profile) @@ -341,7 +335,7 @@ def present( if not throughput_matches: if __opts__["test"]: ret["result"] = None - comments.append("DynamoDB table {0} is set to be updated.".format(name)) + comments.append("DynamoDB table {} is set to be updated.".format(name)) else: is_updated = __salt__["boto_dynamodb.update"]( name, @@ -356,17 +350,17 @@ def present( ) if not is_updated: ret["result"] = False - ret["comment"] = "Failed to update table {0}".format(name) + ret["comment"] = "Failed to update table {}".format(name) _add_changes(ret, changes_old, changes_new) return ret - comments.append("DynamoDB table {0} was successfully updated".format(name)) + comments.append("DynamoDB table {} was successfully updated".format(name)) changes_old["read_capacity_units"] = (current_read_capacity_units,) changes_old["write_capacity_units"] = (current_write_capacity_units,) changes_new["read_capacity_units"] = (read_capacity_units,) changes_new["write_capacity_units"] = (write_capacity_units,) else: - comments.append("DynamoDB table {0} throughput matches".format(name)) + comments.append("DynamoDB table {} throughput matches".format(name)) provisioned_indexes = description.get("Table", {}).get("GlobalSecondaryIndexes", []) @@ -428,7 +422,7 @@ def present( ret["result"] = datapipeline_ret["result"] comments.append(datapipeline_ret["comment"]) if datapipeline_ret.get("changes"): - ret["changes"]["backup_datapipeline_{0}".format(config["name"])] = ( + ret["changes"]["backup_datapipeline_{}".format(config["name"])] = ( datapipeline_ret.get("changes"), ) else: @@ -463,9 +457,9 @@ def _global_indexes_present( """Handles global secondary index for the table present state.""" ret = {"result": True} if provisioned_indexes: - provisioned_gsi_config = dict( - (index["IndexName"], index) for index in provisioned_indexes - ) + provisioned_gsi_config = { + index["IndexName"]: index for index in provisioned_indexes + } else: provisioned_gsi_config = {} provisioned_index_names = set(provisioned_gsi_config.keys()) @@ -484,7 +478,7 @@ def _global_indexes_present( index_name = next(iter(entry.values())) if not index_name: ret["result"] = False - ret["comment"] = "Index name not found for table {0}".format(name) + ret["comment"] = "Index name not found for table {}".format(name) return ret gsi_config[index_name] = index @@ -497,14 +491,14 @@ def _global_indexes_present( if index_names_to_be_deleted: ret["result"] = False ret["comment"] = ( - "Deletion of GSIs ({0}) is not supported! Please do this " + "Deletion of GSIs ({}) is not supported! Please do this " "manually in the AWS console.".format(", ".join(index_names_to_be_deleted)) ) return ret elif len(new_index_names) > 1: ret["result"] = False ret["comment"] = ( - "Creation of multiple GSIs ({0}) is not supported due to API " + "Creation of multiple GSIs ({}) is not supported due to API " "limitations. Please create them one at a time.".format(new_index_names) ) return ret @@ -580,7 +574,7 @@ def _add_global_secondary_index( """Updates ret iff there was a failure or in test mode.""" if __opts__["test"]: ret["result"] = None - ret["comment"] = "Dynamo table {0} will have a GSI added: {1}".format( + ret["comment"] = "Dynamo table {} will have a GSI added: {}".format( name, index_name ) return @@ -597,11 +591,11 @@ def _add_global_secondary_index( ) if success: - comments.append("Created GSI {0}".format(index_name)) + comments.append("Created GSI {}".format(index_name)) changes_new["global_indexes"][index_name] = gsi_config[index_name] else: ret["result"] = False - ret["comment"] = "Failed to create GSI {0}".format(index_name) + ret["comment"] = "Failed to create GSI {}".format(index_name) def _update_global_secondary_indexes( @@ -625,13 +619,13 @@ def _update_global_secondary_indexes( ) except GsiNotUpdatableError as e: ret["result"] = False - ret["comment"] = six.text_type(e) + ret["comment"] = str(e) return if index_updates: if __opts__["test"]: ret["result"] = None - ret["comment"] = "Dynamo table {0} will have GSIs updated: {1}".format( + ret["comment"] = "Dynamo table {} will have GSIs updated: {}".format( name, ", ".join(index_updates.keys()) ) return @@ -643,7 +637,7 @@ def _update_global_secondary_indexes( if success: comments.append( - "Updated GSIs with new throughputs {0}".format(index_updates) + "Updated GSIs with new throughputs {}".format(index_updates) ) for index_name in index_updates: changes_old["global_indexes"][index_name] = provisioned_throughputs[ @@ -652,9 +646,7 @@ def _update_global_secondary_indexes( changes_new["global_indexes"][index_name] = index_updates[index_name] else: ret["result"] = False - ret["comment"] = "Failed to update GSI throughputs {0}".format( - index_updates - ) + ret["comment"] = "Failed to update GSI throughputs {}".format(index_updates) def _determine_gsi_updates(existing_index_names, provisioned_gsi_config, gsi_config): @@ -686,7 +678,7 @@ def _determine_gsi_updates(existing_index_names, provisioned_gsi_config, gsi_con ) elif new_value != current_value: raise GsiNotUpdatableError( - "GSI property {0} cannot be updated for index {1}".format( + "GSI property {} cannot be updated for index {}".format( key, index_name ) ) @@ -726,7 +718,7 @@ def _alarms_present( tmp = dictupdate.update(tmp, alarms) # set alarms, using boto_cloudwatch_alarm.present merged_return_value = {"name": name, "result": True, "comment": "", "changes": {}} - for _, info in six.iteritems(tmp): + for _, info in tmp.items(): # add dynamodb table to name and description info["name"] = name + " " + info["name"] info["attributes"]["description"] = ( @@ -782,7 +774,7 @@ def _ensure_backup_datapipeline_present( ): kwargs = { - "name": "{0}-{1}-backup".format(name, schedule_name), + "name": "{}-{}-backup".format(name, schedule_name), "pipeline_objects": { "DefaultSchedule": { "name": schedule_name, @@ -797,7 +789,7 @@ def _ensure_backup_datapipeline_present( }, "parameter_values": { "myDDBTableName": name, - "myOutputS3Loc": "{0}/{1}/".format(s3_base_location, name), + "myOutputS3Loc": "{}/{}/".format(s3_base_location, name), }, } return __states__["boto_datapipeline.present"](**kwargs) @@ -863,20 +855,20 @@ def absent(name, region=None, key=None, keyid=None, profile=None): ret = {"name": name, "result": True, "comment": "", "changes": {}} exists = __salt__["boto_dynamodb.exists"](name, region, key, keyid, profile) if not exists: - ret["comment"] = "DynamoDB table {0} does not exist".format(name) + ret["comment"] = "DynamoDB table {} does not exist".format(name) return ret if __opts__["test"]: - ret["comment"] = "DynamoDB table {0} is set to be deleted".format(name) + ret["comment"] = "DynamoDB table {} is set to be deleted".format(name) ret["result"] = None return ret is_deleted = __salt__["boto_dynamodb.delete"](name, region, key, keyid, profile) if is_deleted: - ret["comment"] = "Deleted DynamoDB table {0}".format(name) - ret["changes"].setdefault("old", "Table {0} exists".format(name)) - ret["changes"].setdefault("new", "Table {0} deleted".format(name)) + ret["comment"] = "Deleted DynamoDB table {}".format(name) + ret["changes"].setdefault("old", "Table {} exists".format(name)) + ret["changes"].setdefault("new", "Table {} deleted".format(name)) else: - ret["comment"] = "Failed to delete DynamoDB table {0}".format(name) + ret["comment"] = "Failed to delete DynamoDB table {}".format(name) ret["result"] = False return ret diff --git a/salt/states/boto_ec2.py b/salt/states/boto_ec2.py index 4d34b31db5f..265afa67db7 100644 --- a/salt/states/boto_ec2.py +++ b/salt/states/boto_ec2.py @@ -57,7 +57,6 @@ from time import sleep, time import salt.utils.data import salt.utils.dictupdate as dictupdate from salt.exceptions import CommandExecutionError, SaltInvocationError -from salt.ext.six.moves import range log = logging.getLogger(__name__) diff --git a/salt/states/boto_elasticache.py b/salt/states/boto_elasticache.py index 4d0cafd67f1..f46b2f7a1b4 100644 --- a/salt/states/boto_elasticache.py +++ b/salt/states/boto_elasticache.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage Elasticache ================== @@ -76,8 +75,6 @@ passed in as a dict, or as a string to pull from pillars or minion config: key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals import logging @@ -230,7 +227,7 @@ def present( return ret elif not config: if __opts__["test"]: - msg = "Cache cluster {0} is set to be created.".format(name) + msg = "Cache cluster {} is set to be created.".format(name) ret["comment"] = msg ret["result"] = None return ret @@ -264,11 +261,11 @@ def present( ret["changes"]["new"] = config else: ret["result"] = False - ret["comment"] = "Failed to create {0} cache cluster.".format(name) + ret["comment"] = "Failed to create {} cache cluster.".format(name) return ret # TODO: support modification of existing elasticache clusters else: - ret["comment"] = "Cache cluster {0} is present.".format(name) + ret["comment"] = "Cache cluster {} is present.".format(name) return ret @@ -323,7 +320,7 @@ def subnet_group_present( ) if not exists: if __opts__["test"]: - ret["comment"] = "Subnet group {0} is set to be created.".format(name) + ret["comment"] = "Subnet group {} is set to be created.".format(name) ret["result"] = None return ret created = __salt__["boto_elasticache.create_subnet_group"]( @@ -339,11 +336,11 @@ def subnet_group_present( ) if not created: ret["result"] = False - ret["comment"] = "Failed to create {0} subnet group.".format(name) + ret["comment"] = "Failed to create {} subnet group.".format(name) return ret ret["changes"]["old"] = None ret["changes"]["new"] = name - ret["comment"] = "Subnet group {0} created.".format(name) + ret["comment"] = "Subnet group {} created.".format(name) return ret ret["comment"] = "Subnet group present." return ret @@ -383,7 +380,7 @@ def absent(name, wait=True, region=None, key=None, keyid=None, profile=None): if is_present: if __opts__["test"]: - ret["comment"] = "Cache cluster {0} is set to be removed.".format(name) + ret["comment"] = "Cache cluster {} is set to be removed.".format(name) ret["result"] = None return ret deleted = __salt__["boto_elasticache.delete"]( @@ -394,9 +391,9 @@ def absent(name, wait=True, region=None, key=None, keyid=None, profile=None): ret["changes"]["new"] = None else: ret["result"] = False - ret["comment"] = "Failed to delete {0} cache cluster.".format(name) + ret["comment"] = "Failed to delete {} cache cluster.".format(name) else: - ret["comment"] = "{0} does not exist in {1}.".format(name, region) + ret["comment"] = "{} does not exist in {}.".format(name, region) return ret @@ -448,7 +445,7 @@ def creategroup( ) if not is_present: if __opts__["test"]: - ret["comment"] = "Replication {0} is set to be created.".format(name) + ret["comment"] = "Replication {} is set to be created.".format(name) ret["result"] = None created = __salt__["boto_elasticache.create_replication_group"]( name, @@ -469,9 +466,9 @@ def creategroup( ret["result"] = True else: ret["result"] = False - ret["comment"] = "Failed to create {0} replication group.".format(name) + ret["comment"] = "Failed to create {} replication group.".format(name) else: - ret["comment"] = "{0} replication group exists .".format(name) + ret["comment"] = "{} replication group exists .".format(name) ret["result"] = True return ret @@ -486,11 +483,11 @@ def subnet_group_absent( ) if not exists: ret["result"] = True - ret["comment"] = "{0} ElastiCache subnet group does not exist.".format(name) + ret["comment"] = "{} ElastiCache subnet group does not exist.".format(name) return ret if __opts__["test"]: - ret["comment"] = "ElastiCache subnet group {0} is set to be removed.".format( + ret["comment"] = "ElastiCache subnet group {} is set to be removed.".format( name ) ret["result"] = None @@ -500,11 +497,11 @@ def subnet_group_absent( ) if not deleted: ret["result"] = False - ret["comment"] = "Failed to delete {0} ElastiCache subnet group.".format(name) + ret["comment"] = "Failed to delete {} ElastiCache subnet group.".format(name) return ret ret["changes"]["old"] = name ret["changes"]["new"] = None - ret["comment"] = "ElastiCache subnet group {0} deleted.".format(name) + ret["comment"] = "ElastiCache subnet group {} deleted.".format(name) return ret @@ -518,16 +515,14 @@ def replication_group_absent( ) if not exists: ret["result"] = True - ret["comment"] = "{0} ElastiCache replication group does not exist.".format( - name - ) + ret["comment"] = "{} ElastiCache replication group does not exist.".format(name) log.info(ret["comment"]) return ret if __opts__["test"]: ret[ "comment" - ] = "ElastiCache replication group {0} is set to be removed.".format(name) + ] = "ElastiCache replication group {} is set to be removed.".format(name) ret["result"] = True return ret deleted = __salt__["boto_elasticache.delete_replication_group"]( @@ -536,12 +531,12 @@ def replication_group_absent( if not deleted: ret["result"] = False log.error(ret["comment"]) - ret["comment"] = "Failed to delete {0} ElastiCache replication group.".format( + ret["comment"] = "Failed to delete {} ElastiCache replication group.".format( name ) return ret ret["changes"]["old"] = name ret["changes"]["new"] = None - ret["comment"] = "ElastiCache replication group {0} deleted.".format(name) + ret["comment"] = "ElastiCache replication group {} deleted.".format(name) log.info(ret["comment"]) return ret diff --git a/salt/states/boto_elasticsearch_domain.py b/salt/states/boto_elasticsearch_domain.py index 9b4a68fc0d2..db7c0394125 100644 --- a/salt/states/boto_elasticsearch_domain.py +++ b/salt/states/boto_elasticsearch_domain.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage Elasticsearch Domains ============================ @@ -78,18 +77,12 @@ config: """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import logging import os -# Import Salt libs import salt.utils.json -# Import 3rd-party libs -from salt.ext import six - log = logging.getLogger(__name__) @@ -224,12 +217,12 @@ def present( AdvancedOptions = {"rest.action.multi.allow_explicit_index": "true"} if Tags is None: Tags = {} - if AccessPolicies is not None and isinstance(AccessPolicies, six.string_types): + if AccessPolicies is not None and isinstance(AccessPolicies, str): try: AccessPolicies = salt.utils.json.loads(AccessPolicies) except ValueError as e: ret["result"] = False - ret["comment"] = "Failed to create domain: {0}.".format(e.message) + ret["comment"] = "Failed to create domain: {}.".format(e.message) return ret r = __salt__["boto_elasticsearch_domain.exists"]( DomainName=DomainName, region=region, key=key, keyid=keyid, profile=profile @@ -237,12 +230,12 @@ def present( if "error" in r: ret["result"] = False - ret["comment"] = "Failed to create domain: {0}.".format(r["error"]["message"]) + ret["comment"] = "Failed to create domain: {}.".format(r["error"]["message"]) return ret if not r.get("exists"): if __opts__["test"]: - ret["comment"] = "Domain {0} is set to be created.".format(DomainName) + ret["comment"] = "Domain {} is set to be created.".format(DomainName) ret["result"] = None return ret r = __salt__["boto_elasticsearch_domain.create"]( @@ -262,7 +255,7 @@ def present( ) if not r.get("created"): ret["result"] = False - ret["comment"] = "Failed to create domain: {0}.".format( + ret["comment"] = "Failed to create domain: {}.".format( r["error"]["message"] ) return ret @@ -271,11 +264,11 @@ def present( ) ret["changes"]["old"] = {"domain": None} ret["changes"]["new"] = _describe - ret["comment"] = "Domain {0} created.".format(DomainName) + ret["comment"] = "Domain {} created.".format(DomainName) return ret ret["comment"] = os.linesep.join( - [ret["comment"], "Domain {0} is present.".format(DomainName)] + [ret["comment"], "Domain {} is present.".format(DomainName)] ) ret["changes"] = {} # domain exists, ensure config matches @@ -288,7 +281,7 @@ def present( ret["result"] = False ret["comment"] = ( "Failed to update domain: version cannot be modified " - "from {0} to {1}.".format( + "from {} to {}.".format( _status.get("ElasticsearchVersion"), str(ElasticsearchVersion), # future lint: disable=blacklisted-function ) @@ -315,7 +308,7 @@ def present( "AdvancedOptions": AdvancedOptions, } - for k, v in six.iteritems(es_opts): + for k, v in es_opts.items(): if not _compare_json(v, _describe[k]): need_update = True comm_args[k] = v @@ -323,7 +316,7 @@ def present( ret["changes"].setdefault("old", {})[k] = _describe[k] if need_update: if __opts__["test"]: - msg = "Domain {0} set to be modified.".format(DomainName) + msg = "Domain {} set to be modified.".format(DomainName) ret["comment"] = msg ret["result"] = None return ret @@ -340,7 +333,7 @@ def present( ) if not r.get("updated"): ret["result"] = False - ret["comment"] = "Failed to update domain: {0}.".format(r["error"]) + ret["comment"] = "Failed to update domain: {}.".format(r["error"]) ret["changes"] = {} return ret return ret @@ -377,15 +370,15 @@ def absent(name, DomainName, region=None, key=None, keyid=None, profile=None): ) if "error" in r: ret["result"] = False - ret["comment"] = "Failed to delete domain: {0}.".format(r["error"]["message"]) + ret["comment"] = "Failed to delete domain: {}.".format(r["error"]["message"]) return ret if r and not r["exists"]: - ret["comment"] = "Domain {0} does not exist.".format(DomainName) + ret["comment"] = "Domain {} does not exist.".format(DomainName) return ret if __opts__["test"]: - ret["comment"] = "Domain {0} is set to be removed.".format(DomainName) + ret["comment"] = "Domain {} is set to be removed.".format(DomainName) ret["result"] = None return ret @@ -394,9 +387,9 @@ def absent(name, DomainName, region=None, key=None, keyid=None, profile=None): ) if not r["deleted"]: ret["result"] = False - ret["comment"] = "Failed to delete domain: {0}.".format(r["error"]["message"]) + ret["comment"] = "Failed to delete domain: {}.".format(r["error"]["message"]) return ret ret["changes"]["old"] = {"domain": DomainName} ret["changes"]["new"] = {"domain": None} - ret["comment"] = "Domain {0} deleted.".format(DomainName) + ret["comment"] = "Domain {} deleted.".format(DomainName) return ret diff --git a/salt/states/boto_elb.py b/salt/states/boto_elb.py index ff06e3d086a..86e299a62c6 100644 --- a/salt/states/boto_elb.py +++ b/salt/states/boto_elb.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage ELBs @@ -235,10 +234,7 @@ Tags can also be set: OtherTag: 'My Other Value' """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals -# Import Salt Libs import hashlib import logging import re @@ -247,7 +243,6 @@ import salt.utils.data import salt.utils.dictupdate import salt.utils.stringutils from salt.exceptions import SaltInvocationError -from salt.ext import six log = logging.getLogger(__name__) @@ -402,7 +397,7 @@ def present( ret = {"name": name, "result": True, "comment": "", "changes": {}} - if not isinstance(security_groups, (six.string_types, list, type(None))): + if not isinstance(security_groups, ((str,), list, type(None))): msg = ( "The 'security_group' parameter must be either a list or a " "comma-separated string." @@ -410,7 +405,7 @@ def present( log.error(msg) ret.update({"comment": msg, "result": False}) return ret - if isinstance(security_groups, six.string_types): + if isinstance(security_groups, str): security_groups = security_groups.split(",") _ret = _elb_present( @@ -554,7 +549,7 @@ def present( if __salt__["boto_elb.set_instances"]( name, instance_ids, True, region, key, keyid, profile ): - ret["comment"] += " ELB {0} instances would be updated.".format(name) + ret["comment"] += " ELB {} instances would be updated.".format(name) ret["result"] = None else: success = __salt__["boto_elb.set_instances"]( @@ -597,7 +592,7 @@ def register_instances( ret = {"name": name, "result": True, "comment": "", "changes": {}} lb = __salt__["boto_elb.exists"](name, region, key, keyid, profile) if not lb: - msg = "Could not find lb {0}".format(name) + msg = "Could not find lb {}".format(name) log.error(msg) ret.update({"comment": msg, "result": False}) return ret @@ -610,15 +605,13 @@ def register_instances( ] new = [value for value in instances if value not in nodes] if not new: - msg = "Instance/s {0} already exist.".format( - six.text_type(instances).strip("[]") - ) + msg = "Instance/s {} already exist.".format(str(instances).strip("[]")) log.debug(msg) ret.update({"comment": msg}) return ret if __opts__["test"]: - ret["comment"] = "ELB {0} is set to register : {1}.".format(name, new) + ret["comment"] = "ELB {} is set to register : {}.".format(name, new) ret["result"] = None return ret @@ -626,7 +619,7 @@ def register_instances( name, instances, region, key, keyid, profile ) if state: - msg = "Load Balancer {0} has been changed".format(name) + msg = "Load Balancer {} has been changed".format(name) log.info(msg) new = set().union(nodes, instances) ret.update( @@ -636,7 +629,7 @@ def register_instances( } ) else: - msg = "Load balancer {0} failed to add instances".format(name) + msg = "Load balancer {} failed to add instances".format(name) log.error(msg) ret.update({"comment": msg, "result": False}) return ret @@ -711,11 +704,11 @@ def _elb_present( "subnet", name=i, region=region, key=key, keyid=keyid, profile=profile ) if "error" in r: - ret["comment"] = "Error looking up subnet ids: {0}".format(r["error"]) + ret["comment"] = "Error looking up subnet ids: {}".format(r["error"]) ret["result"] = False return ret if "id" not in r: - ret["comment"] = "Subnet {0} does not exist.".format(i) + ret["comment"] = "Subnet {} does not exist.".format(i) ret["result"] = False return ret subnets.append(r["id"]) @@ -727,7 +720,7 @@ def _elb_present( ) vpc_id = vpc_id.get("vpc_id") if not vpc_id: - ret["comment"] = "Subnets {0} do not map to a valid vpc id.".format(subnets) + ret["comment"] = "Subnets {} do not map to a valid vpc id.".format(subnets) ret["result"] = False return ret _security_groups = __salt__["boto_secgroup.convert_to_group_ids"]( @@ -741,7 +734,7 @@ def _elb_present( if not _security_groups: ret[ "comment" - ] = "Security groups {0} do not map to valid security group ids.".format( + ] = "Security groups {} do not map to valid security group ids.".format( security_groups ) ret["result"] = False @@ -749,7 +742,7 @@ def _elb_present( exists = __salt__["boto_elb.exists"](name, region, key, keyid, profile) if not exists: if __opts__["test"]: - ret["comment"] = "ELB {0} is set to be created.".format(name) + ret["comment"] = "ELB {} is set to be created.".format(name) ret["result"] = None return ret created = __salt__["boto_elb.create"]( @@ -767,12 +760,12 @@ def _elb_present( if created: ret["changes"]["old"] = {"elb": None} ret["changes"]["new"] = {"elb": name} - ret["comment"] = "ELB {0} created.".format(name) + ret["comment"] = "ELB {} created.".format(name) else: ret["result"] = False - ret["comment"] = "Failed to create {0} ELB.".format(name) + ret["comment"] = "Failed to create {} ELB.".format(name) else: - ret["comment"] = "ELB {0} present.".format(name) + ret["comment"] = "ELB {} present.".format(name) _ret = _security_groups_present( name, _security_groups, region, key, keyid, profile ) @@ -814,7 +807,7 @@ def _listeners_present(name, listeners, region, key, keyid, profile): ret = {"result": True, "comment": "", "changes": {}} lb = __salt__["boto_elb.get_elb_config"](name, region, key, keyid, profile) if not lb: - ret["comment"] = "{0} ELB configuration could not be retrieved.".format(name) + ret["comment"] = "{} ELB configuration could not be retrieved.".format(name) ret["result"] = False return ret if not listeners: @@ -832,32 +825,32 @@ def _listeners_present(name, listeners, region, key, keyid, profile): to_delete = [] to_create = [] - for t, l in six.iteritems(expected_listeners_by_tuple): + for t, l in expected_listeners_by_tuple.items(): if t not in actual_listeners_by_tuple: to_create.append(l) - for t, l in six.iteritems(actual_listeners_by_tuple): + for t, l in actual_listeners_by_tuple.items(): if t not in expected_listeners_by_tuple: to_delete.append(l) if __opts__["test"]: msg = [] if to_create or to_delete: - msg.append("ELB {0} set to have listeners modified:".format(name)) + msg.append("ELB {} set to have listeners modified:".format(name)) for listener in to_create: msg.append( - "Listener {0} added.".format( + "Listener {} added.".format( __salt__["boto_elb.listener_dict_to_tuple"](listener) ) ) for listener in to_delete: msg.append( - "Listener {0} deleted.".format( + "Listener {} deleted.".format( __salt__["boto_elb.listener_dict_to_tuple"](listener) ) ) ret["result"] = None else: - msg.append("Listeners already set on ELB {0}.".format(name)) + msg.append("Listeners already set on ELB {}.".format(name)) ret["comment"] = " ".join(msg) return ret @@ -867,9 +860,9 @@ def _listeners_present(name, listeners, region, key, keyid, profile): name, ports, region, key, keyid, profile ) if deleted: - ret["comment"] = "Deleted listeners on {0} ELB.".format(name) + ret["comment"] = "Deleted listeners on {} ELB.".format(name) else: - ret["comment"] = "Failed to delete listeners on {0} ELB.".format(name) + ret["comment"] = "Failed to delete listeners on {} ELB.".format(name) ret["result"] = False if to_create: @@ -890,7 +883,7 @@ def _listeners_present(name, listeners, region, key, keyid, profile): lb = __salt__["boto_elb.get_elb_config"](name, region, key, keyid, profile) ret["changes"]["listeners"]["new"] = lb["listeners"] else: - ret["comment"] = "Listeners already set on ELB {0}.".format(name) + ret["comment"] = "Listeners already set on ELB {}.".format(name) return ret @@ -899,7 +892,7 @@ def _security_groups_present(name, security_groups, region, key, keyid, profile) ret = {"result": True, "comment": "", "changes": {}} lb = __salt__["boto_elb.get_elb_config"](name, region, key, keyid, profile) if not lb: - ret["comment"] = "{0} ELB configuration could not be retrieved.".format(name) + ret["comment"] = "{} ELB configuration could not be retrieved.".format(name) ret["result"] = False return ret if not security_groups: @@ -909,23 +902,21 @@ def _security_groups_present(name, security_groups, region, key, keyid, profile) change_needed = True if change_needed: if __opts__["test"]: - ret["comment"] = "ELB {0} set to have security groups modified.".format( - name - ) + ret["comment"] = "ELB {} set to have security groups modified.".format(name) ret["result"] = None return ret changed = __salt__["boto_elb.apply_security_groups"]( name, security_groups, region, key, keyid, profile ) if changed: - ret["comment"] = "Modified security_groups on {0} ELB.".format(name) + ret["comment"] = "Modified security_groups on {} ELB.".format(name) else: - ret["comment"] = "Failed to modify security_groups on {0} ELB.".format(name) + ret["comment"] = "Failed to modify security_groups on {} ELB.".format(name) ret["result"] = False ret["changes"]["old"] = {"security_groups": lb["security_groups"]} ret["changes"]["new"] = {"security_groups": security_groups} else: - ret["comment"] = "security_groups already set on ELB {0}.".format(name) + ret["comment"] = "security_groups already set on ELB {}.".format(name) return ret @@ -934,7 +925,7 @@ def _attributes_present(name, attributes, region, key, keyid, profile): _attributes = __salt__["boto_elb.get_attributes"](name, region, key, keyid, profile) if not _attributes: ret["result"] = False - ret["comment"] = "Failed to retrieve attributes for ELB {0}.".format(name) + ret["comment"] = "Failed to retrieve attributes for ELB {}.".format(name) return ret attrs_to_set = [] if "cross_zone_load_balancing" in attributes: @@ -955,8 +946,8 @@ def _attributes_present(name, attributes, region, key, keyid, profile): if cs["idle_timeout"] != _cs["idle_timeout"]: attrs_to_set.append("connecting_settings") if "access_log" in attributes: - for attr, val in six.iteritems(attributes["access_log"]): - if six.text_type(_attributes["access_log"][attr]) != six.text_type(val): + for attr, val in attributes["access_log"].items(): + if str(_attributes["access_log"][attr]) != str(val): attrs_to_set.append("access_log") if "s3_bucket_prefix" in attributes["access_log"]: sbp = attributes["access_log"]["s3_bucket_prefix"] @@ -966,7 +957,7 @@ def _attributes_present(name, attributes, region, key, keyid, profile): ) if attrs_to_set: if __opts__["test"]: - ret["comment"] = "ELB {0} set to have attributes set.".format(name) + ret["comment"] = "ELB {} set to have attributes set.".format(name) ret["result"] = None return ret was_set = __salt__["boto_elb.set_attributes"]( @@ -975,12 +966,12 @@ def _attributes_present(name, attributes, region, key, keyid, profile): if was_set: ret["changes"]["old"] = {"attributes": _attributes} ret["changes"]["new"] = {"attributes": attributes} - ret["comment"] = "Set attributes on ELB {0}.".format(name) + ret["comment"] = "Set attributes on ELB {}.".format(name) else: ret["result"] = False - ret["comment"] = "Failed to set attributes on ELB {0}.".format(name) + ret["comment"] = "Failed to set attributes on ELB {}.".format(name) else: - ret["comment"] = "Attributes already set on ELB {0}.".format(name) + ret["comment"] = "Attributes already set on ELB {}.".format(name) return ret @@ -993,15 +984,15 @@ def _health_check_present(name, health_check, region, key, keyid, profile): ) if not _health_check: ret["result"] = False - ret["comment"] = "Failed to retrieve health_check for ELB {0}.".format(name) + ret["comment"] = "Failed to retrieve health_check for ELB {}.".format(name) return ret need_to_set = False - for attr, val in six.iteritems(health_check): - if six.text_type(_health_check[attr]) != six.text_type(val): + for attr, val in health_check.items(): + if str(_health_check[attr]) != str(val): need_to_set = True if need_to_set: if __opts__["test"]: - ret["comment"] = "ELB {0} set to have health check set.".format(name) + ret["comment"] = "ELB {} set to have health check set.".format(name) ret["result"] = None return ret was_set = __salt__["boto_elb.set_health_check"]( @@ -1013,12 +1004,12 @@ def _health_check_present(name, health_check, region, key, keyid, profile): name, region, key, keyid, profile ) ret["changes"]["new"] = {"health_check": _health_check} - ret["comment"] = "Set health check on ELB {0}.".format(name) + ret["comment"] = "Set health check on ELB {}.".format(name) else: ret["result"] = False - ret["comment"] = "Failed to set health check on ELB {0}.".format(name) + ret["comment"] = "Failed to set health check on ELB {}.".format(name) else: - ret["comment"] = "Health check already set on ELB {0}.".format(name) + ret["comment"] = "Health check already set on ELB {}.".format(name) return ret @@ -1027,7 +1018,7 @@ def _zones_present(name, availability_zones, region, key, keyid, profile): lb = __salt__["boto_elb.get_elb_config"](name, region, key, keyid, profile) if not lb: ret["result"] = False - ret["comment"] = "Failed to retrieve ELB {0}.".format(name) + ret["comment"] = "Failed to retrieve ELB {}.".format(name) return ret to_enable = [] to_disable = [] @@ -1040,7 +1031,7 @@ def _zones_present(name, availability_zones, region, key, keyid, profile): to_disable.append(zone) if to_enable or to_disable: if __opts__["test"]: - ret["comment"] = "ELB {0} to have availability zones set.".format(name) + ret["comment"] = "ELB {} to have availability zones set.".format(name) ret["result"] = None return ret if to_enable: @@ -1048,11 +1039,11 @@ def _zones_present(name, availability_zones, region, key, keyid, profile): name, to_enable, region, key, keyid, profile ) if enabled: - ret["comment"] = "Enabled availability zones on {0} ELB.".format(name) + ret["comment"] = "Enabled availability zones on {} ELB.".format(name) else: ret[ "comment" - ] = "Failed to enable availability zones on {0} ELB.".format(name) + ] = "Failed to enable availability zones on {} ELB.".format(name) ret["result"] = False if to_disable: disabled = __salt__["boto_elb.disable_availability_zones"]( @@ -1069,7 +1060,7 @@ def _zones_present(name, availability_zones, region, key, keyid, profile): lb = __salt__["boto_elb.get_elb_config"](name, region, key, keyid, profile) ret["changes"]["new"] = {"availability_zones": lb["availability_zones"]} else: - ret["comment"] = "Availability zones already set on ELB {0}.".format(name) + ret["comment"] = "Availability zones already set on ELB {}.".format(name) return ret @@ -1080,7 +1071,7 @@ def _subnets_present(name, subnets, region, key, keyid, profile): lb = __salt__["boto_elb.get_elb_config"](name, region, key, keyid, profile) if not lb: ret["result"] = False - ret["comment"] = "Failed to retrieve ELB {0}.".format(name) + ret["comment"] = "Failed to retrieve ELB {}.".format(name) return ret to_enable = [] to_disable = [] @@ -1093,7 +1084,7 @@ def _subnets_present(name, subnets, region, key, keyid, profile): to_disable.append(subnet) if to_enable or to_disable: if __opts__["test"]: - ret["comment"] = "ELB {0} to have subnets set.".format(name) + ret["comment"] = "ELB {} to have subnets set.".format(name) ret["result"] = None return ret if to_enable: @@ -1101,9 +1092,9 @@ def _subnets_present(name, subnets, region, key, keyid, profile): name, to_enable, region, key, keyid, profile ) if attached: - ret["comment"] = "Attached subnets on {0} ELB.".format(name) + ret["comment"] = "Attached subnets on {} ELB.".format(name) else: - ret["comment"] = "Failed to attach subnets on {0} ELB.".format(name) + ret["comment"] = "Failed to attach subnets on {} ELB.".format(name) ret["result"] = False if to_disable: detached = __salt__["boto_elb.detach_subnets"]( @@ -1111,13 +1102,13 @@ def _subnets_present(name, subnets, region, key, keyid, profile): ) if detached: ret["comment"] = " ".join( - [ret["comment"], "Detached subnets on {0} ELB.".format(name)] + [ret["comment"], "Detached subnets on {} ELB.".format(name)] ) else: ret["comment"] = " ".join( [ ret["comment"], - "Failed to detach subnets on {0} ELB.".format(name), + "Failed to detach subnets on {} ELB.".format(name), ] ) ret["result"] = False @@ -1125,7 +1116,7 @@ def _subnets_present(name, subnets, region, key, keyid, profile): lb = __salt__["boto_elb.get_elb_config"](name, region, key, keyid, profile) ret["changes"]["new"] = {"subnets": lb["subnets"]} else: - ret["comment"] = "Subnets already set on ELB {0}.".format(name) + ret["comment"] = "Subnets already set on ELB {}.".format(name) return ret @@ -1135,7 +1126,7 @@ def _alarms_present(name, alarms, alarms_from_pillar, region, key, keyid, profil if alarms: current = salt.utils.dictupdate.update(current, alarms) ret = {"name": name, "result": True, "comment": "", "changes": {}} - for _, info in six.iteritems(current): + for _, info in current.items(): info["name"] = name + " " + info["name"] info["attributes"]["description"] = ( name + " " + info["attributes"]["description"] @@ -1195,7 +1186,7 @@ def _policies_present( # check for unique policy names if p["policy_name"] in policy_names: raise SaltInvocationError( - "Policy names must be unique: policy {0}" + "Policy names must be unique: policy {}" " is declared twice.".format(p["policy_name"]) ) policy_names.add(p["policy_name"]) @@ -1205,8 +1196,8 @@ def _policies_present( for p in l.get("policies", []): if p not in policy_names: raise SaltInvocationError( - "Listener {0} on ELB {1} refers to " - "undefined policy {2}.".format(l["elb_port"], name, p) + "Listener {} on ELB {} refers to " + "undefined policy {}.".format(l["elb_port"], name, p) ) # check that backends refer to valid policy names @@ -1214,16 +1205,16 @@ def _policies_present( for p in b.get("policies", []): if p not in policy_names: raise SaltInvocationError( - "Backend {0} on ELB {1} refers to " + "Backend {} on ELB {} refers to " "undefined policy " - "{2}.".format(b["instance_port"], name, p) + "{}.".format(b["instance_port"], name, p) ) ret = {"result": True, "comment": "", "changes": {}} lb = __salt__["boto_elb.get_elb_config"](name, region, key, keyid, profile) if not lb: - ret["comment"] = "{0} ELB configuration could not be retrieved.".format(name) + ret["comment"] = "{} ELB configuration could not be retrieved.".format(name) ret["result"] = False return ret @@ -1253,9 +1244,9 @@ def _policies_present( expected_policies_by_listener = {} for l in listeners: - expected_policies_by_listener[l["elb_port"]] = set( - [cnames_by_name[p] for p in l.get("policies", [])] - ) + expected_policies_by_listener[l["elb_port"]] = { + cnames_by_name[p] for p in l.get("policies", []) + } actual_policies_by_listener = {} for l in lb["listeners"]: @@ -1270,9 +1261,9 @@ def _policies_present( expected_policies_by_backend = {} for b in backends: - expected_policies_by_backend[b["instance_port"]] = set( - [cnames_by_name[p] for p in b.get("policies", [])] - ) + expected_policies_by_backend[b["instance_port"]] = { + cnames_by_name[p] for p in b.get("policies", []) + } actual_policies_by_backend = {} for b in lb["backends"]: @@ -1291,36 +1282,36 @@ def _policies_present( to_delete.append(policy_name) listeners_to_update = set() - for port, policies in six.iteritems(expected_policies_by_listener): + for port, policies in expected_policies_by_listener.items(): if policies != actual_policies_by_listener.get(port, set()): listeners_to_update.add(port) - for port, policies in six.iteritems(actual_policies_by_listener): + for port, policies in actual_policies_by_listener.items(): if policies != expected_policies_by_listener.get(port, set()): listeners_to_update.add(port) backends_to_update = set() - for port, policies in six.iteritems(expected_policies_by_backend): + for port, policies in expected_policies_by_backend.items(): if policies != actual_policies_by_backend.get(port, set()): backends_to_update.add(port) - for port, policies in six.iteritems(actual_policies_by_backend): + for port, policies in actual_policies_by_backend.items(): if policies != expected_policies_by_backend.get(port, set()): backends_to_update.add(port) if __opts__["test"]: msg = [] if to_create or to_delete: - msg.append("ELB {0} set to have policies modified:".format(name)) + msg.append("ELB {} set to have policies modified:".format(name)) for policy in to_create: - msg.append("Policy {0} added.".format(policy)) + msg.append("Policy {} added.".format(policy)) for policy in to_delete: - msg.append("Policy {0} deleted.".format(policy)) + msg.append("Policy {} deleted.".format(policy)) ret["result"] = None else: - msg.append("Policies already set on ELB {0}.".format(name)) + msg.append("Policies already set on ELB {}.".format(name)) for listener in listeners_to_update: - msg.append("Listener {0} policies updated.".format(listener)) + msg.append("Listener {} policies updated.".format(listener)) for backend in backends_to_update: - msg.append("Backend {0} policies updated.".format(backend)) + msg.append("Backend {} policies updated.".format(backend)) ret["comment"] = " ".join(msg) return ret @@ -1338,7 +1329,7 @@ def _policies_present( ) if created: ret["changes"].setdefault(policy_name, {})["new"] = policy_name - comment = "Policy {0} was created on ELB {1}".format(policy_name, name) + comment = "Policy {} was created on ELB {}".format(policy_name, name) ret["comment"] = " ".join([ret["comment"], comment]) ret["result"] = True else: @@ -1356,12 +1347,12 @@ def _policies_present( profile=profile, ) if policy_set: - policy_key = "listener_{0}_policy".format(port) + policy_key = "listener_{}_policy".format(port) ret["changes"][policy_key] = { "old": list(actual_policies_by_listener.get(port, [])), "new": list(expected_policies_by_listener.get(port, [])), } - comment = "Policy {0} was created on ELB {1} listener {2}".format( + comment = "Policy {} was created on ELB {} listener {}".format( expected_policies_by_listener[port], name, port ) ret["comment"] = " ".join([ret["comment"], comment]) @@ -1381,12 +1372,12 @@ def _policies_present( profile=profile, ) if policy_set: - policy_key = "backend_{0}_policy".format(port) + policy_key = "backend_{}_policy".format(port) ret["changes"][policy_key] = { "old": list(actual_policies_by_backend.get(port, [])), "new": list(expected_policies_by_backend.get(port, [])), } - comment = "Policy {0} was created on ELB {1} backend {2}".format( + comment = "Policy {} was created on ELB {} backend {}".format( expected_policies_by_backend[port], name, port ) ret["comment"] = " ".join([ret["comment"], comment]) @@ -1407,9 +1398,7 @@ def _policies_present( ) if deleted: ret["changes"].setdefault(policy_name, {})["old"] = policy_name - comment = "Policy {0} was deleted from ELB {1}".format( - policy_name, name - ) + comment = "Policy {} was deleted from ELB {}".format(policy_name, name) ret["comment"] = " ".join([ret["comment"], comment]) ret["result"] = True else: @@ -1422,15 +1411,13 @@ def _policy_cname(policy_dict): policy_name = policy_dict["policy_name"] policy_type = policy_dict["policy_type"] policy = policy_dict["policy"] - canonical_policy_repr = six.text_type( - sorted(list(six.iteritems(policy)), key=lambda x: six.text_type(x[0])) - ) + canonical_policy_repr = str(sorted(list(policy.items()), key=lambda x: str(x[0]))) policy_hash = hashlib.md5( salt.utils.stringutils.to_bytes(str(canonical_policy_repr)) ).hexdigest() # future lint: disable=blacklisted-function if policy_type.endswith("Type"): policy_type = policy_type[:-4] - return "{0}-{1}-{2}".format(policy_type, policy_name, policy_hash) + return "{}-{}-{}".format(policy_type, policy_name, policy_hash) def absent(name, region=None, key=None, keyid=None, profile=None): @@ -1445,19 +1432,19 @@ def absent(name, region=None, key=None, keyid=None, profile=None): exists = __salt__["boto_elb.exists"](name, region, key, keyid, profile) if exists: if __opts__["test"]: - ret["comment"] = "ELB {0} is set to be removed.".format(name) + ret["comment"] = "ELB {} is set to be removed.".format(name) ret["result"] = None return ret deleted = __salt__["boto_elb.delete"](name, region, key, keyid, profile) if deleted: ret["changes"]["old"] = {"elb": name} ret["changes"]["new"] = {"elb": None} - ret["comment"] = "ELB {0} deleted.".format(name) + ret["comment"] = "ELB {} deleted.".format(name) else: ret["result"] = False - ret["comment"] = "Failed to delete {0} ELB.".format(name) + ret["comment"] = "Failed to delete {} ELB.".format(name) else: - ret["comment"] = "{0} ELB does not exist.".format(name) + ret["comment"] = "{} ELB does not exist.".format(name) return ret @@ -1483,7 +1470,7 @@ def _tags_present(name, tags, region, key, keyid, profile): tags_to_add.pop(_tag) if tags_to_remove: if __opts__["test"]: - msg = "The following tag{0} set to be removed: {1}.".format( + msg = "The following tag{} set to be removed: {}.".format( ("s are" if len(tags_to_remove) > 1 else " is"), ", ".join(tags_to_remove), ) @@ -1495,7 +1482,7 @@ def _tags_present(name, tags, region, key, keyid, profile): ) if not _ret: ret["result"] = False - msg = "Error attempting to delete tag {0}.".format(tags_to_remove) + msg = "Error attempting to delete tag {}.".format(tags_to_remove) ret["comment"] = " ".join([ret["comment"], msg]) return ret if "old" not in ret["changes"]: @@ -1507,14 +1494,14 @@ def _tags_present(name, tags, region, key, keyid, profile): if tags_to_add or tags_to_update: if __opts__["test"]: if tags_to_add: - msg = "The following tag{0} set to be added: {1}.".format( + msg = "The following tag{} set to be added: {}.".format( ("s are" if len(tags_to_add.keys()) > 1 else " is"), ", ".join(tags_to_add.keys()), ) ret["comment"] = " ".join([ret["comment"], msg]) ret["result"] = None if tags_to_update: - msg = "The following tag {0} set to be updated: {1}.".format( + msg = "The following tag {} set to be updated: {}.".format( ( "values are" if len(tags_to_update.keys()) > 1 diff --git a/salt/states/boto_iam_role.py b/salt/states/boto_iam_role.py index 5377b7a34f9..f61c117578e 100644 --- a/salt/states/boto_iam_role.py +++ b/salt/states/boto_iam_role.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage IAM roles ================ @@ -86,13 +85,11 @@ on the IAM role to be persistent. This functionality was added in 2015.8.0. will be used as the default region. """ -from __future__ import absolute_import, print_function, unicode_literals import logging import salt.utils.dictdiffer import salt.utils.dictupdate as dictupdate -from salt.ext import six from salt.utils.odict import OrderedDict log = logging.getLogger(__name__) @@ -258,7 +255,7 @@ def _role_present( role = __salt__["boto_iam.describe_role"](name, region, key, keyid, profile) if not role: if __opts__["test"]: - ret["comment"] = "IAM role {0} is set to be created.".format(name) + ret["comment"] = "IAM role {} is set to be created.".format(name) ret["result"] = None return ret created = __salt__["boto_iam.create_role"]( @@ -267,12 +264,12 @@ def _role_present( if created: ret["changes"]["old"] = {"role": None} ret["changes"]["new"] = {"role": name} - ret["comment"] = "IAM role {0} created.".format(name) + ret["comment"] = "IAM role {} created.".format(name) else: ret["result"] = False - ret["comment"] = "Failed to create {0} IAM role.".format(name) + ret["comment"] = "Failed to create {} IAM role.".format(name) else: - ret["comment"] = "{0} role present.".format(name) + ret["comment"] = "{} role present.".format(name) if not policy_document: _policy_document = __salt__["boto_iam.build_policy"]( region, key, keyid, profile @@ -285,7 +282,7 @@ def _role_present( ): if __opts__["test"]: msg = "Assume role policy document to be updated." - ret["comment"] = "{0} {1}".format(ret["comment"], msg) + ret["comment"] = "{} {}".format(ret["comment"], msg) ret["result"] = None return ret updated = __salt__["boto_iam.update_assume_role_policy"]( @@ -293,7 +290,7 @@ def _role_present( ) if updated: msg = "Assume role policy document updated." - ret["comment"] = "{0} {1}".format(ret["comment"], msg) + ret["comment"] = "{} {}".format(ret["comment"], msg) ret["changes"]["old"] = { "policy_document": role["assume_role_policy_document"] } @@ -301,7 +298,7 @@ def _role_present( else: ret["result"] = False msg = "Failed to update assume role policy." - ret["comment"] = "{0} {1}".format(ret["comment"], msg) + ret["comment"] = "{} {}".format(ret["comment"], msg) return ret @@ -312,7 +309,7 @@ def _instance_profile_present(name, region=None, key=None, keyid=None, profile=N ) if not exists: if __opts__["test"]: - ret["comment"] = "Instance profile {0} is set to be created.".format(name) + ret["comment"] = "Instance profile {} is set to be created.".format(name) ret["result"] = None return ret created = __salt__["boto_iam.create_instance_profile"]( @@ -321,10 +318,10 @@ def _instance_profile_present(name, region=None, key=None, keyid=None, profile=N if created: ret["changes"]["old"] = {"instance_profile": None} ret["changes"]["new"] = {"instance_profile": name} - ret["comment"] = "Instance profile {0} created.".format(name) + ret["comment"] = "Instance profile {} created.".format(name) else: ret["result"] = False - ret["comment"] = "Failed to create {0} instance profile.".format(name) + ret["comment"] = "Failed to create {} instance profile.".format(name) return ret @@ -335,9 +332,7 @@ def _instance_profile_associated(name, region=None, key=None, keyid=None, profil ) if not is_associated: if __opts__["test"]: - ret["comment"] = "Instance profile {0} is set to be associated.".format( - name - ) + ret["comment"] = "Instance profile {} is set to be associated.".format(name) ret["result"] = None return ret associated = __salt__["boto_iam.associate_profile_to_role"]( @@ -346,7 +341,7 @@ def _instance_profile_associated(name, region=None, key=None, keyid=None, profil if associated: ret["changes"]["old"] = {"profile_associated": None} ret["changes"]["new"] = {"profile_associated": True} - ret["comment"] = "Instance profile {0} associated.".format(name) + ret["comment"] = "Instance profile {} associated.".format(name) else: ret["result"] = False ret[ @@ -365,7 +360,7 @@ def _sort_policy(doc): if isinstance(doc, list): return sorted([_sort_policy(i) for i in doc]) elif isinstance(doc, (dict, OrderedDict)): - return dict([(k, _sort_policy(v)) for k, v in six.iteritems(doc)]) + return {k: _sort_policy(v) for k, v in doc.items()} return doc @@ -381,7 +376,7 @@ def _policies_present( ret = {"result": True, "comment": "", "changes": {}} policies_to_create = {} policies_to_delete = [] - for policy_name, policy in six.iteritems(policies): + for policy_name, policy in policies.items(): _policy = __salt__["boto_iam.get_role_policy"]( name, policy_name, region, key, keyid, profile ) @@ -395,13 +390,13 @@ def _policies_present( _to_modify = list(policies_to_delete) _to_modify.extend(policies_to_create) if __opts__["test"]: - ret["comment"] = "{0} policies to be modified on role {1}.".format( + ret["comment"] = "{} policies to be modified on role {}.".format( ", ".join(_to_modify), name ) ret["result"] = None return ret ret["changes"]["old"] = {"policies": _list} - for policy_name, policy in six.iteritems(policies_to_create): + for policy_name, policy in policies_to_create.items(): policy_set = __salt__["boto_iam.create_role_policy"]( name, policy_name, policy, region, key, keyid, profile ) @@ -411,7 +406,7 @@ def _policies_present( ) ret["changes"]["new"] = {"policies": _list} ret["result"] = False - ret["comment"] = "Failed to add policy {0} to role {1}".format( + ret["comment"] = "Failed to add policy {} to role {}".format( policy_name, name ) return ret @@ -425,7 +420,7 @@ def _policies_present( ) ret["changes"]["new"] = {"policies": _list} ret["result"] = False - ret["comment"] = "Failed to remove policy {0} from role {1}".format( + ret["comment"] = "Failed to remove policy {} from role {}".format( policy_name, name ) return ret @@ -433,7 +428,7 @@ def _policies_present( name, region, key, keyid, profile ) ret["changes"]["new"] = {"policies": _list} - ret["comment"] = "{0} policies modified on role {1}.".format( + ret["comment"] = "{} policies modified on role {}.".format( ", ".join(_list), name ) return ret @@ -475,7 +470,7 @@ def _policies_attached( _to_modify = list(policies_to_detach) _to_modify.extend(policies_to_attach) if __opts__["test"]: - ret["comment"] = "{0} policies to be modified on role {1}.".format( + ret["comment"] = "{} policies to be modified on role {}.".format( ", ".join(_to_modify), name ) ret["result"] = None @@ -497,7 +492,7 @@ def _policies_attached( newpolicies = [x.get("policy_arn") for x in _list] ret["changes"]["new"] = {"managed_policies": newpolicies} ret["result"] = False - ret["comment"] = "Failed to add policy {0} to role {1}".format( + ret["comment"] = "Failed to add policy {} to role {}".format( policy_name, name ) return ret @@ -517,7 +512,7 @@ def _policies_attached( newpolicies = [x.get("policy_arn") for x in _list] ret["changes"]["new"] = {"managed_policies": newpolicies} ret["result"] = False - ret["comment"] = "Failed to remove policy {0} from role {1}".format( + ret["comment"] = "Failed to remove policy {} from role {}".format( policy_name, name ) return ret @@ -527,7 +522,7 @@ def _policies_attached( newpolicies = [x.get("policy_arn") for x in _list] log.debug(newpolicies) ret["changes"]["new"] = {"managed_policies": newpolicies} - ret["comment"] = "{0} policies modified on role {1}.".format( + ret["comment"] = "{} policies modified on role {}.".format( ", ".join(newpolicies), name ) return ret @@ -596,19 +591,19 @@ def _role_absent(name, region=None, key=None, keyid=None, profile=None): exists = __salt__["boto_iam.role_exists"](name, region, key, keyid, profile) if exists: if __opts__["test"]: - ret["comment"] = "IAM role {0} is set to be removed.".format(name) + ret["comment"] = "IAM role {} is set to be removed.".format(name) ret["result"] = None return ret deleted = __salt__["boto_iam.delete_role"](name, region, key, keyid, profile) if deleted: ret["changes"]["old"] = {"role": name} ret["changes"]["new"] = {"role": None} - ret["comment"] = "IAM role {0} removed.".format(name) + ret["comment"] = "IAM role {} removed.".format(name) else: ret["result"] = False - ret["comment"] = "Failed to delete {0} iam role.".format(name) + ret["comment"] = "Failed to delete {} iam role.".format(name) else: - ret["comment"] = "{0} role does not exist.".format(name) + ret["comment"] = "{} role does not exist.".format(name) return ret @@ -620,7 +615,7 @@ def _instance_profile_absent(name, region=None, key=None, keyid=None, profile=No ) if exists: if __opts__["test"]: - ret["comment"] = "Instance profile {0} is set to be removed.".format(name) + ret["comment"] = "Instance profile {} is set to be removed.".format(name) ret["result"] = None return ret deleted = __salt__["boto_iam.delete_instance_profile"]( @@ -629,12 +624,12 @@ def _instance_profile_absent(name, region=None, key=None, keyid=None, profile=No if deleted: ret["changes"]["old"] = {"instance_profile": name} ret["changes"]["new"] = {"instance_profile": None} - ret["comment"] = "Instance profile {0} removed.".format(name) + ret["comment"] = "Instance profile {} removed.".format(name) else: ret["result"] = False - ret["comment"] = "Failed to delete {0} instance profile.".format(name) + ret["comment"] = "Failed to delete {} instance profile.".format(name) else: - ret["comment"] = "{0} instance profile does not exist.".format(name) + ret["comment"] = "{} instance profile does not exist.".format(name) return ret @@ -642,10 +637,10 @@ def _policies_absent(name, region=None, key=None, keyid=None, profile=None): ret = {"result": True, "comment": "", "changes": {}} _list = __salt__["boto_iam.list_role_policies"](name, region, key, keyid, profile) if not _list: - ret["comment"] = "No policies in role {0}.".format(name) + ret["comment"] = "No policies in role {}.".format(name) return ret if __opts__["test"]: - ret["comment"] = "{0} policies to be removed from role {1}.".format( + ret["comment"] = "{} policies to be removed from role {}.".format( ", ".join(_list), name ) ret["result"] = None @@ -661,15 +656,13 @@ def _policies_absent(name, region=None, key=None, keyid=None, profile=None): ) ret["changes"]["new"] = {"policies": _list} ret["result"] = False - ret["comment"] = "Failed to add policy {0} to role {1}".format( + ret["comment"] = "Failed to add policy {} to role {}".format( policy_name, name ) return ret _list = __salt__["boto_iam.list_role_policies"](name, region, key, keyid, profile) ret["changes"]["new"] = {"policies": _list} - ret["comment"] = "{0} policies removed from role {1}.".format( - ", ".join(_list), name - ) + ret["comment"] = "{} policies removed from role {}.".format(", ".join(_list), name) return ret @@ -680,10 +673,10 @@ def _policies_detached(name, region=None, key=None, keyid=None, profile=None): ) oldpolicies = [x.get("policy_arn") for x in _list] if not _list: - ret["comment"] = "No attached policies in role {0}.".format(name) + ret["comment"] = "No attached policies in role {}.".format(name) return ret if __opts__["test"]: - ret["comment"] = "{0} policies to be detached from role {1}.".format( + ret["comment"] = "{} policies to be detached from role {}.".format( ", ".join(oldpolicies), name ) ret["result"] = None @@ -700,16 +693,14 @@ def _policies_detached(name, region=None, key=None, keyid=None, profile=None): newpolicies = [x.get("policy_arn") for x in _list] ret["changes"]["new"] = {"managed_policies": newpolicies} ret["result"] = False - ret["comment"] = "Failed to detach {0} from role {1}".format( - policy_arn, name - ) + ret["comment"] = "Failed to detach {} from role {}".format(policy_arn, name) return ret _list = __salt__["boto_iam.list_attached_role_policies"]( name, region=region, key=key, keyid=keyid, profile=profile ) newpolicies = [x.get("policy_arn") for x in _list] ret["changes"]["new"] = {"managed_policies": newpolicies} - ret["comment"] = "{0} policies detached from role {1}.".format( + ret["comment"] = "{} policies detached from role {}.".format( ", ".join(newpolicies), name ) return ret @@ -724,7 +715,7 @@ def _instance_profile_disassociated( ) if is_associated: if __opts__["test"]: - ret["comment"] = "Instance profile {0} is set to be disassociated.".format( + ret["comment"] = "Instance profile {} is set to be disassociated.".format( name ) ret["result"] = None @@ -735,7 +726,7 @@ def _instance_profile_disassociated( if associated: ret["changes"]["old"] = {"profile_associated": True} ret["changes"]["new"] = {"profile_associated": False} - ret["comment"] = "Instance profile {0} disassociated.".format(name) + ret["comment"] = "Instance profile {} disassociated.".format(name) else: ret["result"] = False ret[ diff --git a/salt/states/boto_iot.py b/salt/states/boto_iot.py index 0d038c31756..e14d1541949 100644 --- a/salt/states/boto_iot.py +++ b/salt/states/boto_iot.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage IoT Objects ================== @@ -70,21 +69,15 @@ config: - key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import datetime import logging import os import time -# Import Salt libs import salt.utils.data import salt.utils.json -# Import 3rd-party libs -from salt.ext import six - log = logging.getLogger(__name__) @@ -151,20 +144,20 @@ def thing_type_present( if "error" in r: ret["result"] = False - ret["comment"] = "Failed to create thing type: {0}.".format( + ret["comment"] = "Failed to create thing type: {}.".format( r["error"]["message"] ) return ret if r.get("exists"): ret["result"] = True - ret["comment"] = "Thing type with given name {0} already exists".format( + ret["comment"] = "Thing type with given name {} already exists".format( thingTypeName ) return ret if __opts__["test"]: - ret["comment"] = "Thing type {0} is set to be created.".format(thingTypeName) + ret["comment"] = "Thing type {} is set to be created.".format(thingTypeName) ret["result"] = None return ret @@ -180,7 +173,7 @@ def thing_type_present( if not r.get("created"): ret["result"] = False - ret["comment"] = "Failed to create thing type: {0}.".format( + ret["comment"] = "Failed to create thing type: {}.".format( r["error"]["message"] ) return ret @@ -194,7 +187,7 @@ def thing_type_present( ) ret["changes"]["old"] = {"thing_type": None} ret["changes"]["new"] = _describe - ret["comment"] = "Thing Type {0} created.".format(thingTypeName) + ret["comment"] = "Thing Type {} created.".format(thingTypeName) return ret @@ -238,13 +231,13 @@ def thing_type_absent( ) if "error" in _describe: ret["result"] = False - ret["comment"] = "Failed to delete thing type: {0}.".format( + ret["comment"] = "Failed to delete thing type: {}.".format( _describe["error"]["message"] ) return ret if _describe and not _describe["thing_type"]: - ret["comment"] = "Thing Type {0} does not exist.".format(thingTypeName) + ret["comment"] = "Thing Type {} does not exist.".format(thingTypeName) return ret _existing_thing_type = _describe["thing_type"] @@ -256,7 +249,7 @@ def thing_type_absent( _change_desc = "removed" else: _change_desc = "deprecated and removed" - ret["comment"] = "Thing Type {0} is set to be {1}.".format( + ret["comment"] = "Thing Type {} is set to be {}.".format( thingTypeName, _change_desc ) ret["result"] = None @@ -278,7 +271,7 @@ def thing_type_absent( ) if "error" in _deprecate: ret["result"] = False - ret["comment"] = "Failed to deprecate thing type: {0}.".format( + ret["comment"] = "Failed to deprecate thing type: {}.".format( _deprecate["error"]["message"] ) return ret @@ -320,13 +313,13 @@ def thing_type_absent( ) if not r["deleted"]: ret["result"] = False - ret["comment"] = "Failed to delete thing type: {0}.".format( + ret["comment"] = "Failed to delete thing type: {}.".format( r["error"]["message"] ) return ret ret["changes"]["old"] = _describe ret["changes"]["new"] = {"thing_type": None} - ret["comment"] = "Thing Type {0} deleted.".format(thingTypeName) + ret["comment"] = "Thing Type {} deleted.".format(thingTypeName) return ret @@ -368,12 +361,12 @@ def policy_present( if "error" in r: ret["result"] = False - ret["comment"] = "Failed to create policy: {0}.".format(r["error"]["message"]) + ret["comment"] = "Failed to create policy: {}.".format(r["error"]["message"]) return ret if not r.get("exists"): if __opts__["test"]: - ret["comment"] = "Policy {0} is set to be created.".format(policyName) + ret["comment"] = "Policy {} is set to be created.".format(policyName) ret["result"] = None return ret r = __salt__["boto_iot.create_policy"]( @@ -386,7 +379,7 @@ def policy_present( ) if not r.get("created"): ret["result"] = False - ret["comment"] = "Failed to create policy: {0}.".format( + ret["comment"] = "Failed to create policy: {}.".format( r["error"]["message"] ) return ret @@ -395,11 +388,11 @@ def policy_present( ) ret["changes"]["old"] = {"policy": None} ret["changes"]["new"] = _describe - ret["comment"] = "Policy {0} created.".format(policyName) + ret["comment"] = "Policy {} created.".format(policyName) return ret ret["comment"] = os.linesep.join( - [ret["comment"], "Policy {0} is present.".format(policyName)] + [ret["comment"], "Policy {} is present.".format(policyName)] ) ret["changes"] = {} # policy exists, ensure config matches @@ -407,18 +400,18 @@ def policy_present( policyName=policyName, region=region, key=key, keyid=keyid, profile=profile )["policy"] - if isinstance(_describe["policyDocument"], six.string_types): + if isinstance(_describe["policyDocument"], str): describeDict = salt.utils.json.loads(_describe["policyDocument"]) else: describeDict = _describe["policyDocument"] - if isinstance(policyDocument, six.string_types): + if isinstance(policyDocument, str): policyDocument = salt.utils.json.loads(policyDocument) r = salt.utils.data.compare_dicts(describeDict, policyDocument) if bool(r): if __opts__["test"]: - msg = "Policy {0} set to be modified.".format(policyName) + msg = "Policy {} set to be modified.".format(policyName) ret["comment"] = msg ret["result"] = None return ret @@ -437,7 +430,7 @@ def policy_present( ) if not r.get("created"): ret["result"] = False - ret["comment"] = "Failed to update policy: {0}.".format( + ret["comment"] = "Failed to update policy: {}.".format( r["error"]["message"] ) ret["changes"] = {} @@ -490,15 +483,15 @@ def policy_absent(name, policyName, region=None, key=None, keyid=None, profile=N ) if "error" in r: ret["result"] = False - ret["comment"] = "Failed to delete policy: {0}.".format(r["error"]["message"]) + ret["comment"] = "Failed to delete policy: {}.".format(r["error"]["message"]) return ret if r and not r["exists"]: - ret["comment"] = "Policy {0} does not exist.".format(policyName) + ret["comment"] = "Policy {} does not exist.".format(policyName) return ret if __opts__["test"]: - ret["comment"] = "Policy {0} is set to be removed.".format(policyName) + ret["comment"] = "Policy {} is set to be removed.".format(policyName) ret["result"] = None return ret # delete non-default versions @@ -519,7 +512,7 @@ def policy_absent(name, policyName, region=None, key=None, keyid=None, profile=N ) if not r["deleted"]: ret["result"] = False - ret["comment"] = "Failed to delete policy: {0}.".format( + ret["comment"] = "Failed to delete policy: {}.".format( r["error"]["message"] ) return ret @@ -535,11 +528,11 @@ def policy_absent(name, policyName, region=None, key=None, keyid=None, profile=N ) if not r["deleted"]: ret["result"] = False - ret["comment"] = "Failed to delete policy: {0}.".format(r["error"]["message"]) + ret["comment"] = "Failed to delete policy: {}.".format(r["error"]["message"]) return ret ret["changes"]["old"] = {"policy": policyName} ret["changes"]["new"] = {"policy": None} - ret["comment"] = "Policy {0} deleted.".format(policyName) + ret["comment"] = "Policy {} deleted.".format(policyName) return ret @@ -579,7 +572,7 @@ def policy_attached( if "error" in r: ret["result"] = False - ret["comment"] = "Failed to attach policy: {0}.".format(r["error"]["message"]) + ret["comment"] = "Failed to attach policy: {}.".format(r["error"]["message"]) return ret attached = False @@ -589,7 +582,7 @@ def policy_attached( break if not attached: if __opts__["test"]: - ret["comment"] = "Policy {0} is set to be attached to {1}.".format( + ret["comment"] = "Policy {} is set to be attached to {}.".format( policyName, principal ) ret["result"] = None @@ -604,17 +597,17 @@ def policy_attached( ) if not r.get("attached"): ret["result"] = False - ret["comment"] = "Failed to attach policy: {0}.".format( + ret["comment"] = "Failed to attach policy: {}.".format( r["error"]["message"] ) return ret ret["changes"]["old"] = {"attached": False} ret["changes"]["new"] = {"attached": True} - ret["comment"] = "Policy {0} attached to {1}.".format(policyName, principal) + ret["comment"] = "Policy {} attached to {}.".format(policyName, principal) return ret ret["comment"] = os.linesep.join( - [ret["comment"], "Policy {0} is attached.".format(policyName)] + [ret["comment"], "Policy {} is attached.".format(policyName)] ) ret["changes"] = {} @@ -658,7 +651,7 @@ def policy_detached( if "error" in r: ret["result"] = False - ret["comment"] = "Failed to detached policy: {0}.".format(r["error"]["message"]) + ret["comment"] = "Failed to detached policy: {}.".format(r["error"]["message"]) return ret attached = False @@ -668,7 +661,7 @@ def policy_detached( break if attached: if __opts__["test"]: - ret["comment"] = "Policy {0} is set to be detached from {1}.".format( + ret["comment"] = "Policy {} is set to be detached from {}.".format( policyName, principal ) ret["result"] = None @@ -683,17 +676,17 @@ def policy_detached( ) if not r.get("detached"): ret["result"] = False - ret["comment"] = "Failed to detach policy: {0}.".format( + ret["comment"] = "Failed to detach policy: {}.".format( r["error"]["message"] ) return ret ret["changes"]["old"] = {"attached": True} ret["changes"]["new"] = {"attached": False} - ret["comment"] = "Policy {0} detached from {1}.".format(policyName, principal) + ret["comment"] = "Policy {} detached from {}.".format(policyName, principal) return ret ret["comment"] = os.linesep.join( - [ret["comment"], "Policy {0} is detached.".format(policyName)] + [ret["comment"], "Policy {} is detached.".format(policyName)] ) ret["changes"] = {} @@ -754,12 +747,12 @@ def topic_rule_present( if "error" in r: ret["result"] = False - ret["comment"] = "Failed to create rule: {0}.".format(r["error"]["message"]) + ret["comment"] = "Failed to create rule: {}.".format(r["error"]["message"]) return ret if not r.get("exists"): if __opts__["test"]: - ret["comment"] = "Rule {0} is set to be created.".format(ruleName) + ret["comment"] = "Rule {} is set to be created.".format(ruleName) ret["result"] = None return ret r = __salt__["boto_iot.create_topic_rule"]( @@ -775,18 +768,18 @@ def topic_rule_present( ) if not r.get("created"): ret["result"] = False - ret["comment"] = "Failed to create rule: {0}.".format(r["error"]["message"]) + ret["comment"] = "Failed to create rule: {}.".format(r["error"]["message"]) return ret _describe = __salt__["boto_iot.describe_topic_rule"]( ruleName, region=region, key=key, keyid=keyid, profile=profile ) ret["changes"]["old"] = {"rule": None} ret["changes"]["new"] = _describe - ret["comment"] = "Rule {0} created.".format(ruleName) + ret["comment"] = "Rule {} created.".format(ruleName) return ret ret["comment"] = os.linesep.join( - [ret["comment"], "Rule {0} is present.".format(ruleName)] + [ret["comment"], "Rule {} is present.".format(ruleName)] ) ret["changes"] = {} # policy exists, ensure config matches @@ -794,7 +787,7 @@ def topic_rule_present( ruleName=ruleName, region=region, key=key, keyid=keyid, profile=profile )["rule"] - if isinstance(actions, six.string_types): + if isinstance(actions, str): actions = salt.utils.json.loads(actions) need_update = False @@ -812,7 +805,7 @@ def topic_rule_present( ret["changes"].setdefault("old", {})[var] = _describe[var] if need_update: if __opts__["test"]: - msg = "Rule {0} set to be modified.".format(ruleName) + msg = "Rule {} set to be modified.".format(ruleName) ret["changes"] = {} ret["comment"] = msg ret["result"] = None @@ -831,7 +824,7 @@ def topic_rule_present( ) if not r.get("replaced"): ret["result"] = False - ret["comment"] = "Failed to update rule: {0}.".format(r["error"]["message"]) + ret["comment"] = "Failed to update rule: {}.".format(r["error"]["message"]) ret["changes"] = {} return ret @@ -867,15 +860,15 @@ def topic_rule_absent(name, ruleName, region=None, key=None, keyid=None, profile ) if "error" in r: ret["result"] = False - ret["comment"] = "Failed to delete rule: {0}.".format(r["error"]["message"]) + ret["comment"] = "Failed to delete rule: {}.".format(r["error"]["message"]) return ret if r and not r["exists"]: - ret["comment"] = "Rule {0} does not exist.".format(ruleName) + ret["comment"] = "Rule {} does not exist.".format(ruleName) return ret if __opts__["test"]: - ret["comment"] = "Rule {0} is set to be removed.".format(ruleName) + ret["comment"] = "Rule {} is set to be removed.".format(ruleName) ret["result"] = None return ret r = __salt__["boto_iot.delete_topic_rule"]( @@ -883,9 +876,9 @@ def topic_rule_absent(name, ruleName, region=None, key=None, keyid=None, profile ) if not r["deleted"]: ret["result"] = False - ret["comment"] = "Failed to delete rule: {0}.".format(r["error"]["message"]) + ret["comment"] = "Failed to delete rule: {}.".format(r["error"]["message"]) return ret ret["changes"]["old"] = {"rule": ruleName} ret["changes"]["new"] = {"rule": None} - ret["comment"] = "Rule {0} deleted.".format(ruleName) + ret["comment"] = "Rule {} deleted.".format(ruleName) return ret diff --git a/salt/states/boto_kinesis.py b/salt/states/boto_kinesis.py index 453c0b82ac7..7c0b1cbffb3 100644 --- a/salt/states/boto_kinesis.py +++ b/salt/states/boto_kinesis.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage Kinesis Streams ====================== @@ -57,8 +56,6 @@ pillars or minion config: """ # pylint: disable=undefined-variable -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals # Keep pylint from chocking on ret import logging @@ -143,7 +140,7 @@ def present( if exists["result"] is False: if __opts__["test"]: ret["result"] = None - comments.append("Kinesis stream {0} would be created".format(name)) + comments.append("Kinesis stream {} would be created".format(name)) _add_changes(ret, changes_old, changes_new, comments) return ret else: @@ -153,16 +150,16 @@ def present( if "error" in is_created: ret["result"] = False comments.append( - "Failed to create stream {0}: {1}".format(name, is_created["error"]) + "Failed to create stream {}: {}".format(name, is_created["error"]) ) _add_changes(ret, changes_old, changes_new, comments) return ret - comments.append("Kinesis stream {0} successfully created".format(name)) + comments.append("Kinesis stream {} successfully created".format(name)) changes_new["name"] = name changes_new["num_shards"] = num_shards else: - comments.append("Kinesis stream {0} already exists".format(name)) + comments.append("Kinesis stream {} already exists".format(name)) stream_response = __salt__["boto_kinesis.get_stream_when_active"]( name, region, key, keyid, profile @@ -170,7 +167,7 @@ def present( if "error" in stream_response: ret["result"] = False comments.append( - "Kinesis stream {0}: error getting description: {1}".format( + "Kinesis stream {}: error getting description: {}".format( name, stream_response["error"] ) ) @@ -187,7 +184,7 @@ def present( if __opts__["test"]: ret["result"] = None comments.append( - "Kinesis stream {0}: retention hours would be updated to {1}".format( + "Kinesis stream {}: retention hours would be updated to {}".format( name, retention_hours ) ) @@ -204,7 +201,7 @@ def present( if "error" in retention_updated: ret["result"] = False comments.append( - "Kinesis stream {0}: failed to update retention hours: {1}".format( + "Kinesis stream {}: failed to update retention hours: {}".format( name, retention_updated["error"] ) ) @@ -212,7 +209,7 @@ def present( return ret comments.append( - "Kinesis stream {0}: retention hours was successfully updated".format( + "Kinesis stream {}: retention hours was successfully updated".format( name ) ) @@ -227,7 +224,7 @@ def present( if "error" in stream_response: ret["result"] = False comments.append( - "Kinesis stream {0}: error getting description: {1}".format( + "Kinesis stream {}: error getting description: {}".format( name, stream_response["error"] ) ) @@ -237,13 +234,13 @@ def present( stream_details = stream_response["result"]["StreamDescription"] else: comments.append( - "Kinesis stream {0}: retention hours did not require change, already set at {1}".format( + "Kinesis stream {}: retention hours did not require change, already set at {}".format( name, old_retention_hours ) ) else: comments.append( - "Kinesis stream {0}: did not configure retention hours".format(name) + "Kinesis stream {}: did not configure retention hours".format(name) ) # Configure enhanced monitoring @@ -277,7 +274,7 @@ def present( if __opts__["test"]: ret["result"] = None comments.append( - "Kinesis stream {0}: would enable enhanced monitoring for {1}".format( + "Kinesis stream {}: would enable enhanced monitoring for {}".format( name, enable_metrics ) ) @@ -289,7 +286,7 @@ def present( if "error" in metrics_enabled: ret["result"] = False comments.append( - "Kinesis stream {0}: failed to enable enhanced monitoring: {1}".format( + "Kinesis stream {}: failed to enable enhanced monitoring: {}".format( name, metrics_enabled["error"] ) ) @@ -297,7 +294,7 @@ def present( return ret comments.append( - "Kinesis stream {0}: enhanced monitoring was enabled for shard-level metrics {1}".format( + "Kinesis stream {}: enhanced monitoring was enabled for shard-level metrics {}".format( name, enable_metrics ) ) @@ -306,7 +303,7 @@ def present( if __opts__["test"]: ret["result"] = None comments.append( - "Kinesis stream {0}: would disable enhanced monitoring for {1}".format( + "Kinesis stream {}: would disable enhanced monitoring for {}".format( name, disable_metrics ) ) @@ -318,7 +315,7 @@ def present( if "error" in metrics_disabled: ret["result"] = False comments.append( - "Kinesis stream {0}: failed to disable enhanced monitoring: {1}".format( + "Kinesis stream {}: failed to disable enhanced monitoring: {}".format( name, metrics_disabled["error"] ) ) @@ -326,14 +323,14 @@ def present( return ret comments.append( - "Kinesis stream {0}: enhanced monitoring was disabled for shard-level metrics {1}".format( + "Kinesis stream {}: enhanced monitoring was disabled for shard-level metrics {}".format( name, disable_metrics ) ) if len(disable_metrics) == 0 and len(enable_metrics) == 0: comments.append( - "Kinesis stream {0}: enhanced monitoring did not require change, already set at {1}".format( + "Kinesis stream {}: enhanced monitoring did not require change, already set at {}".format( name, ( old_enhanced_monitoring @@ -351,7 +348,7 @@ def present( ) else: comments.append( - "Kinesis stream {0}: did not configure enhanced monitoring".format(name) + "Kinesis stream {}: did not configure enhanced monitoring".format(name) ) # Reshard stream if necessary @@ -366,7 +363,7 @@ def present( if __opts__["test"]: ret["result"] = None comments.append( - "Kinesis stream {0}: would be resharded from {1} to {2} shards".format( + "Kinesis stream {}: would be resharded from {} to {} shards".format( name, old_num_shards, num_shards ) ) @@ -388,7 +385,7 @@ def present( if "error" in reshard_response: ret["result"] = False comments.append( - "Encountered error while resharding {0}: {1}".format( + "Encountered error while resharding {}: {}".format( name, reshard_response["error"] ) ) @@ -398,7 +395,7 @@ def present( continue_reshard = reshard_response["result"] comments.append( - "Kinesis stream {0}: successfully resharded to {1} shards".format( + "Kinesis stream {}: successfully resharded to {} shards".format( name, num_shards ) ) @@ -406,13 +403,13 @@ def present( changes_new["num_shards"] = num_shards else: comments.append( - "Kinesis stream {0}: did not require resharding, remains at {1} shards".format( + "Kinesis stream {}: did not require resharding, remains at {} shards".format( name, old_num_shards ) ) else: comments.append( - "Kinesis stream {0}: did not reshard, remains at {1} shards".format( + "Kinesis stream {}: did not reshard, remains at {} shards".format( name, old_num_shards ) ) @@ -445,11 +442,11 @@ def absent(name, region=None, key=None, keyid=None, profile=None): exists = __salt__["boto_kinesis.exists"](name, region, key, keyid, profile) if exists["result"] is False: - ret["comment"] = "Kinesis stream {0} does not exist".format(name) + ret["comment"] = "Kinesis stream {} does not exist".format(name) return ret if __opts__["test"]: - ret["comment"] = "Kinesis stream {0} would be deleted".format(name) + ret["comment"] = "Kinesis stream {} would be deleted".format(name) ret["result"] = None return ret @@ -457,14 +454,14 @@ def absent(name, region=None, key=None, keyid=None, profile=None): name, region, key, keyid, profile ) if "error" in is_deleted: - ret["comment"] = "Failed to delete stream {0}: {1}".format( + ret["comment"] = "Failed to delete stream {}: {}".format( name, is_deleted["error"] ) ret["result"] = False else: - ret["comment"] = "Deleted stream {0}".format(name) - ret["changes"].setdefault("old", "Stream {0} exists".format(name)) - ret["changes"].setdefault("new", "Stream {0} deleted".format(name)) + ret["comment"] = "Deleted stream {}".format(name) + ret["changes"].setdefault("old", "Stream {} exists".format(name)) + ret["changes"].setdefault("new", "Stream {} deleted".format(name)) return ret diff --git a/salt/states/boto_kms.py b/salt/states/boto_kms.py index b5e328cdc52..aadc02093e8 100644 --- a/salt/states/boto_kms.py +++ b/salt/states/boto_kms.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage KMS keys, key policies and grants. @@ -56,7 +55,6 @@ config: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs """ -from __future__ import absolute_import, print_function, unicode_literals import salt.utils.dictupdate as dictupdate from salt.exceptions import SaltInvocationError @@ -176,11 +174,11 @@ def _key_present( profile, ): ret = {"result": True, "comment": "", "changes": {}} - alias = "alias/{0}".format(name) + alias = "alias/{}".format(name) r = __salt__["boto_kms.key_exists"](alias, region, key, keyid, profile) if "error" in r: ret["result"] = False - ret["comment"] = "Error when attempting to find key: {0}.".format( + ret["comment"] = "Error when attempting to find key: {}.".format( r["error"]["message"] ) return ret @@ -194,7 +192,7 @@ def _key_present( ) if "error" in rc: ret["result"] = False - ret["comment"] = "Failed to create key: {0}".format(rc["error"]["message"]) + ret["comment"] = "Failed to create key: {}".format(rc["error"]["message"]) return ret key_metadata = rc["key_metadata"] kms_key_id = key_metadata["KeyId"] @@ -207,19 +205,19 @@ def _key_present( # for not including alias in the create_key call. ret["result"] = False ret["comment"] = ( - "Failed to create key alias for key_id {0}. This resource " + "Failed to create key alias for key_id {}. This resource " "will be left dangling. Please clean manually. " - "Error: {1}".format(kms_key_id, rn["error"]["message"]) + "Error: {}".format(kms_key_id, rn["error"]["message"]) ) return ret ret["changes"]["old"] = {"key": None} ret["changes"]["new"] = {"key": name} - ret["comment"] = "Key {0} created.".format(name) + ret["comment"] = "Key {} created.".format(name) else: rd = __salt__["boto_kms.describe_key"](alias, region, key, keyid, profile) if "error" in rd: ret["result"] = False - ret["comment"] = "Failed to update key: {0}.".format(rd["error"]["message"]) + ret["comment"] = "Failed to update key: {}.".format(rd["error"]["message"]) return ret key_metadata = rd["key_metadata"] _ret = _key_description(key_metadata, description, region, key, keyid, profile) @@ -269,11 +267,11 @@ def _key_enabled(key_metadata, enabled, region, key, keyid, profile): event = "Disabled" if "error" in re: ret["result"] = False - ret["comment"] = "Failed to update key enabled status: {0}.".format( + ret["comment"] = "Failed to update key enabled status: {}.".format( re["error"]["message"] ) else: - ret["comment"] = "{0} key.".format(event) + ret["comment"] = "{} key.".format(event) return ret @@ -290,7 +288,7 @@ def _key_description(key_metadata, description, region, key, keyid, profile): ) if "error" in rdu: ret["result"] = False - ret["comment"] = "Failed to update key description: {0}.".format( + ret["comment"] = "Failed to update key description: {}.".format( rdu["error"]["message"] ) else: @@ -333,7 +331,7 @@ def _key_rotation(key_metadata, key_rotation, region, key, keyid, profile): ret["comment"] = msg return ret ret["result"] = False - ret["comment"] = "Failed to set key rotation: {0}.".format( + ret["comment"] = "Failed to set key rotation: {}.".format( rk["error"]["message"] ) else: @@ -341,7 +339,7 @@ def _key_rotation(key_metadata, key_rotation, region, key, keyid, profile): "old": {"key_rotation": not key_rotation}, "new": {"key_rotation": key_rotation}, } - ret["comment"] = "Set key rotation policy to {0}.".format(key_rotation) + ret["comment"] = "Set key rotation policy to {}.".format(key_rotation) return ret @@ -354,9 +352,7 @@ def _key_policy(key_metadata, policy, region, key, keyid, profile): if rkp["key_policy"] == policy: return ret if __opts__["test"]: - ret["comment"] = "{0} Key set to have key policy updated.".format( - ret["comment"] - ) + ret["comment"] = "{} Key set to have key policy updated.".format(ret["comment"]) ret["result"] = None return ret rpkp = __salt__["boto_kms.put_key_policy"]( @@ -364,7 +360,7 @@ def _key_policy(key_metadata, policy, region, key, keyid, profile): ) if "error" in rpkp: ret["result"] = False - ret["comment"] = "{0} Failed to update key policy: {1}".format( + ret["comment"] = "{} Failed to update key policy: {}".format( ret["comment"], rpkp["error"]["message"] ) else: diff --git a/salt/states/boto_lambda.py b/salt/states/boto_lambda.py index 2ca8249e38d..91ee60f8e7f 100644 --- a/salt/states/boto_lambda.py +++ b/salt/states/boto_lambda.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage Lambda Functions ======================= @@ -60,8 +59,6 @@ config: """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals import hashlib import logging @@ -73,9 +70,6 @@ import salt.utils.files import salt.utils.json from salt.exceptions import SaltInvocationError -# Import Salt Libs -from salt.ext import six - log = logging.getLogger(__name__) @@ -225,22 +219,22 @@ def function_present( ret = {"name": FunctionName, "result": True, "comment": "", "changes": {}} if Permissions is not None: - if isinstance(Permissions, six.string_types): + if isinstance(Permissions, str): Permissions = salt.utils.json.loads(Permissions) - required_keys = set(("Action", "Principal")) - optional_keys = set(("SourceArn", "SourceAccount", "Qualifier")) - for sid, permission in six.iteritems(Permissions): + required_keys = {"Action", "Principal"} + optional_keys = {"SourceArn", "SourceAccount", "Qualifier"} + for sid, permission in Permissions.items(): keyset = set(permission.keys()) if not keyset.issuperset(required_keys): raise SaltInvocationError( - "{0} are required for each permission " + "{} are required for each permission " "specification".format(", ".join(required_keys)) ) keyset = keyset - required_keys keyset = keyset - optional_keys if bool(keyset): raise SaltInvocationError( - "Invalid permission value {0}".format(", ".join(keyset)) + "Invalid permission value {}".format(", ".join(keyset)) ) r = __salt__["boto_lambda.function_exists"]( @@ -249,14 +243,14 @@ def function_present( if "error" in r: ret["result"] = False - ret["comment"] = "Failed to create function: " "{0}.".format( + ret["comment"] = "Failed to create function: " "{}.".format( r["error"]["message"] ) return ret if not r.get("exists"): if __opts__["test"]: - ret["comment"] = "Function {0} is set to be created.".format(FunctionName) + ret["comment"] = "Function {} is set to be created.".format(FunctionName) ret["result"] = None return ret r = __salt__["boto_lambda.create_function"]( @@ -282,13 +276,13 @@ def function_present( ) if not r.get("created"): ret["result"] = False - ret["comment"] = "Failed to create function: " "{0}.".format( + ret["comment"] = "Failed to create function: " "{}.".format( r["error"]["message"] ) return ret if Permissions: - for sid, permission in six.iteritems(Permissions): + for sid, permission in Permissions.items(): r = __salt__["boto_lambda.add_permission"]( FunctionName=FunctionName, StatementId=sid, @@ -300,7 +294,7 @@ def function_present( ) if not r.get("updated"): ret["result"] = False - ret["comment"] = "Failed to create function: " "{0}.".format( + ret["comment"] = "Failed to create function: " "{}.".format( r["error"]["message"] ) @@ -312,11 +306,11 @@ def function_present( )["permissions"] ret["changes"]["old"] = {"function": None} ret["changes"]["new"] = _describe - ret["comment"] = "Function {0} created.".format(FunctionName) + ret["comment"] = "Function {} created.".format(FunctionName) return ret ret["comment"] = os.linesep.join( - [ret["comment"], "Function {0} is present.".format(FunctionName)] + [ret["comment"], "Function {} is present.".format(FunctionName)] ) ret["changes"] = {} # function exists, ensure config matches @@ -380,11 +374,11 @@ def _get_role_arn(name, region=None, key=None, keyid=None, profile=None): account_id = __salt__["boto_iam.get_account_id"]( region=region, key=key, keyid=keyid, profile=profile ) - return "arn:aws:iam::{0}:role/{1}".format(account_id, name) + return "arn:aws:iam::{}:role/{}".format(account_id, name) def _resolve_vpcconfig(conf, region=None, key=None, keyid=None, profile=None): - if isinstance(conf, six.string_types): + if isinstance(conf, str): conf = salt.utils.json.loads(conf) if not conf: # if the conf is None, we should explicitly set the VpcConfig to @@ -438,7 +432,7 @@ def _function_config_present( "MemorySize": MemorySize, } - for key, val in six.iteritems(options): + for key, val in options.items(): if func[key] != val: need_update = True ret["changes"].setdefault("old", {})[key] = func[key] @@ -468,7 +462,7 @@ def _function_config_present( [ret["comment"], "Function config to be modified"] ) if __opts__["test"]: - ret["comment"] = "Function {0} set to be modified.".format(FunctionName) + ret["comment"] = "Function {} set to be modified.".format(FunctionName) ret["result"] = None return ret _r = __salt__["boto_lambda.update_function_config"]( @@ -489,7 +483,7 @@ def _function_config_present( ) if not _r.get("updated"): ret["result"] = False - ret["comment"] = "Failed to update function: " "{0}.".format( + ret["comment"] = "Failed to update function: " "{}.".format( _r["error"]["message"] ) ret["changes"] = {} @@ -509,7 +503,7 @@ def _function_code_present( dlZipFile = __salt__["cp.cache_file"](path=ZipFile) if dlZipFile is False: ret["result"] = False - ret["comment"] = "Failed to cache ZipFile `{0}`.".format(ZipFile) + ret["comment"] = "Failed to cache ZipFile `{}`.".format(ZipFile) return ret ZipFile = dlZipFile size = os.path.getsize(ZipFile) @@ -529,7 +523,7 @@ def _function_code_present( update = True if update: if __opts__["test"]: - ret["comment"] = "Function {0} set to be modified.".format(FunctionName) + ret["comment"] = "Function {} set to be modified.".format(FunctionName) ret["result"] = None return ret ret["changes"]["old"] = { @@ -549,7 +543,7 @@ def _function_code_present( ) if not func.get("updated"): ret["result"] = False - ret["comment"] = "Failed to update function: " "{0}.".format( + ret["comment"] = "Failed to update function: " "{}.".format( func["error"]["message"] ) ret["changes"] = {} @@ -587,10 +581,10 @@ def _function_permissions_present( [ret["comment"], "Function permissions to be modified"] ) if __opts__["test"]: - ret["comment"] = "Function {0} set to be modified.".format(FunctionName) + ret["comment"] = "Function {} set to be modified.".format(FunctionName) ret["result"] = None return ret - for sid, diff in six.iteritems(diffs): + for sid, diff in diffs.items(): if diff.get("old", "") != "": # There's a permssion that needs to be removed _r = __salt__["boto_lambda.remove_permission"]( @@ -628,7 +622,7 @@ def _function_permissions_present( oldperms[sid] = {} if not _r.get("updated"): ret["result"] = False - ret["comment"] = "Failed to update function: " "{0}.".format( + ret["comment"] = "Failed to update function: " "{}.".format( _r["error"]["message"] ) ret["changes"] = {} @@ -668,15 +662,15 @@ def function_absent( ) if "error" in r: ret["result"] = False - ret["comment"] = "Failed to delete function: {0}.".format(r["error"]["message"]) + ret["comment"] = "Failed to delete function: {}.".format(r["error"]["message"]) return ret if r and not r["exists"]: - ret["comment"] = "Function {0} does not exist.".format(FunctionName) + ret["comment"] = "Function {} does not exist.".format(FunctionName) return ret if __opts__["test"]: - ret["comment"] = "Function {0} is set to be removed.".format(FunctionName) + ret["comment"] = "Function {} is set to be removed.".format(FunctionName) ret["result"] = None return ret r = __salt__["boto_lambda.delete_function"]( @@ -684,13 +678,13 @@ def function_absent( ) if not r["deleted"]: ret["result"] = False - ret["comment"] = "Failed to delete function: " "{0}.".format( + ret["comment"] = "Failed to delete function: " "{}.".format( r["error"]["message"] ) return ret ret["changes"]["old"] = {"function": FunctionName} ret["changes"]["new"] = {"function": None} - ret["comment"] = "Function {0} deleted.".format(FunctionName) + ret["comment"] = "Function {} deleted.".format(FunctionName) return ret @@ -750,12 +744,12 @@ def alias_present( if "error" in r: ret["result"] = False - ret["comment"] = "Failed to create alias: " "{0}.".format(r["error"]["message"]) + ret["comment"] = "Failed to create alias: " "{}.".format(r["error"]["message"]) return ret if not r.get("exists"): if __opts__["test"]: - ret["comment"] = "Alias {0} is set to be created.".format(Name) + ret["comment"] = "Alias {} is set to be created.".format(Name) ret["result"] = None return ret r = __salt__["boto_lambda.create_alias"]( @@ -770,7 +764,7 @@ def alias_present( ) if not r.get("created"): ret["result"] = False - ret["comment"] = "Failed to create alias: " "{0}.".format( + ret["comment"] = "Failed to create alias: " "{}.".format( r["error"]["message"] ) return ret @@ -779,11 +773,11 @@ def alias_present( ) ret["changes"]["old"] = {"alias": None} ret["changes"]["new"] = _describe - ret["comment"] = "Alias {0} created.".format(Name) + ret["comment"] = "Alias {} created.".format(Name) return ret ret["comment"] = os.linesep.join( - [ret["comment"], "Alias {0} is present.".format(Name)] + [ret["comment"], "Alias {} is present.".format(Name)] ) ret["changes"] = {} _describe = __salt__["boto_lambda.describe_alias"]( @@ -793,7 +787,7 @@ def alias_present( need_update = False options = {"FunctionVersion": FunctionVersion, "Description": Description} - for key, val in six.iteritems(options): + for key, val in options.items(): if _describe[key] != val: need_update = True ret["changes"].setdefault("old", {})[key] = _describe[key] @@ -803,7 +797,7 @@ def alias_present( [ret["comment"], "Alias config to be modified"] ) if __opts__["test"]: - ret["comment"] = "Alias {0} set to be modified.".format(Name) + ret["comment"] = "Alias {} set to be modified.".format(Name) ret["result"] = None return ret _r = __salt__["boto_lambda.update_alias"]( @@ -818,7 +812,7 @@ def alias_present( ) if not _r.get("updated"): ret["result"] = False - ret["comment"] = "Failed to update alias: " "{0}.".format( + ret["comment"] = "Failed to update alias: " "{}.".format( _r["error"]["message"] ) ret["changes"] = {} @@ -861,15 +855,15 @@ def alias_absent( ) if "error" in r: ret["result"] = False - ret["comment"] = "Failed to delete alias: " "{0}.".format(r["error"]["message"]) + ret["comment"] = "Failed to delete alias: " "{}.".format(r["error"]["message"]) return ret if r and not r["exists"]: - ret["comment"] = "Alias {0} does not exist.".format(Name) + ret["comment"] = "Alias {} does not exist.".format(Name) return ret if __opts__["test"]: - ret["comment"] = "Alias {0} is set to be removed.".format(Name) + ret["comment"] = "Alias {} is set to be removed.".format(Name) ret["result"] = None return ret r = __salt__["boto_lambda.delete_alias"]( @@ -877,11 +871,11 @@ def alias_absent( ) if not r["deleted"]: ret["result"] = False - ret["comment"] = "Failed to delete alias: " "{0}.".format(r["error"]["message"]) + ret["comment"] = "Failed to delete alias: " "{}.".format(r["error"]["message"]) return ret ret["changes"]["old"] = {"alias": Name} ret["changes"]["new"] = {"alias": None} - ret["comment"] = "Alias {0} deleted.".format(Name) + ret["comment"] = "Alias {} deleted.".format(Name) return ret @@ -896,7 +890,7 @@ def _get_function_arn(name, region=None, key=None, keyid=None, profile=None): region = profile["region"] if region is None: region = "us-east-1" - return "arn:aws:lambda:{0}:{1}:function:{2}".format(region, account_id, name) + return "arn:aws:lambda:{}:{}:function:{}".format(region, account_id, name) def event_source_mapping_present( @@ -973,14 +967,14 @@ def event_source_mapping_present( if "error" in r: ret["result"] = False - ret["comment"] = "Failed to create event source mapping: " "{0}.".format( + ret["comment"] = "Failed to create event source mapping: " "{}.".format( r["error"]["message"] ) return ret if not r.get("exists"): if __opts__["test"]: - ret["comment"] = "Event source mapping {0} is set " "to be created.".format( + ret["comment"] = "Event source mapping {} is set " "to be created.".format( FunctionName ) ret["result"] = None @@ -998,7 +992,7 @@ def event_source_mapping_present( ) if not r.get("created"): ret["result"] = False - ret["comment"] = "Failed to create event source mapping: " "{0}.".format( + ret["comment"] = "Failed to create event source mapping: " "{}.".format( r["error"]["message"] ) return ret @@ -1013,7 +1007,7 @@ def event_source_mapping_present( ret["name"] = _describe["event_source_mapping"]["UUID"] ret["changes"]["old"] = {"event_source_mapping": None} ret["changes"]["new"] = _describe - ret["comment"] = "Event source mapping {0} " "created.".format(ret["name"]) + ret["comment"] = "Event source mapping {} " "created.".format(ret["name"]) return ret ret["comment"] = os.linesep.join( @@ -1032,7 +1026,7 @@ def event_source_mapping_present( need_update = False options = {"BatchSize": BatchSize} - for key, val in six.iteritems(options): + for key, val in options.items(): if _describe[key] != val: need_update = True ret["changes"].setdefault("old", {})[key] = _describe[key] @@ -1052,7 +1046,7 @@ def event_source_mapping_present( [ret["comment"], "Event source mapping to be modified"] ) if __opts__["test"]: - ret["comment"] = "Event source mapping {0} set to be modified.".format( + ret["comment"] = "Event source mapping {} set to be modified.".format( _describe["UUID"] ) ret["result"] = None @@ -1069,7 +1063,7 @@ def event_source_mapping_present( ) if not _r.get("updated"): ret["result"] = False - ret["comment"] = "Failed to update mapping: " "{0}.".format( + ret["comment"] = "Failed to update mapping: " "{}.".format( _r["error"]["message"] ) ret["changes"] = {} @@ -1117,7 +1111,7 @@ def event_source_mapping_absent( ) if "error" in desc: ret["result"] = False - ret["comment"] = "Failed to delete event source mapping: " "{0}.".format( + ret["comment"] = "Failed to delete event source mapping: " "{}.".format( desc["error"]["message"] ) return ret @@ -1141,7 +1135,7 @@ def event_source_mapping_absent( ) if not r["deleted"]: ret["result"] = False - ret["comment"] = "Failed to delete event source mapping: {0}.".format( + ret["comment"] = "Failed to delete event source mapping: {}.".format( r["error"]["message"] ) return ret diff --git a/salt/states/boto_lc.py b/salt/states/boto_lc.py index 8e99dd564ab..3999ccd98fd 100644 --- a/salt/states/boto_lc.py +++ b/salt/states/boto_lc.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage Launch Configurations @@ -98,7 +97,6 @@ and autoscale groups are completely dependent on each other. key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 """ -from __future__ import absolute_import, print_function, unicode_literals from salt.exceptions import SaltInvocationError diff --git a/salt/states/boto_rds.py b/salt/states/boto_rds.py index d3336dd1789..e0fff2ca7ea 100644 --- a/salt/states/boto_rds.py +++ b/salt/states/boto_rds.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage RDSs =========== @@ -69,8 +68,6 @@ config: """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals import logging import os @@ -78,9 +75,6 @@ import os import salt.utils.data from salt.exceptions import SaltInvocationError -# Import Salt Libs -from salt.ext import six - log = logging.getLogger(__name__) @@ -312,7 +306,7 @@ def present( if not r.get("exists"): if __opts__["test"]: - ret["comment"] = "RDS instance {0} would be created.".format(name) + ret["comment"] = "RDS instance {} would be created.".format(name) ret["result"] = None return ret @@ -364,7 +358,7 @@ def present( if not r.get("created"): ret["result"] = False - ret["comment"] = "Failed to create RDS instance {0}.".format( + ret["comment"] = "Failed to create RDS instance {}.".format( r["error"]["message"] ) return ret @@ -380,9 +374,9 @@ def present( profile=profile, ) } - ret["comment"] = "RDS instance {0} created.".format(name) + ret["comment"] = "RDS instance {} created.".format(name) else: - ret["comment"] = "RDS instance {0} exists.".format(name) + ret["comment"] = "RDS instance {} exists.".format(name) return ret @@ -419,7 +413,7 @@ def replica_present( ) if not replica_exists.get("exists"): if __opts__["test"]: - ret["comment"] = "RDS read replica {0} is set to be created ".format(name) + ret["comment"] = "RDS read replica {} is set to be created ".format(name) ret["result"] = None return ret created = __salt__["boto_rds.create_read_replica"]( @@ -439,7 +433,7 @@ def replica_present( profile, ) if created: - ret["comment"] = "RDS replica {0} created.".format(name) + ret["comment"] = "RDS replica {} created.".format(name) ret["changes"]["old"] = {"instance": None} ret["changes"]["new"] = { "instance": __salt__["boto_rds.describe_db_instances"]( @@ -453,7 +447,7 @@ def replica_present( } else: ret["result"] = False - ret["comment"] = "Failed to create RDS replica {0}.".format(name) + ret["comment"] = "Failed to create RDS replica {}.".format(name) else: jmespath = "DBInstances[0].DBParameterGroups[0].DBParameterGroupName" pmg_name = __salt__["boto_rds.describe_db_instances"]( @@ -477,13 +471,13 @@ def replica_present( if not modified: ret["result"] = False ret["comment"] = ( - "Failed to update parameter group of {0} RDS " + "Failed to update parameter group of {} RDS " "instance.".format(name) ) ret["changes"]["old"] = pmg_name ret["changes"]["new"] = db_parameter_group_name ret["result"] = True - ret["comment"] = "RDS replica {0} exists.".format(name) + ret["comment"] = "RDS replica {} exists.".format(name) return ret @@ -548,13 +542,13 @@ def subnet_group_present( ) if "error" in r: - ret["comment"] = "Error looking up subnet ids: {0}".format( + ret["comment"] = "Error looking up subnet ids: {}".format( r["error"]["message"] ) ret["result"] = False return ret if r["id"] is None: - ret["comment"] = "Subnet {0} does not exist.".format(i) + ret["comment"] = "Subnet {} does not exist.".format(i) ret["result"] = False return ret subnet_ids.append(r["id"]) @@ -564,7 +558,7 @@ def subnet_group_present( ) if not exists.get("exists"): if __opts__["test"]: - ret["comment"] = "Subnet group {0} is set to be created.".format(name) + ret["comment"] = "Subnet group {} is set to be created.".format(name) ret["result"] = None return ret created = __salt__["boto_rds.create_subnet_group"]( @@ -580,14 +574,14 @@ def subnet_group_present( if not created: ret["result"] = False - ret["comment"] = "Failed to create {0} subnet group.".format(name) + ret["comment"] = "Failed to create {} subnet group.".format(name) return ret ret["changes"]["old"] = None ret["changes"]["new"] = name - ret["comment"] = "Subnet {0} created.".format(name) + ret["comment"] = "Subnet {} created.".format(name) return ret else: - ret["comment"] = "Subnet {0} present.".format(name) + ret["comment"] = "Subnet {} present.".format(name) return ret @@ -649,11 +643,11 @@ def absent( ) if not current: ret["result"] = True - ret["comment"] = "{0} RDS already absent.".format(name) + ret["comment"] = "{} RDS already absent.".format(name) return ret if __opts__["test"]: - ret["comment"] = "RDS {0} would be removed.".format(name) + ret["comment"] = "RDS {} would be removed.".format(name) ret["result"] = None return ret deleted = __salt__["boto_rds.delete"]( @@ -670,11 +664,11 @@ def absent( ) if not deleted: ret["result"] = False - ret["comment"] = "Failed to delete {0} RDS.".format(name) + ret["comment"] = "Failed to delete {} RDS.".format(name) return ret ret["changes"]["old"] = {"instance": current[0]} ret["changes"]["new"] = {"instance": None} - ret["comment"] = "RDS {0} deleted.".format(name) + ret["comment"] = "RDS {} deleted.".format(name) return ret @@ -688,11 +682,11 @@ def subnet_group_absent( ) if not exists: ret["result"] = True - ret["comment"] = "{0} RDS subnet group does not exist.".format(name) + ret["comment"] = "{} RDS subnet group does not exist.".format(name) return ret if __opts__["test"]: - ret["comment"] = "RDS subnet group {0} is set to be removed.".format(name) + ret["comment"] = "RDS subnet group {} is set to be removed.".format(name) ret["result"] = None return ret deleted = __salt__["boto_rds.delete_subnet_group"]( @@ -700,11 +694,11 @@ def subnet_group_absent( ) if not deleted: ret["result"] = False - ret["comment"] = "Failed to delete {0} RDS subnet group.".format(name) + ret["comment"] = "Failed to delete {} RDS subnet group.".format(name) return ret ret["changes"]["old"] = name ret["changes"]["new"] = None - ret["comment"] = "RDS subnet group {0} deleted.".format(name) + ret["comment"] = "RDS subnet group {} deleted.".format(name) return ret @@ -769,7 +763,7 @@ def parameter_present( ) if not res.get("exists"): if __opts__["test"]: - ret["comment"] = "Parameter group {0} is set to be created.".format(name) + ret["comment"] = "Parameter group {} is set to be created.".format(name) ret["result"] = None return ret created = __salt__["boto_rds.create_parameter_group"]( @@ -784,12 +778,12 @@ def parameter_present( ) if not created: ret["result"] = False - ret["comment"] = "Failed to create {0} parameter group.".format(name) + ret["comment"] = "Failed to create {} parameter group.".format(name) return ret ret["changes"]["New Parameter Group"] = name - ret["comment"] = "Parameter group {0} created.".format(name) + ret["comment"] = "Parameter group {} created.".format(name) else: - ret["comment"] = "Parameter group {0} present.".format(name) + ret["comment"] = "Parameter group {} present.".format(name) if parameters is not None: params = {} changed = {} @@ -798,7 +792,7 @@ def parameter_present( if type(value) is bool: params[k] = "on" if value else "off" else: - params[k] = six.text_type(value) + params[k] = str(value) log.debug("Parameters from user are : %s.", params) options = __salt__["boto_rds.describe_parameters"]( name=name, region=region, key=key, keyid=keyid, profile=profile @@ -806,13 +800,13 @@ def parameter_present( if not options.get("result"): ret["result"] = False ret["comment"] = os.linesep.join( - [ret["comment"], "Faled to get parameters for group {0}.".format(name)] + [ret["comment"], "Faled to get parameters for group {}.".format(name)] ) return ret for parameter in options["parameters"].values(): if parameter["ParameterName"] in params and params.get( parameter["ParameterName"] - ) != six.text_type(parameter["ParameterValue"]): + ) != str(parameter["ParameterValue"]): log.debug( "Values that are being compared for %s are %s:%s.", parameter["ParameterName"], @@ -827,7 +821,7 @@ def parameter_present( ret["comment"] = os.linesep.join( [ ret["comment"], - "Parameters {0} for group {1} are set to be changed.".format( + "Parameters {} for group {} are set to be changed.".format( changed, name ), ] @@ -849,7 +843,7 @@ def parameter_present( ret["comment"] = os.linesep.join( [ ret["comment"], - "Failed to change parameters {0} for group {1}:".format( + "Failed to change parameters {} for group {}:".format( changed, name ), update["error"]["message"], @@ -860,14 +854,14 @@ def parameter_present( ret["comment"] = os.linesep.join( [ ret["comment"], - "Parameters {0} for group {1} are changed.".format(changed, name), + "Parameters {} for group {} are changed.".format(changed, name), ] ) else: ret["comment"] = os.linesep.join( [ ret["comment"], - "Parameters {0} for group {1} are present.".format(params, name), + "Parameters {} for group {} are present.".format(params, name), ] ) return ret diff --git a/salt/states/boto_route53.py b/salt/states/boto_route53.py index 4e81832d323..b5ab874573b 100644 --- a/salt/states/boto_route53.py +++ b/salt/states/boto_route53.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage Route53 records @@ -71,17 +70,13 @@ passed in as a dict, or as a string to pull from pillars or minion config: key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals import logging import uuid -# Import Salt Libs import salt.utils.data import salt.utils.json from salt.exceptions import SaltInvocationError -from salt.ext import six log = logging.getLogger(__name__) @@ -172,15 +167,15 @@ def present( name=name_tag, return_objs=True, in_states=in_states, profile=profile ) if len(r) < 1: - ret["comment"] = "Error: instance with Name tag {0} not found".format( + ret["comment"] = "Error: instance with Name tag {} not found".format( name_tag ) ret["result"] = False return ret if len(r) > 1: - ret[ - "comment" - ] = "Error: Name tag {0} matched more than one instance".format(name_tag) + ret["comment"] = "Error: Name tag {} matched more than one instance".format( + name_tag + ) ret["result"] = False return ret instance = r[0] @@ -193,7 +188,7 @@ def present( if public_ip is None: ret[ "comment" - ] = "Error: No Public IP assigned to instance with Name {0}".format( + ] = "Error: No Public IP assigned to instance with Name {}".format( name_tag ) ret["result"] = False @@ -216,13 +211,13 @@ def present( identifier, ) except SaltInvocationError as err: - ret["comment"] = "Error: {0}".format(err) + ret["comment"] = "Error: {}".format(err) ret["result"] = False return ret if isinstance(record, dict) and not record: if __opts__["test"]: - ret["comment"] = "Route53 record {0} set to be added.".format(name) + ret["comment"] = "Route53 record {} set to be added.".format(name) ret["result"] = None return ret added = __salt__["boto_route53.add_record"]( @@ -249,10 +244,10 @@ def present( "ttl": ttl, "identifier": identifier, } - ret["comment"] = "Added {0} Route53 record.".format(name) + ret["comment"] = "Added {} Route53 record.".format(name) else: ret["result"] = False - ret["comment"] = "Failed to add {0} Route53 record.".format(name) + ret["comment"] = "Failed to add {} Route53 record.".format(name) return ret elif record: need_to_update = False @@ -269,11 +264,11 @@ def present( need_to_update = True if identifier and identifier != record["identifier"]: need_to_update = True - if ttl and six.text_type(ttl) != six.text_type(record["ttl"]): + if ttl and str(ttl) != str(record["ttl"]): need_to_update = True if need_to_update: if __opts__["test"]: - ret["comment"] = "Route53 record {0} set to be updated.".format(name) + ret["comment"] = "Route53 record {} set to be updated.".format(name) ret["result"] = None return ret updated = __salt__["boto_route53.update_record"]( @@ -300,12 +295,12 @@ def present( "ttl": ttl, "identifier": identifier, } - ret["comment"] = "Updated {0} Route53 record.".format(name) + ret["comment"] = "Updated {} Route53 record.".format(name) else: ret["result"] = False - ret["comment"] = "Failed to update {0} Route53 record.".format(name) + ret["comment"] = "Failed to update {} Route53 record.".format(name) else: - ret["comment"] = "{0} exists.".format(name) + ret["comment"] = "{} exists.".format(name) return ret @@ -381,7 +376,7 @@ def absent( ) if record: if __opts__["test"]: - ret["comment"] = "Route53 record {0} set to be deleted.".format(name) + ret["comment"] = "Route53 record {} set to be deleted.".format(name) ret["result"] = None return ret deleted = __salt__["boto_route53.delete_record"]( @@ -401,12 +396,12 @@ def absent( if deleted: ret["changes"]["old"] = record ret["changes"]["new"] = None - ret["comment"] = "Deleted {0} Route53 record.".format(name) + ret["comment"] = "Deleted {} Route53 record.".format(name) else: ret["result"] = False - ret["comment"] = "Failed to delete {0} Route53 record.".format(name) + ret["comment"] = "Failed to delete {} Route53 record.".format(name) else: - ret["comment"] = "{0} does not exist.".format(name) + ret["comment"] = "{} does not exist.".format(name) return ret @@ -538,7 +533,7 @@ def hosted_zone_present( else: create = True if not create: - ret["comment"] = "Hostd Zone {0} already in desired state".format( + ret["comment"] = "Hostd Zone {} already in desired state".format( domain_name ) else: @@ -557,9 +552,9 @@ def hosted_zone_present( if create: if caller_ref is None: - caller_ref = six.text_type(uuid.uuid4()) + caller_ref = str(uuid.uuid4()) if __opts__["test"]: - ret["comment"] = "Route53 Hosted Zone {0} set to be added.".format( + ret["comment"] = "Route53 Hosted Zone {} set to be added.".format( domain_name ) ret["result"] = None @@ -577,13 +572,13 @@ def hosted_zone_present( profile=profile, ) if res: - msg = "Hosted Zone {0} successfully created".format(domain_name) + msg = "Hosted Zone {} successfully created".format(domain_name) log.info(msg) ret["comment"] = msg ret["changes"]["old"] = None ret["changes"]["new"] = res else: - ret["comment"] = "Creating Hosted Zone {0} failed".format(domain_name) + ret["comment"] = "Creating Hosted Zone {} failed".format(domain_name) ret["result"] = False return ret @@ -611,13 +606,11 @@ def hosted_zone_absent( domain_name=domain_name, region=region, key=key, keyid=keyid, profile=profile ) if not deets: - ret["comment"] = "Hosted Zone {0} already absent".format(domain_name) + ret["comment"] = "Hosted Zone {} already absent".format(domain_name) log.info(ret["comment"]) return ret if __opts__["test"]: - ret["comment"] = "Route53 Hosted Zone {0} set to be deleted.".format( - domain_name - ) + ret["comment"] = "Route53 Hosted Zone {} set to be deleted.".format(domain_name) ret["result"] = None return ret # Not entirely comfortable with this - no safety checks around pub/priv, VPCs @@ -626,7 +619,7 @@ def hosted_zone_absent( if __salt__["boto_route53.delete_zone"]( zone=domain_name, region=region, key=key, keyid=keyid, profile=profile ): - ret["comment"] = "Route53 Hosted Zone {0} deleted".format(domain_name) + ret["comment"] = "Route53 Hosted Zone {} deleted".format(domain_name) log.info(ret["comment"]) ret["changes"]["old"] = deets ret["changes"]["new"] = None diff --git a/salt/states/boto_s3.py b/salt/states/boto_s3.py index bb9b0bf3212..40a953c2764 100644 --- a/salt/states/boto_s3.py +++ b/salt/states/boto_s3.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage S3 Resources =================== @@ -49,15 +48,11 @@ config: :depends: boto3 """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals import copy import difflib import logging -# Import Salt libs -import salt.ext.six as six import salt.utils.hashutils log = logging.getLogger(__name__) @@ -179,10 +174,10 @@ def object_present( __utils__["dictupdate.update"](combined_extra_args, extra_args) if combined_extra_args: supported_args = STORED_EXTRA_ARGS | UPLOAD_ONLY_EXTRA_ARGS - combined_extra_args_keys = frozenset(six.iterkeys(combined_extra_args)) + combined_extra_args_keys = frozenset(combined_extra_args.keys()) extra_keys = combined_extra_args_keys - supported_args if extra_keys: - msg = "extra_args keys {0} are not supported".format(extra_keys) + msg = "extra_args keys {} are not supported".format(extra_keys) return {"error": msg} # Get the hash of the local file @@ -190,14 +185,14 @@ def object_present( hash_type = __opts__["hash_type"] try: digest = salt.utils.hashutils.get_hash(source, form=hash_type) - except IOError as e: + except OSError as e: ret["result"] = False - ret["comment"] = "Could not read local file {0}: {1}".format(source, e,) + ret["comment"] = "Could not read local file {}: {}".format(source, e,) return ret except ValueError as e: # Invalid hash type exception from get_hash ret["result"] = False - ret["comment"] = "Could not hash local file {0}: {1}".format(source, e,) + ret["comment"] = "Could not hash local file {}: {}".format(source, e,) return ret HASH_METADATA_KEY = "salt_managed_content_hash" @@ -207,25 +202,21 @@ def object_present( if combined_extra_args["Metadata"][HASH_METADATA_KEY] != digest: ret["result"] = False ret["comment"] = ( - "Salt uses the {0} metadata key internally," + "Salt uses the {} metadata key internally," "do not pass it to the boto_s3.object_present state." ).format(HASH_METADATA_KEY) return ret combined_extra_args["Metadata"][HASH_METADATA_KEY] = digest # Remove upload-only keys from full set of extra_args # to create desired dict for comparisons - desired_metadata = dict( - (k, v) - for k, v in six.iteritems(combined_extra_args) - if k not in UPLOAD_ONLY_EXTRA_ARGS - ) + desired_metadata = { + k: v for k, v in combined_extra_args.items() if k not in UPLOAD_ONLY_EXTRA_ARGS + } # Some args (SSE-C, RequestPayer) must also be passed to get_metadata - metadata_extra_args = dict( - (k, v) - for k, v in six.iteritems(combined_extra_args) - if k in GET_METADATA_EXTRA_ARGS - ) + metadata_extra_args = { + k: v for k, v in combined_extra_args.items() if k in GET_METADATA_EXTRA_ARGS + } r = __salt__["boto_s3.get_object_metadata"]( name, extra_args=metadata_extra_args, @@ -236,7 +227,7 @@ def object_present( ) if "error" in r: ret["result"] = False - ret["comment"] = "Failed to check if S3 object exists: {0}.".format(r["error"],) + ret["comment"] = "Failed to check if S3 object exists: {}.".format(r["error"],) return ret if r["result"]: @@ -245,14 +236,14 @@ def object_present( # so we can combine both checks into one # Only check metadata keys specified by the user, # ignore other fields that have been set - s3_metadata = dict( - (k, r["result"][k]) + s3_metadata = { + k: r["result"][k] for k in STORED_EXTRA_ARGS if k in desired_metadata and k in r["result"] - ) + } if s3_metadata == desired_metadata: ret["result"] = True - ret["comment"] = "S3 object {0} is present.".format(name) + ret["comment"] = "S3 object {} is present.".format(name) return ret action = "update" else: @@ -276,8 +267,8 @@ def object_present( if __opts__["test"]: ret["result"] = None - ret["comment"] = "S3 object {0} set to be {1}d.".format(name, action) - ret["comment"] += "\nChanges:\n{0}".format(changes_diff) + ret["comment"] = "S3 object {} set to be {}d.".format(name, action) + ret["comment"] += "\nChanges:\n{}".format(changes_diff) ret["changes"] = {"diff": changes_diff} return ret @@ -293,11 +284,11 @@ def object_present( if "error" in r: ret["result"] = False - ret["comment"] = "Failed to {0} S3 object: {1}.".format(action, r["error"],) + ret["comment"] = "Failed to {} S3 object: {}.".format(action, r["error"],) return ret ret["result"] = True - ret["comment"] = "S3 object {0} {1}d.".format(name, action) - ret["comment"] += "\nChanges:\n{0}".format(changes_diff) + ret["comment"] = "S3 object {} {}d.".format(name, action) + ret["comment"] += "\nChanges:\n{}".format(changes_diff) ret["changes"] = {"diff": changes_diff} return ret diff --git a/salt/states/boto_s3_bucket.py b/salt/states/boto_s3_bucket.py index 0e3b6038f0c..121fbe17aa6 100644 --- a/salt/states/boto_s3_bucket.py +++ b/salt/states/boto_s3_bucket.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage S3 Buckets ================= @@ -138,18 +137,12 @@ config: """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import copy import logging -# Import Salt libs import salt.utils.json -# Import 3rd-party libs -from salt.ext import six - log = logging.getLogger(__name__) @@ -304,7 +297,7 @@ def _get_role_arn(name, region=None, key=None, keyid=None, profile=None): region = profile["region"] if region is None: region = "us-east-1" - return "arn:aws:iam::{0}:role/{1}".format(account_id, name) + return "arn:aws:iam::{}:role/{}".format(account_id, name) def _compare_json(current, desired, region, key, keyid, profile): @@ -430,7 +423,7 @@ def present( if RequestPayment is None: RequestPayment = {"Payer": "BucketOwner"} if Policy: - if isinstance(Policy, six.string_types): + if isinstance(Policy, str): Policy = salt.utils.json.loads(Policy) Policy = __utils__["boto3.ordered"](Policy) @@ -440,12 +433,12 @@ def present( if "error" in r: ret["result"] = False - ret["comment"] = "Failed to create bucket: {0}.".format(r["error"]["message"]) + ret["comment"] = "Failed to create bucket: {}.".format(r["error"]["message"]) return ret if not r.get("exists"): if __opts__["test"]: - ret["comment"] = "S3 bucket {0} is set to be created.".format(Bucket) + ret["comment"] = "S3 bucket {} is set to be created.".format(Bucket) ret["result"] = None return ret r = __salt__["boto_s3_bucket.create"]( @@ -458,7 +451,7 @@ def present( ) if not r.get("created"): ret["result"] = False - ret["comment"] = "Failed to create bucket: {0}.".format( + ret["comment"] = "Failed to create bucket: {}.".format( r["error"]["message"] ) return ret @@ -486,7 +479,7 @@ def present( ("put_website", Website, Website), ): if testval is not None: - r = __salt__["boto_s3_bucket.{0}".format(setter)]( + r = __salt__["boto_s3_bucket.{}".format(setter)]( Bucket=Bucket, region=region, key=key, @@ -496,7 +489,7 @@ def present( ) if not r.get("updated"): ret["result"] = False - ret["comment"] = "Failed to create bucket: {0}.".format( + ret["comment"] = "Failed to create bucket: {}.".format( r["error"]["message"] ) return ret @@ -506,13 +499,13 @@ def present( ) ret["changes"]["old"] = {"bucket": None} ret["changes"]["new"] = _describe - ret["comment"] = "S3 bucket {0} created.".format(Bucket) + ret["comment"] = "S3 bucket {} created.".format(Bucket) return ret # bucket exists, ensure config matches ret["comment"] = " ".join( - [ret["comment"], "S3 bucket {0} is present.".format(Bucket)] + [ret["comment"], "S3 bucket {} is present.".format(Bucket)] ) ret["changes"] = {} _describe = __salt__["boto_s3_bucket.describe"]( @@ -520,7 +513,7 @@ def present( ) if "error" in _describe: ret["result"] = False - ret["comment"] = "Failed to update bucket: {0}.".format( + ret["comment"] = "Failed to update bucket: {}.".format( _describe["error"]["message"] ) ret["changes"] = {} @@ -635,7 +628,7 @@ def present( temp = current.get("Policy") # Policy description is always returned as a JSON string. # Convert it to JSON now for ease of comparisons later. - if isinstance(temp, six.string_types): + if isinstance(temp, str): current = __utils__["boto3.ordered"]( {"Policy": salt.utils.json.loads(temp)} ) @@ -652,7 +645,7 @@ def present( if not __opts__["test"]: if deleter and desired is None: # Setting can be deleted, so use that to unset it - r = __salt__["boto_s3_bucket.{0}".format(deleter)]( + r = __salt__["boto_s3_bucket.{}".format(deleter)]( Bucket=Bucket, region=region, key=key, @@ -661,13 +654,13 @@ def present( ) if not r.get("deleted"): ret["result"] = False - ret["comment"] = "Failed to update bucket: {0}.".format( + ret["comment"] = "Failed to update bucket: {}.".format( r["error"]["message"] ) ret["changes"] = {} return ret else: - r = __salt__["boto_s3_bucket.{0}".format(setter)]( + r = __salt__["boto_s3_bucket.{}".format(setter)]( Bucket=Bucket, region=region, key=key, @@ -677,13 +670,13 @@ def present( ) if not r.get("updated"): ret["result"] = False - ret["comment"] = "Failed to update bucket: {0}.".format( + ret["comment"] = "Failed to update bucket: {}.".format( r["error"]["message"] ) ret["changes"] = {} return ret if update and __opts__["test"]: - msg = "S3 bucket {0} set to be modified.".format(Bucket) + msg = "S3 bucket {} set to be modified.".format(Bucket) ret["comment"] = msg ret["result"] = None return ret @@ -692,12 +685,12 @@ def present( # the things are correct by the time we fail here. Fail so the user will # notice something mismatches their desired state. if _describe.get("Location", {}).get("LocationConstraint") != LocationConstraint: - msg = "Bucket {0} location does not match desired configuration, but cannot be changed".format( + msg = "Bucket {} location does not match desired configuration, but cannot be changed".format( LocationConstraint ) log.warning(msg) ret["result"] = False - ret["comment"] = "Failed to update bucket: {0}.".format(msg) + ret["comment"] = "Failed to update bucket: {}.".format(msg) return ret return ret @@ -737,15 +730,15 @@ def absent(name, Bucket, Force=False, region=None, key=None, keyid=None, profile ) if "error" in r: ret["result"] = False - ret["comment"] = "Failed to delete bucket: {0}.".format(r["error"]["message"]) + ret["comment"] = "Failed to delete bucket: {}.".format(r["error"]["message"]) return ret if r and not r["exists"]: - ret["comment"] = "S3 bucket {0} does not exist.".format(Bucket) + ret["comment"] = "S3 bucket {} does not exist.".format(Bucket) return ret if __opts__["test"]: - ret["comment"] = "S3 bucket {0} is set to be removed.".format(Bucket) + ret["comment"] = "S3 bucket {} is set to be removed.".format(Bucket) ret["result"] = None return ret r = __salt__["boto_s3_bucket.delete"]( @@ -753,9 +746,9 @@ def absent(name, Bucket, Force=False, region=None, key=None, keyid=None, profile ) if not r["deleted"]: ret["result"] = False - ret["comment"] = "Failed to delete bucket: {0}.".format(r["error"]["message"]) + ret["comment"] = "Failed to delete bucket: {}.".format(r["error"]["message"]) return ret ret["changes"]["old"] = {"bucket": Bucket} ret["changes"]["new"] = {"bucket": None} - ret["comment"] = "S3 bucket {0} deleted.".format(Bucket) + ret["comment"] = "S3 bucket {} deleted.".format(Bucket) return ret diff --git a/salt/states/boto_secgroup.py b/salt/states/boto_secgroup.py index 5f61e394ee3..b4037ad11a2 100644 --- a/salt/states/boto_secgroup.py +++ b/salt/states/boto_secgroup.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage Security Groups ====================== @@ -103,16 +102,12 @@ passed in as a dict, or as a string to pull from pillars or minion config: will be used as the default region. """ -from __future__ import absolute_import, print_function, unicode_literals -# Import Python libs import logging import pprint -# Import salt libs import salt.utils.dictupdate as dictupdate from salt.exceptions import SaltInvocationError -from salt.ext import six log = logging.getLogger(__name__) @@ -288,7 +283,7 @@ def _security_group_present( ) if not exists: if __opts__["test"]: - ret["comment"] = "Security group {0} is set to be created.".format(name) + ret["comment"] = "Security group {} is set to be created.".format(name) ret["result"] = None return ret created = __salt__["boto_secgroup.create"]( @@ -314,12 +309,12 @@ def _security_group_present( vpc_name=vpc_name, ) ret["changes"]["new"] = {"secgroup": sg} - ret["comment"] = "Security group {0} created.".format(name) + ret["comment"] = "Security group {} created.".format(name) else: ret["result"] = False - ret["comment"] = "Failed to create {0} security group.".format(name) + ret["comment"] = "Failed to create {} security group.".format(name) else: - ret["comment"] = "Security group {0} present.".format(name) + ret["comment"] = "Security group {} present.".format(name) return ret @@ -336,17 +331,17 @@ def _split_rules(rules): cidr_ip = rule.get("cidr_ip") group_name = rule.get("source_group_name") group_id = rule.get("source_group_group_id") - if cidr_ip and not isinstance(cidr_ip, six.string_types): + if cidr_ip and not isinstance(cidr_ip, str): for ip in cidr_ip: _rule = rule.copy() _rule["cidr_ip"] = ip split.append(_rule) - elif group_name and not isinstance(group_name, six.string_types): + elif group_name and not isinstance(group_name, str): for name in group_name: _rule = rule.copy() _rule["source_group_name"] = name split.append(_rule) - elif group_id and not isinstance(group_id, six.string_types): + elif group_id and not isinstance(group_id, str): for _id in group_id: _rule = rule.copy() _rule["source_group_group_id"] = _id @@ -375,8 +370,8 @@ def _check_rule(rule, _rule): if ( rule["ip_protocol"] == _rule["ip_protocol"] - and six.text_type(rule["from_port"]) == six.text_type(_rule["from_port"]) - and six.text_type(rule["to_port"]) == six.text_type(_rule["to_port"]) + and str(rule["from_port"]) == str(_rule["from_port"]) + and str(rule["to_port"]) == str(_rule["to_port"]) ): _cidr_ip = _rule.get("cidr_ip") if _cidr_ip and _cidr_ip == rule.get("cidr_ip"): @@ -405,7 +400,7 @@ def _get_rule_changes(rules, _rules): # 2. determine if rule exists in existing security group rules for rule in rules: try: - ip_protocol = six.text_type(rule.get("ip_protocol")) + ip_protocol = str(rule.get("ip_protocol")) except KeyError: raise SaltInvocationError( "ip_protocol, to_port, and from_port are" @@ -427,10 +422,10 @@ def _get_rule_changes(rules, _rules): -1, ] if ip_protocol not in supported_protocols and ( - not "{0}".format(ip_protocol).isdigit() or int(ip_protocol) > 255 + not "{}".format(ip_protocol).isdigit() or int(ip_protocol) > 255 ): raise SaltInvocationError( - "Invalid ip_protocol {0} specified in security group rule.".format( + "Invalid ip_protocol {} specified in security group rule.".format( ip_protocol ) ) @@ -516,7 +511,7 @@ def _rules_present( if not sg: ret[ "comment" - ] = "{0} security group configuration could not be retrieved.".format(name) + ] = "{} security group configuration could not be retrieved.".format(name) ret["result"] = False return ret rules = _split_rules(rules) @@ -541,7 +536,7 @@ def _rules_present( ) if not _group_id: raise SaltInvocationError( - "source_group_name {0} does not map to a valid " + "source_group_name {} does not map to a valid " "source group id.".format(_source_group_name) ) rule["source_group_name"] = None @@ -554,9 +549,9 @@ def _rules_present( to_delete = to_delete if delete_ingress_rules else [] if to_create or to_delete: if __opts__["test"]: - msg = """Security group {0} set to have rules modified. - To be created: {1} - To be deleted: {2}""".format( + msg = """Security group {} set to have rules modified. + To be created: {} + To be deleted: {}""".format( name, pprint.pformat(to_create), pprint.pformat(to_delete) ) ret["comment"] = msg @@ -578,9 +573,9 @@ def _rules_present( if not _deleted: deleted = False if deleted: - ret["comment"] = "Removed rules on {0} security group.".format(name) + ret["comment"] = "Removed rules on {} security group.".format(name) else: - ret["comment"] = "Failed to remove rules on {0} security group.".format( + ret["comment"] = "Failed to remove rules on {} security group.".format( name ) ret["result"] = False @@ -603,14 +598,14 @@ def _rules_present( ret["comment"] = " ".join( [ ret["comment"], - "Created rules on {0} security group.".format(name), + "Created rules on {} security group.".format(name), ] ) else: ret["comment"] = " ".join( [ ret["comment"], - "Failed to create rules on {0} security group.".format(name), + "Failed to create rules on {} security group.".format(name), ] ) ret["result"] = False @@ -661,7 +656,7 @@ def _rules_egress_present( if not sg: ret[ "comment" - ] = "{0} security group configuration could not be retrieved.".format(name) + ] = "{} security group configuration could not be retrieved.".format(name) ret["result"] = False return ret rules_egress = _split_rules(rules_egress) @@ -686,7 +681,7 @@ def _rules_egress_present( ) if not _group_id: raise SaltInvocationError( - "source_group_name {0} does not map to a valid " + "source_group_name {} does not map to a valid " "source group id.".format(_source_group_name) ) rule["source_group_name"] = None @@ -699,9 +694,9 @@ def _rules_egress_present( to_delete = to_delete if delete_egress_rules else [] if to_create or to_delete: if __opts__["test"]: - msg = """Security group {0} set to have rules modified. - To be created: {1} - To be deleted: {2}""".format( + msg = """Security group {} set to have rules modified. + To be created: {} + To be deleted: {}""".format( name, pprint.pformat(to_create), pprint.pformat(to_delete) ) ret["comment"] = msg @@ -727,14 +722,14 @@ def _rules_egress_present( ret["comment"] = " ".join( [ ret["comment"], - "Removed egress rule on {0} security group.".format(name), + "Removed egress rule on {} security group.".format(name), ] ) else: ret["comment"] = " ".join( [ ret["comment"], - "Failed to remove egress rule on {0} security group.".format( + "Failed to remove egress rule on {} security group.".format( name ), ] @@ -760,14 +755,14 @@ def _rules_egress_present( ret["comment"] = " ".join( [ ret["comment"], - "Created egress rules on {0} security group.".format(name), + "Created egress rules on {} security group.".format(name), ] ) else: ret["comment"] = " ".join( [ ret["comment"], - "Failed to create egress rules on {0} security group.".format( + "Failed to create egress rules on {} security group.".format( name ), ] @@ -836,7 +831,7 @@ def absent( if sg: if __opts__["test"]: - ret["comment"] = "Security group {0} is set to be removed.".format(name) + ret["comment"] = "Security group {} is set to be removed.".format(name) ret["result"] = None return ret deleted = __salt__["boto_secgroup.delete"]( @@ -852,12 +847,12 @@ def absent( if deleted: ret["changes"]["old"] = {"secgroup": sg} ret["changes"]["new"] = {"secgroup": None} - ret["comment"] = "Security group {0} deleted.".format(name) + ret["comment"] = "Security group {} deleted.".format(name) else: ret["result"] = False - ret["comment"] = "Failed to delete {0} security group.".format(name) + ret["comment"] = "Failed to delete {} security group.".format(name) else: - ret["comment"] = "{0} security group does not exist.".format(name) + ret["comment"] = "{} security group does not exist.".format(name) return ret @@ -889,7 +884,7 @@ def _tags_present( if not sg: ret[ "comment" - ] = "{0} security group configuration could not be retrieved.".format(name) + ] = "{} security group configuration could not be retrieved.".format(name) ret["result"] = False return ret tags_to_add = tags @@ -906,7 +901,7 @@ def _tags_present( tags_to_add.pop(existing_tag) if tags_to_remove: if __opts__["test"]: - msg = "The following tag{0} set to be removed: {1}.".format( + msg = "The following tag{} set to be removed: {}.".format( ("s are" if len(tags_to_remove) > 1 else " is"), ", ".join(tags_to_remove), ) @@ -929,7 +924,7 @@ def _tags_present( ret["comment"] = " ".join( [ ret["comment"], - "Error attempting to delete tags {0}.".format( + "Error attempting to delete tags {}.".format( tags_to_remove ), ] @@ -944,14 +939,14 @@ def _tags_present( if tags_to_add or tags_to_update: if __opts__["test"]: if tags_to_add: - msg = "The following tag{0} set to be added: {1}.".format( + msg = "The following tag{} set to be added: {}.".format( ("s are" if len(tags_to_add.keys()) > 1 else " is"), ", ".join(tags_to_add.keys()), ) ret["comment"] = " ".join([ret["comment"], msg]) ret["result"] = None if tags_to_update: - msg = "The following tag {0} set to be updated: {1}.".format( + msg = "The following tag {} set to be updated: {}.".format( ( "values are" if len(tags_to_update.keys()) > 1 diff --git a/salt/states/boto_sns.py b/salt/states/boto_sns.py index 79c16cc399c..6f695180ade 100644 --- a/salt/states/boto_sns.py +++ b/salt/states/boto_sns.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage SNS Topics @@ -54,7 +53,6 @@ passed in as a dict, or as a string to pull from pillars or minion config: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs """ -from __future__ import absolute_import, print_function, unicode_literals # Standard Libs import re @@ -108,10 +106,10 @@ def present(name, subscriptions=None, region=None, key=None, keyid=None, profile ) if is_present: ret["result"] = True - ret["comment"] = "AWS SNS topic {0} present.".format(name) + ret["comment"] = "AWS SNS topic {} present.".format(name) else: if __opts__["test"]: - msg = "AWS SNS topic {0} is set to be created.".format(name) + msg = "AWS SNS topic {} is set to be created.".format(name) ret["comment"] = msg ret["result"] = None return ret @@ -120,13 +118,13 @@ def present(name, subscriptions=None, region=None, key=None, keyid=None, profile name, region=region, key=key, keyid=keyid, profile=profile ) if created: - msg = "AWS SNS topic {0} created.".format(name) + msg = "AWS SNS topic {} created.".format(name) ret["comment"] = msg ret["changes"]["old"] = None ret["changes"]["new"] = {"topic": name, "subscriptions": []} ret["result"] = True else: - ret["comment"] = "Failed to create {0} AWS SNS topic".format(name) + ret["comment"] = "Failed to create {} AWS SNS topic".format(name) ret["result"] = False return ret @@ -163,7 +161,7 @@ def present(name, subscriptions=None, region=None, key=None, keyid=None, profile subscription["endpoint"] = _endpoint if __opts__["test"]: - msg = " AWS SNS subscription {0}:{1} to be set on topic {2}.".format( + msg = " AWS SNS subscription {}:{} to be set on topic {}.".format( subscription["protocol"], subscription["endpoint"], name ) ret["comment"] += msg @@ -180,7 +178,7 @@ def present(name, subscriptions=None, region=None, key=None, keyid=None, profile profile=profile, ) if created: - msg = " AWS SNS subscription {0}:{1} set on topic {2}.".format( + msg = " AWS SNS subscription {}:{} set on topic {}.".format( subscription["protocol"], subscription["endpoint"], name ) ret["comment"] += msg @@ -193,7 +191,7 @@ def present(name, subscriptions=None, region=None, key=None, keyid=None, profile ret["result"] = False return ret else: - msg = " AWS SNS subscription {0}:{1} already set on topic {2}.".format( + msg = " AWS SNS subscription {}:{} already set on topic {}.".format( subscription["protocol"], subscription["endpoint"], name ) ret["comment"] += msg @@ -244,8 +242,8 @@ def absent(name, region=None, key=None, keyid=None, profile=None, unsubscribe=Fa if __opts__.get("test"): ret["comment"] = ( - "AWS SNS topic {0} is set to be removed. " - "{1} subscription(s) will be removed.".format(name, len(subscriptions)) + "AWS SNS topic {} is set to be removed. " + "{} subscription(s) will be removed.".format(name, len(subscriptions)) ) ret["result"] = None return ret @@ -266,7 +264,7 @@ def absent(name, region=None, key=None, keyid=None, profile=None, unsubscribe=Fa name, region=region, key=key, keyid=keyid, profile=profile ) if deleted: - ret["comment"] = "AWS SNS topic {0} deleted.".format(name) + ret["comment"] = "AWS SNS topic {} deleted.".format(name) ret["changes"]["new"] = None if unsubscribe is False: ret["changes"]["old"] = {"topic": name} @@ -278,8 +276,8 @@ def absent(name, region=None, key=None, keyid=None, profile=None, unsubscribe=Fa } else: ret["result"] = False - ret["comment"] = "Failed to delete {0} AWS SNS topic.".format(name) + ret["comment"] = "Failed to delete {} AWS SNS topic.".format(name) else: - ret["comment"] = "AWS SNS topic {0} does not exist.".format(name) + ret["comment"] = "AWS SNS topic {} does not exist.".format(name) return ret diff --git a/salt/states/boto_sqs.py b/salt/states/boto_sqs.py index b198a5f4f80..8db68fb417b 100644 --- a/salt/states/boto_sqs.py +++ b/salt/states/boto_sqs.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage SQS Queues @@ -57,18 +56,12 @@ passed in as a dict, or as a string to pull from pillars or minion config: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs """ -from __future__ import absolute_import, print_function, unicode_literals -# Import Python libs import difflib import logging -# Import Salt libs import salt.utils.json -# Import 3rd-party libs -from salt.ext import six - log = logging.getLogger(__name__) @@ -122,11 +115,11 @@ def present( return ret if r["result"]: - ret["comment"].append("SQS queue {0} present.".format(name)) + ret["comment"].append("SQS queue {} present.".format(name)) else: if __opts__["test"]: ret["result"] = None - ret["comment"].append("SQS queue {0} is set to be created.".format(name),) + ret["comment"].append("SQS queue {} is set to be created.".format(name),) ret["changes"] = {"old": None, "new": name} return ret @@ -141,11 +134,11 @@ def present( if "error" in r: ret["result"] = False ret["comment"].append( - "Failed to create SQS queue {0}: {1}".format(name, r["error"]), + "Failed to create SQS queue {}: {}".format(name, r["error"]), ) return ret - ret["comment"].append("SQS queue {0} created.".format(name)) + ret["comment"].append("SQS queue {} created.".format(name)) ret["changes"]["old"] = None ret["changes"]["new"] = name # Return immediately, as the create call also set all attributes @@ -159,23 +152,23 @@ def present( ) if "error" in r: ret["result"] = False - ret["comment"].append("Failed to get queue attributes: {0}".format(r["error"]),) + ret["comment"].append("Failed to get queue attributes: {}".format(r["error"]),) return ret current_attributes = r["result"] attrs_to_set = {} - for attr, val in six.iteritems(attributes): + for attr, val in attributes.items(): _val = current_attributes.get(attr, None) if attr == "Policy": # Normalize by brute force - if isinstance(_val, six.string_types): + if isinstance(_val, str): _val = salt.utils.json.loads(_val) - if isinstance(val, six.string_types): + if isinstance(val, str): val = salt.utils.json.loads(val) if _val != val: log.debug("Policies differ:\n%s\n%s", _val, val) attrs_to_set[attr] = salt.utils.json.dumps(val, sort_keys=True) - elif six.text_type(_val) != six.text_type(val): + elif str(_val) != str(val): log.debug("Attributes differ:\n%s\n%s", _val, val) attrs_to_set[attr] = val attr_names = ", ".join(attrs_to_set) @@ -204,7 +197,7 @@ def present( if __opts__["test"]: ret["result"] = None ret["comment"].append( - "Attribute(s) {0} set to be updated:\n{1}".format( + "Attribute(s) {} set to be updated:\n{}".format( attr_names, attributes_diff, ) ) @@ -216,10 +209,10 @@ def present( ) if "error" in r: ret["result"] = False - ret["comment"].append("Failed to set queue attributes: {0}".format(r["error"]),) + ret["comment"].append("Failed to set queue attributes: {}".format(r["error"]),) return ret - ret["comment"].append("Updated SQS queue attribute(s) {0}.".format(attr_names),) + ret["comment"].append("Updated SQS queue attribute(s) {}.".format(attr_names),) ret["changes"]["attributes"] = {"diff": attributes_diff} return ret @@ -253,16 +246,16 @@ def absent( ) if "error" in r: ret["result"] = False - ret["comment"] = six.text_type(r["error"]) + ret["comment"] = str(r["error"]) return ret if not r["result"]: - ret["comment"] = "SQS queue {0} does not exist in {1}.".format(name, region,) + ret["comment"] = "SQS queue {} does not exist in {}.".format(name, region,) return ret if __opts__["test"]: ret["result"] = None - ret["comment"] = "SQS queue {0} is set to be removed.".format(name) + ret["comment"] = "SQS queue {} is set to be removed.".format(name) ret["changes"] = {"old": name, "new": None} return ret @@ -271,10 +264,10 @@ def absent( ) if "error" in r: ret["result"] = False - ret["comment"] = six.text_type(r["error"]) + ret["comment"] = str(r["error"]) return ret - ret["comment"] = "SQS queue {0} was deleted.".format(name) + ret["comment"] = "SQS queue {} was deleted.".format(name) ret["changes"]["old"] = name ret["changes"]["new"] = None return ret diff --git a/salt/states/cabal.py b/salt/states/cabal.py index a694ff0978a..8c415e32c4f 100644 --- a/salt/states/cabal.py +++ b/salt/states/cabal.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Installation of Cabal Packages ============================== @@ -23,7 +22,6 @@ pkg.installed state for the package which provides cabal """ -from __future__ import absolute_import, print_function, unicode_literals import salt.utils.path from salt.exceptions import CommandExecutionError, CommandNotFoundError @@ -86,7 +84,7 @@ def installed(name, pkgs=None, user=None, install_global=False, env=None): call = __salt__["cabal.update"](user=user, env=env) except (CommandNotFoundError, CommandExecutionError) as err: ret["result"] = False - ret["comment"] = "Could not run cabal update {0}".format(err) + ret["comment"] = "Could not run cabal update {}".format(err) return ret if pkgs is not None: @@ -98,7 +96,7 @@ def installed(name, pkgs=None, user=None, install_global=False, env=None): installed_pkgs = __salt__["cabal.list"](user=user, installed=True, env=env) except (CommandNotFoundError, CommandExecutionError) as err: ret["result"] = False - ret["comment"] = "Error looking up '{0}': {1}".format(name, err) + ret["comment"] = "Error looking up '{}': {}".format(name, err) return ret pkgs_satisfied = [] @@ -125,14 +123,14 @@ def installed(name, pkgs=None, user=None, install_global=False, env=None): if pkgs_to_install: comment_msg.append( - "Packages(s) '{0}' are set to be installed".format( + "Packages(s) '{}' are set to be installed".format( ", ".join(pkgs_to_install) ) ) if pkgs_satisfied: comment_msg.append( - "Packages(s) '{0}' satisfied by {1}".format( + "Packages(s) '{}' satisfied by {}".format( ", ".join(pkg_list), ", ".join(pkgs_satisfied) ) ) @@ -142,7 +140,7 @@ def installed(name, pkgs=None, user=None, install_global=False, env=None): if not pkgs_to_install: ret["result"] = True - ret["comment"] = "Packages(s) '{0}' satisfied by {1}".format( + ret["comment"] = "Packages(s) '{}' satisfied by {}".format( ", ".join(pkg_list), ", ".join(pkgs_satisfied) ) @@ -154,18 +152,18 @@ def installed(name, pkgs=None, user=None, install_global=False, env=None): ) except (CommandNotFoundError, CommandExecutionError) as err: ret["result"] = False - ret["comment"] = "Error installing '{0}': {1}".format(", ".join(pkg_list), err) + ret["comment"] = "Error installing '{}': {}".format(", ".join(pkg_list), err) return ret if call and isinstance(call, dict): ret["result"] = True ret["changes"] = {"old": [], "new": pkgs_to_install} - ret["comment"] = "Packages(s) '{0}' successfully installed".format( + ret["comment"] = "Packages(s) '{}' successfully installed".format( ", ".join(pkgs_to_install) ) else: ret["result"] = False - ret["comment"] = "Could not install packages(s) '{0}'".format( + ret["comment"] = "Could not install packages(s) '{}'".format( ", ".join(pkg_list) ) @@ -183,24 +181,24 @@ def removed(name, user=None, env=None): installed_pkgs = __salt__["cabal.list"](user=user, installed=True, env=env) except (CommandNotFoundError, CommandExecutionError) as err: ret["result"] = False - ret["comment"] = "Error looking up '{0}': {1}".format(name, err) + ret["comment"] = "Error looking up '{}': {}".format(name, err) if name not in installed_pkgs: ret["result"] = True - ret["comment"] = "Package '{0}' is not installed".format(name) + ret["comment"] = "Package '{}' is not installed".format(name) return ret if __opts__["test"]: ret["result"] = None - ret["comment"] = "Package '{0}' is set to be removed".format(name) + ret["comment"] = "Package '{}' is set to be removed".format(name) return ret if __salt__["cabal.uninstall"](pkg=name, user=user, env=env): ret["result"] = True ret["changes"][name] = "Removed" - ret["comment"] = "Package '{0}' was successfully removed".format(name) + ret["comment"] = "Package '{}' was successfully removed".format(name) else: ret["result"] = False - ret["comment"] = "Error removing package '{0}'".format(name) + ret["comment"] = "Error removing package '{}'".format(name) return ret diff --git a/salt/states/ceph.py b/salt/states/ceph.py index a895d50fa0f..328e9f52e78 100644 --- a/salt/states/ceph.py +++ b/salt/states/ceph.py @@ -1,15 +1,11 @@ -# -*- coding: utf-8 -*- """ Manage ceph with salt. .. versionadded:: 2016.11.0 """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals import logging -# Import Salt Libs import salt.utils.json from salt.exceptions import CommandExecutionError, CommandNotFoundError diff --git a/salt/states/chef.py b/salt/states/chef.py index 100db45eb76..b511a95d5b6 100644 --- a/salt/states/chef.py +++ b/salt/states/chef.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Execute Chef client runs ===================================================================== @@ -19,9 +18,7 @@ Run chef-client or chef-solo chef.solo: - environment: dev """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import re diff --git a/salt/states/chronos_job.py b/salt/states/chronos_job.py index 7e6c2eeb375..f068f5bf213 100644 --- a/salt/states/chronos_job.py +++ b/salt/states/chronos_job.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Configure Chronos jobs via a salt proxy. @@ -13,13 +12,11 @@ Configure Chronos jobs via a salt proxy. .. versionadded:: 2015.8.2 """ -from __future__ import absolute_import, print_function, unicode_literals import copy import logging import salt.utils.configcomparer -from salt.ext import six __proxyenabled__ = ["chronos"] log = logging.getLogger(__file__) @@ -79,16 +76,14 @@ def config(name, config): log.debug("_old schedule: %s", _old) if len(_new) == 3 and len(_old) == 3: log.debug( - "_new[0] == _old[0]: %s", - six.text_type(_new[0]) == six.text_type(_old[0]), + "_new[0] == _old[0]: %s", str(_new[0]) == str(_old[0]), ) log.debug( - "_new[2] == _old[2]: %s", - six.text_type(_new[2]) == six.text_type(_old[2]), + "_new[2] == _old[2]: %s", str(_new[2]) == str(_old[2]), ) - if six.text_type(_new[0]) == six.text_type( - _old[0] - ) and six.text_type(_new[2]) == six.text_type(_old[2]): + if str(_new[0]) == str(_old[0]) and str(_new[2]) == str( + _old[2] + ): log.debug("schedules match--no need for changes") ret["changes"] = {} @@ -98,22 +93,22 @@ def config(name, config): # if test report there will be an update if __opts__["test"]: ret["result"] = None - ret["comment"] = "Chronos job {0} is set to be updated".format(name) + ret["comment"] = "Chronos job {} is set to be updated".format(name) return ret update_result = __salt__["chronos.update_job"](name, update_config) if "exception" in update_result: ret["result"] = False - ret["comment"] = "Failed to update job config for {0}: {1}".format( + ret["comment"] = "Failed to update job config for {}: {}".format( name, update_result["exception"], ) return ret else: ret["result"] = True - ret["comment"] = "Updated job config for {0}".format(name) + ret["comment"] = "Updated job config for {}".format(name) return ret ret["result"] = True - ret["comment"] = "Chronos job {0} configured correctly".format(name) + ret["comment"] = "Chronos job {} configured correctly".format(name) return ret @@ -127,18 +122,18 @@ def absent(name): ret = {"name": name, "changes": {}, "result": False, "comment": ""} if not __salt__["chronos.has_job"](name): ret["result"] = True - ret["comment"] = "Job {0} already absent".format(name) + ret["comment"] = "Job {} already absent".format(name) return ret if __opts__["test"]: ret["result"] = None - ret["comment"] = "Job {0} is set to be removed".format(name) + ret["comment"] = "Job {} is set to be removed".format(name) return ret if __salt__["chronos.rm_job"](name): ret["changes"] = {"job": name} ret["result"] = True - ret["comment"] = "Removed job {0}".format(name) + ret["comment"] = "Removed job {}".format(name) return ret else: ret["result"] = False - ret["comment"] = "Failed to remove job {0}".format(name) + ret["comment"] = "Failed to remove job {}".format(name) return ret diff --git a/salt/states/cimc.py b/salt/states/cimc.py index 982522a1c36..09832c99ed4 100644 --- a/salt/states/cimc.py +++ b/salt/states/cimc.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ A state module to manage Cisco UCS chassis devices. @@ -18,8 +17,6 @@ relies on the CIMC proxy module to interface with the device. """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals import logging diff --git a/salt/states/composer.py b/salt/states/composer.py index 96607dead4f..c21ae515098 100644 --- a/salt/states/composer.py +++ b/salt/states/composer.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Installation of Composer Packages ================================= @@ -37,9 +36,7 @@ the location of composer in the state. - php: /usr/local/bin/php - no_dev: true """ -from __future__ import absolute_import, print_function, unicode_literals -# Import salt libs from salt.exceptions import SaltException @@ -140,12 +137,10 @@ def installed( else: install_status = "not " - ret["comment"] = 'The state of "{0}" will be changed.'.format(name) + ret["comment"] = 'The state of "{}" will be changed.'.format(name) ret["changes"] = { - "old": "composer install has {0}been run in {1}".format( - install_status, name - ), - "new": "composer install will be run in {0}".format(name), + "old": "composer install has {}been run in {}".format(install_status, name), + "new": "composer install will be run in {}".format(name), } ret["result"] = None return ret @@ -168,7 +163,7 @@ def installed( ) except (SaltException) as err: ret["result"] = False - ret["comment"] = "Error executing composer in '{0}': {1}".format(name, err) + ret["comment"] = "Error executing composer in '{}': {}".format(name, err) return ret # If composer retcode != 0 then an exception was thrown and we dealt with it. @@ -255,17 +250,17 @@ def update( # Check if composer.lock exists, if so we already ran `composer install` is_installed = __salt__["composer.did_composer_install"](name) if is_installed: - old_status = "composer install has not yet been run in {0}".format(name) + old_status = "composer install has not yet been run in {}".format(name) else: - old_status = "composer install has been run in {0}".format(name) + old_status = "composer install has been run in {}".format(name) # The state of the system does need to be changed. Check if we're running # in ``test=true`` mode. if __opts__["test"] is True: - ret["comment"] = 'The state of "{0}" will be changed.'.format(name) + ret["comment"] = 'The state of "{}" will be changed.'.format(name) ret["changes"] = { "old": old_status, - "new": "composer install/update will be run in {0}".format(name), + "new": "composer install/update will be run in {}".format(name), } ret["result"] = None return ret @@ -288,7 +283,7 @@ def update( ) except (SaltException) as err: ret["result"] = False - ret["comment"] = "Error executing composer in '{0}': {1}".format(name, err) + ret["comment"] = "Error executing composer in '{}': {}".format(name, err) return ret # If composer retcode != 0 then an exception was thrown and we dealt with it. diff --git a/salt/states/cryptdev.py b/salt/states/cryptdev.py index a4961f3082c..2b5740f7f79 100644 --- a/salt/states/cryptdev.py +++ b/salt/states/cryptdev.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Opening of Encrypted Devices ============================ @@ -28,7 +27,6 @@ Ensure that an encrypted device is mapped with the `mapped` function: .. versionadded:: 2018.3.0 """ -from __future__ import absolute_import, print_function, unicode_literals import logging @@ -130,15 +128,15 @@ def mapped( ) if crypttab_result: if crypttab_result == "new": - ret["changes"]["crypttab"] = "Entry added in {0}".format(config) + ret["changes"]["crypttab"] = "Entry added in {}".format(config) if crypttab_result == "change": - ret["changes"]["crypttab"] = "Existing entry in {0} changed".format( + ret["changes"]["crypttab"] = "Existing entry in {} changed".format( config ) else: - ret["changes"]["crypttab"] = "Unable to set entry in {0}".format(config) + ret["changes"]["crypttab"] = "Unable to set entry in {}".format(config) ret["result"] = False return ret @@ -185,10 +183,10 @@ def unmapped(name, config="/etc/crypttab", persist=True, immediate=False): crypttab_result = __salt__["cryptdev.rm_crypttab"](name, config=config) if crypttab_result: if crypttab_result == "change": - ret["changes"]["crypttab"] = "Entry removed from {0}".format(config) + ret["changes"]["crypttab"] = "Entry removed from {}".format(config) else: - ret["changes"]["crypttab"] = "Unable to remove entry in {0}".format(config) + ret["changes"]["crypttab"] = "Unable to remove entry in {}".format(config) ret["result"] = False return ret diff --git a/salt/states/csf.py b/salt/states/csf.py index 7babe88a666..4a66377031c 100644 --- a/salt/states/csf.py +++ b/salt/states/csf.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ CSF Ip tables management ======================== @@ -14,14 +13,9 @@ CSF Ip tables management ip: 1.2.3.4 method: allow """ # pylint: disable=W0105 -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals import logging -# Import Salt Libs -from salt.ext import six - log = logging.getLogger(__name__) @@ -113,8 +107,8 @@ def rule_present( return ret else: if ttl: - method = "temp{0}".format(method) - func = __salt__["csf.{0}".format(method)] + method = "temp{}".format(method) + func = __salt__["csf.{}".format(method)] rule = func( ip, port=port, @@ -250,7 +244,7 @@ def ports_open(name, ports, proto="tcp", direction="in"): traffic, or both. """ - ports = list(six.moves.map(six.text_type, ports)) + ports = list(map(str, ports)) diff = False ret = { "name": ",".join(ports), @@ -393,7 +387,7 @@ def option_present(name, value, reload=False): if current_option: l = __salt__["csf.split_option"](current_option) option_value = l[1] - if '"{0}"'.format(value) == option_value: + if '"{}"'.format(value) == option_value: return ret else: result = __salt__["csf.set_option"](option, value) @@ -401,7 +395,7 @@ def option_present(name, value, reload=False): ret["changes"]["Option"] = "Changed" else: result = __salt__["file.append"]( - "/etc/csf/csf.conf", args='{0} = "{1}"'.format(option, value) + "/etc/csf/csf.conf", args='{} = "{}"'.format(option, value) ) ret["comment"] = "Option not present. Appended to csf.conf" ret["changes"]["Option"] = "Changed." diff --git a/salt/states/cyg.py b/salt/states/cyg.py index c660f7d94fa..770ca50e16b 100644 --- a/salt/states/cyg.py +++ b/salt/states/cyg.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Installation of Cygwin packages. @@ -10,7 +9,6 @@ or removed. dos2unix: cyg.installed """ -from __future__ import absolute_import, print_function, unicode_literals import logging @@ -61,7 +59,7 @@ def installed(name, cyg_arch="x86_64", mirrors=None): be one of 'x86' or 'x86_64'" return ret - LOG.debug("Installed State: Initial Mirror list: {0}".format(mirrors)) + LOG.debug("Installed State: Initial Mirror list: {}".format(mirrors)) if not __salt__["cyg.check_valid_package"]( name, cyg_arch=cyg_arch, mirrors=mirrors @@ -79,7 +77,7 @@ def installed(name, cyg_arch="x86_64", mirrors=None): if __opts__["test"]: ret[ "comment" - ] = "The package {0} would\ + ] = "The package {} would\ have been installed".format( name ) @@ -144,7 +142,7 @@ def removed(name, cyg_arch="x86_64", mirrors=None): return ret if __opts__["test"]: - ret["comment"] = "The package {0} would have been removed".format(name) + ret["comment"] = "The package {} would have been removed".format(name) return ret if __salt__["cyg.uninstall"](name, cyg_arch): ret["result"] = True @@ -223,7 +221,7 @@ def updated(name=None, cyg_arch="x86_64", mirrors=None): # http://stackoverflow.com/a/1165552 -class DictDiffer(object): +class DictDiffer: """ Calculate the difference between two dictionaries. @@ -265,14 +263,10 @@ class DictDiffer(object): """ Return a set of the keys with changed values. """ - return set( - o for o in self.intersect if self.past_dict[o] != self.current_dict[o] - ) + return {o for o in self.intersect if self.past_dict[o] != self.current_dict[o]} def unchanged(self): """ Return a set of the keys with unchanged values. """ - return set( - o for o in self.intersect if self.past_dict[o] == self.current_dict[o] - ) + return {o for o in self.intersect if self.past_dict[o] == self.current_dict[o]} diff --git a/salt/states/ddns.py b/salt/states/ddns.py index dfec659ece4..8fd2e9c0508 100644 --- a/salt/states/ddns.py +++ b/salt/states/ddns.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Dynamic DNS updates =================== @@ -25,7 +24,6 @@ Example: - nameserver: 123.234.345.456 - keyfile: /srv/salt/dnspy_tsig_key.txt """ -from __future__ import absolute_import, print_function, unicode_literals def __virtual__(): @@ -66,19 +64,19 @@ def present(name, zone, ttl, data, rdtype="A", **kwargs): if __opts__["test"]: ret["result"] = None - ret["comment"] = '{0} record "{1}" will be updated'.format(rdtype, name) + ret["comment"] = '{} record "{}" will be updated'.format(rdtype, name) return ret status = __salt__["ddns.update"](zone, name, ttl, rdtype, data, **kwargs) if status is None: ret["result"] = True - ret["comment"] = '{0} record "{1}" already present with ttl of {2}'.format( + ret["comment"] = '{} record "{}" already present with ttl of {}'.format( rdtype, name, ttl ) elif status: ret["result"] = True - ret["comment"] = 'Updated {0} record for "{1}"'.format(rdtype, name) + ret["comment"] = 'Updated {} record for "{}"'.format(rdtype, name) ret["changes"] = { "name": name, "zone": zone, @@ -88,7 +86,7 @@ def present(name, zone, ttl, data, rdtype="A", **kwargs): } else: ret["result"] = False - ret["comment"] = 'Failed to create or update {0} record for "{1}"'.format( + ret["comment"] = 'Failed to create or update {} record for "{}"'.format( rdtype, name ) return ret @@ -124,7 +122,7 @@ def absent(name, zone, data=None, rdtype=None, **kwargs): if __opts__["test"]: ret["result"] = None - ret["comment"] = '{0} record "{1}" will be deleted'.format(rdtype, name) + ret["comment"] = '{} record "{}" will be deleted'.format(rdtype, name) return ret status = __salt__["ddns.delete"](zone, name, rdtype, data, **kwargs) diff --git a/salt/states/dellchassis.py b/salt/states/dellchassis.py index b91fc30923d..2ac905c8ad2 100644 --- a/salt/states/dellchassis.py +++ b/salt/states/dellchassis.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage chassis via Salt Proxies. @@ -154,8 +153,6 @@ pillar stated above: """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import logging import os @@ -163,7 +160,6 @@ import os from salt.exceptions import CommandExecutionError # Import Salt lobs -from salt.ext import six # Get logging started log = logging.getLogger(__name__) @@ -246,10 +242,7 @@ def blade_idrac( idrac_dhcp = 1 else: idrac_dhcp = 0 - if ( - six.text_type(module_network["Network"]["DHCP Enabled"]) == "0" - and idrac_dhcp == 1 - ): + if str(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 @@ -425,7 +418,7 @@ def chassis( inventory = __salt__[chassis_cmd]("inventory") if idrac_launch: - idrac_launch = six.text_type(idrac_launch) + idrac_launch = str(idrac_launch) current_name = __salt__[chassis_cmd]("get_chassis_name") if chassis_name != current_name: @@ -499,7 +492,7 @@ def chassis( 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): + for k, v in target_power_states.items(): old = {k: current_power_states[k]} new = {k: v} if ret["changes"].get("Blade Power States") is None: @@ -558,7 +551,7 @@ def chassis( slot_names = True powerchange_all_ok = True - for k, v in six.iteritems(target_power_states): + for k, v in target_power_states.items(): powerchange_ok = __salt__[chassis_cmd]("server_power", v, module=k) if not powerchange_ok: powerchange_all_ok = False @@ -708,9 +701,9 @@ def switch( 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"] = "There was an error setting the switch {}.".format(name) - ret["comment"] = "Dell chassis switch {0} was updated.".format(name) + ret["comment"] = "Dell chassis switch {} was updated.".format(name) return ret @@ -763,7 +756,7 @@ def firmware_update(hosts=None, directory=""): ret["changes"].update( { "host": { - "comment": "Firmware update submitted for {0}".format(host), + "comment": "Firmware update submitted for {}".format(host), "success": True, } } @@ -773,9 +766,9 @@ def firmware_update(hosts=None, directory=""): ret["changes"].update( { "host": { - "comment": "FAILED to update firmware for {0}".format(host), + "comment": "FAILED to update firmware for {}".format(host), "success": False, - "reason": six.text_type(err), + "reason": str(err), } } ) diff --git a/salt/states/docker_container.py b/salt/states/docker_container.py index d7647517575..644a77995c9 100644 --- a/salt/states/docker_container.py +++ b/salt/states/docker_container.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of Docker containers @@ -45,7 +44,6 @@ configuration remains unchanged. :ref:`here ` for more information on how to configure access to docker registries in :ref:`Pillar ` data. """ -from __future__ import absolute_import, print_function, unicode_literals import copy import logging @@ -54,7 +52,6 @@ import salt.utils.args import salt.utils.data import salt.utils.dockermod from salt.exceptions import CommandExecutionError -from salt.ext import six # Enable proper logging log = logging.getLogger(__name__) # pylint: disable=invalid-name @@ -78,7 +75,7 @@ def _format_comments(ret, comments): DRY code for joining comments together and conditionally adding a period at the end, and adding this comment string to the state return dict. """ - if isinstance(comments, six.string_types): + if isinstance(comments, str): ret["comment"] = comments else: ret["comment"] = ". ".join(comments) @@ -127,14 +124,14 @@ def _parse_networks(networks): raise CommandExecutionError( "Invalid network configuration (see documentation)" ) - for net_name, net_conf in six.iteritems(networks): + for net_name, net_conf in networks.items(): if net_conf is None: networks[net_name] = {} else: networks[net_name] = salt.utils.data.repack_dictlist(net_conf) if not networks[net_name]: raise CommandExecutionError( - "Invalid configuration for network '{0}' " + "Invalid configuration for network '{}' " "(see documentation)".format(net_name) ) for key in ("links", "aliases"): @@ -148,12 +145,12 @@ def _parse_networks(networks): # Iterate over the networks again now, looking for # incorrectly-formatted arguments errors = [] - for net_name, net_conf in six.iteritems(networks): + for net_name, net_conf in networks.items(): if net_conf is not None: - for key, val in six.iteritems(net_conf): + for key, val in net_conf.items(): if val is None: errors.append( - "Config option '{0}' for network '{1}' is " + "Config option '{}' for network '{}' is " "missing a value".format(key, net_name) ) if errors: @@ -166,13 +163,13 @@ def _parse_networks(networks): ] except CommandExecutionError as exc: raise CommandExecutionError( - "Failed to get list of existing networks: {0}.".format(exc) + "Failed to get list of existing networks: {}.".format(exc) ) else: missing_networks = [x for x in sorted(networks) if x not in all_networks] if missing_networks: raise CommandExecutionError( - "The following networks are not present: {0}".format( + "The following networks are not present: {}".format( ", ".join(missing_networks) ) ) @@ -194,9 +191,7 @@ def _resolve_image(ret, image, client_timeout): image, client_timeout=client_timeout, ) except Exception as exc: # pylint: disable=broad-except - raise CommandExecutionError( - "Failed to pull {0}: {1}".format(image, exc) - ) + raise CommandExecutionError("Failed to pull {}: {}".format(image, exc)) else: ret["changes"]["image"] = pull_result # Try resolving again now that we've pulled @@ -204,7 +199,7 @@ def _resolve_image(ret, image, client_timeout): if image_id is False: # Shouldn't happen unless the pull failed raise CommandExecutionError( - "Image '{0}' not present despite a docker pull " + "Image '{}' not present despite a docker pull " "raising no errors".format(image) ) return image_id @@ -1674,8 +1669,8 @@ def running( ret["result"] = False ret["comment"] = "The 'image' argument is required" return ret - elif not isinstance(image, six.string_types): - image = six.text_type(image) + elif not isinstance(image, str): + image = str(image) try: # Since we're rewriting the "networks" value below, save the original @@ -1705,7 +1700,7 @@ def running( except KeyError: ret["result"] = False comments.append( - "Unable to detect current image for container '{0}'. " + "Unable to detect current image for container '{}'. " "This might be due to a change in the Docker API.".format(name) ) return _format_comments(ret, comments) @@ -1728,7 +1723,7 @@ def running( elif current_image_id != image_id: ret["changes"]["image"] = {"old": current_image_id, "new": image_id} comments.append( - "Container '{0}' would be {1}".format( + "Container '{}' would be {}".format( name, "created" if not exists else "replaced" ) ) @@ -1750,7 +1745,7 @@ def running( except KeyError as exc: ret["result"] = False comments.append( - "Key '{0}' missing from API response, this may be due to a " + "Key '{}' missing from API response, this may be due to a " "change in the Docker Remote API. Please report this on the " "SaltStack issue tracker if it has not already been reported.".format(exc) ) @@ -1783,9 +1778,9 @@ def running( result = __salt__["docker.rename"](new, orig) except CommandExecutionError as exc: result = False - comments.append("Failed to rename temp container: {0}".format(exc)) + comments.append("Failed to rename temp container: {}".format(exc)) if result: - comments.append("Replaced container '{0}'".format(orig)) + comments.append("Replaced container '{}'".format(orig)) else: comments.append("Failed to replace container '{0}'") return result @@ -1803,7 +1798,7 @@ def running( pre_net_connect = __salt__["docker.inspect_container"]( name if exists else temp_container_name ) - for net_name, net_conf in six.iteritems(networks): + for net_name, net_conf in networks.items(): try: __salt__["docker.connect_container_to_network"]( temp_container_name, net_name, **net_conf @@ -1856,7 +1851,7 @@ def running( "The detected changes may be due to incorrect " "handling of arguments in earlier Salt releases. If " "this warning persists after running the state " - "again{0}, and no changes were made to the SLS file, " + "again{}, and no changes were made to the SLS file, " "then please report this.".format( " without test=True" if __opts__["test"] else "" ) @@ -1867,7 +1862,7 @@ def running( if __opts__["test"]: ret["result"] = None comments.append( - "Container '{0}' would be {1}".format( + "Container '{}' would be {}".format( name, "created" if not exists else "replaced" ) ) @@ -1889,7 +1884,7 @@ def running( if send_signal: if __opts__["test"]: comments.append( - "Signal {0} would be sent to container".format(watch_action) + "Signal {} would be sent to container".format(watch_action) ) else: try: @@ -1897,13 +1892,13 @@ def running( except CommandExecutionError as exc: ret["result"] = False comments.append( - "Failed to signal container: {0}".format(exc) + "Failed to signal container: {}".format(exc) ) return _format_comments(ret, comments) else: ret["changes"]["signal"] = watch_action comments.append( - "Sent signal {0} to container".format(watch_action) + "Sent signal {} to container".format(watch_action) ) elif container_changes: if not comments: @@ -1913,7 +1908,7 @@ def running( name, ) comments.append( - "Container '{0}'{1} updated.".format( + "Container '{}'{} updated.".format( name, " would be" if __opts__["test"] else "" ) ) @@ -1922,9 +1917,7 @@ def running( # existing container and the temp container were detected, # and no signal was sent to the container. comments.append( - "Container '{0}' is already configured as specified".format( - name - ) + "Container '{}' is already configured as specified".format(name) ) if net_changes: @@ -1981,15 +1974,15 @@ def running( if disconnected and connected: comments.append( - "Reconnected to network '{0}' with updated " + "Reconnected to network '{}' with updated " "configuration".format(net_name) ) elif disconnected: comments.append( - "Disconnected from network '{0}'".format(net_name) + "Disconnected from network '{}'".format(net_name) ) elif connected: - comments.append("Connected to network '{0}'".format(net_name)) + comments.append("Connected to network '{}'".format(net_name)) if network_failure: ret["result"] = False @@ -2000,7 +1993,7 @@ def running( if skip_comparison: if not exists: - comments.append("Created container '{0}'".format(name)) + comments.append("Created container '{}'".format(name)) else: if not _replace(name, temp_container): ret["result"] = False @@ -2028,7 +2021,7 @@ def running( except Exception as exc: # pylint: disable=broad-except ret["result"] = False comments.append( - "Failed to start container '{0}': '{1}'".format(name, exc) + "Failed to start container '{}': '{}'".format(name, exc) ) return _format_comments(ret, comments) else: @@ -2054,8 +2047,8 @@ def running( autoip_keys = __salt__["config.option"]( "docker.compare_container_networks" ).get("automatic", []) - for net_name, net_changes in six.iteritems( - ret["changes"].get("container", {}).get("Networks", {}) + for net_name, net_changes in ( + ret["changes"].get("container", {}).get("Networks", {}).items() ): if ( "IPConfiguration" in net_changes @@ -2075,7 +2068,7 @@ def running( ret["changes"]["state"] = {"old": pre_state, "new": post_state} if pre_state is not None: comments.append( - "State changed from '{0}' to '{1}'".format(pre_state, post_state) + "State changed from '{}' to '{}'".format(pre_state, post_state) ) if exists and current_image_id != image_id: @@ -2190,15 +2183,15 @@ def run( for unsupported in ("watch_action", "start", "shutdown_timeout", "follow"): if unsupported in kwargs: ret["result"] = False - ret["comment"] = "The '{0}' argument is not supported".format(unsupported) + ret["comment"] = "The '{}' argument is not supported".format(unsupported) return ret if image is None: ret["result"] = False ret["comment"] = "The 'image' argument is required" return ret - elif not isinstance(image, six.string_types): - image = six.text_type(image) + elif not isinstance(image, str): + image = str(image) try: if "networks" in kwargs and kwargs["networks"] is not None: @@ -2214,7 +2207,7 @@ def run( if __opts__["test"]: ret["result"] = None - ret["comment"] = "Container would be run{0}".format( + ret["comment"] = "Container would be run{}".format( " in the background" if bg else "" ) return ret @@ -2269,7 +2262,7 @@ def run( except Exception as exc: # pylint: disable=broad-except log.exception("Encountered error running container") ret["result"] = False - ret["comment"] = "Encountered error running container: {0}".format(exc) + ret["comment"] = "Encountered error running container: {}".format(exc) else: if bg: ret["comment"] = "Container was run in the background" @@ -2282,7 +2275,7 @@ def run( ret["result"] = False if failhard and retcode != 0 else True ret["comment"] = ( "Container ran and exited with a return code of " - "{0}".format(retcode) + "{}".format(retcode) ) if remove: @@ -2292,7 +2285,7 @@ def run( __salt__["docker.rm"](ret["changes"]["Id"]) except CommandExecutionError as exc: ret.setdefault("warnings", []).append( - "Failed to auto_remove container: {0}".format(exc) + "Failed to auto_remove container: {}".format(exc) ) return ret @@ -2364,12 +2357,12 @@ def stopped( return ret targets = [] for target in containers: - if not isinstance(target, six.string_types): - target = six.text_type(target) + if not isinstance(target, str): + target = str(target) targets.append(target) elif name: - if not isinstance(name, six.string_types): - targets = [six.text_type(name)] + if not isinstance(name, str): + targets = [str(name)] else: targets = [name] @@ -2385,7 +2378,7 @@ def stopped( errors = [] if error_on_absent and "absent" in containers: errors.append( - "The following container(s) are absent: {0}".format( + "The following container(s) are absent: {}".format( ", ".join(containers["absent"]) ) ) @@ -2393,7 +2386,7 @@ def stopped( if not unpause and "paused" in containers: ret["result"] = False errors.append( - "The following container(s) are paused: {0}".format( + "The following container(s) are paused: {}".format( ", ".join(containers["paused"]) ) ) @@ -2408,7 +2401,7 @@ def stopped( if not to_stop: ret["result"] = True if len(targets) == 1: - ret["comment"] = "Container '{0}' is ".format(targets[0]) + ret["comment"] = "Container '{}' is ".format(targets[0]) else: ret["comment"] = "All specified containers are " if "absent" in containers: @@ -2418,7 +2411,7 @@ def stopped( if __opts__["test"]: ret["result"] = None - ret["comment"] = "The following container(s) will be stopped: {0}".format( + ret["comment"] = "The following container(s) will be stopped: {}".format( ", ".join(to_stop) ) return ret @@ -2435,14 +2428,14 @@ def stopped( if "comment" in changes: stop_errors.append(changes["comment"]) else: - stop_errors.append("Failed to stop container '{0}'".format(target)) + stop_errors.append("Failed to stop container '{}'".format(target)) if stop_errors: ret["comment"] = "; ".join(stop_errors) return ret ret["result"] = True - ret["comment"] = "The following container(s) were stopped: {0}".format( + ret["comment"] = "The following container(s) were stopped: {}".format( ", ".join(to_stop) ) return ret @@ -2476,7 +2469,7 @@ def absent(name, force=False): if name not in __salt__["docker.list_containers"](all=True): ret["result"] = True - ret["comment"] = "Container '{0}' does not exist".format(name) + ret["comment"] = "Container '{}' does not exist".format(name) return ret pre_state = __salt__["docker.state"](name) @@ -2488,23 +2481,23 @@ def absent(name, force=False): if __opts__["test"]: ret["result"] = None - ret["comment"] = "Container '{0}' will be removed".format(name) + ret["comment"] = "Container '{}' will be removed".format(name) return ret try: ret["changes"]["removed"] = __salt__["docker.rm"](name, force=force) except Exception as exc: # pylint: disable=broad-except - ret["comment"] = "Failed to remove container '{0}': {1}".format(name, exc) + ret["comment"] = "Failed to remove container '{}': {}".format(name, exc) return ret if name in __salt__["docker.list_containers"](all=True): - ret["comment"] = "Failed to remove container '{0}'".format(name) + ret["comment"] = "Failed to remove container '{}'".format(name) else: if force and pre_state != "stopped": method = "Forcibly" else: method = "Successfully" - ret["comment"] = "{0} removed container '{1}'".format(method, name) + ret["comment"] = "{} removed container '{}'".format(method, name) ret["result"] = True return ret @@ -2538,5 +2531,5 @@ def mod_watch(name, sfun=None, **kwargs): "name": name, "changes": {}, "result": False, - "comment": ("watch requisite is not" " implemented for {0}".format(sfun)), + "comment": ("watch requisite is not" " implemented for {}".format(sfun)), } diff --git a/salt/states/docker_volume.py b/salt/states/docker_volume.py index d45355fe9e3..86497b5dbd5 100644 --- a/salt/states/docker_volume.py +++ b/salt/states/docker_volume.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of Docker volumes @@ -30,11 +29,9 @@ Management of Docker volumes These states were moved from the :mod:`docker ` state module (formerly called **dockerng**) in the 2017.7.0 release. """ -from __future__ import absolute_import, print_function, unicode_literals import logging -# Import salt libs import salt.utils.data # Enable proper logging @@ -138,14 +135,14 @@ def present(name, driver=None, driver_opts=None, force=False): if not volume: if __opts__["test"]: ret["result"] = None - ret["comment"] = "The volume '{0}' will be created".format(name) + ret["comment"] = "The volume '{}' will be created".format(name) return ret try: ret["changes"]["created"] = __salt__["docker.create_volume"]( name, driver=driver, driver_opts=driver_opts ) except Exception as exc: # pylint: disable=broad-except - ret["comment"] = "Failed to create volume '{0}': {1}".format(name, exc) + ret["comment"] = "Failed to create volume '{}': {}".format(name, exc) return ret else: result = True @@ -155,8 +152,8 @@ def present(name, driver=None, driver_opts=None, force=False): if driver is not None and volume["Driver"] != driver: if not force: ret["comment"] = ( - "Driver for existing volume '{0}' ('{1}')" - " does not match specified driver ('{2}')" + "Driver for existing volume '{}' ('{}')" + " does not match specified driver ('{}')" " and force is False".format(name, volume["Driver"], driver) ) ret["result"] = None if __opts__["test"] else False @@ -164,14 +161,14 @@ def present(name, driver=None, driver_opts=None, force=False): if __opts__["test"]: ret["result"] = None ret["comment"] = ( - "The volume '{0}' will be replaced with a" - " new one using the driver '{1}'".format(name, volume) + "The volume '{}' will be replaced with a" + " new one using the driver '{}'".format(name, volume) ) return ret try: ret["changes"]["removed"] = __salt__["docker.remove_volume"](name) except Exception as exc: # pylint: disable=broad-except - ret["comment"] = "Failed to remove volume '{0}': {1}".format(name, exc) + ret["comment"] = "Failed to remove volume '{}': {}".format(name, exc) return ret else: try: @@ -179,7 +176,7 @@ def present(name, driver=None, driver_opts=None, force=False): name, driver=driver, driver_opts=driver_opts ) except Exception as exc: # pylint: disable=broad-except - ret["comment"] = "Failed to create volume '{0}': {1}".format(name, exc) + ret["comment"] = "Failed to create volume '{}': {}".format(name, exc) return ret else: result = True @@ -187,7 +184,7 @@ def present(name, driver=None, driver_opts=None, force=False): return ret ret["result"] = True - ret["comment"] = "Volume '{0}' already exists.".format(name) + ret["comment"] = "Volume '{}' already exists.".format(name) return ret @@ -215,12 +212,12 @@ def absent(name, driver=None): volume = _find_volume(name) if not volume: ret["result"] = True - ret["comment"] = "Volume '{0}' already absent".format(name) + ret["comment"] = "Volume '{}' already absent".format(name) return ret try: ret["changes"]["removed"] = __salt__["docker.remove_volume"](name) ret["result"] = True except Exception as exc: # pylint: disable=broad-except - ret["comment"] = "Failed to remove volume '{0}': {1}".format(name, exc) + ret["comment"] = "Failed to remove volume '{}': {}".format(name, exc) return ret diff --git a/salt/states/drac.py b/salt/states/drac.py index d2394e03dd9..29a3a6fa7a6 100644 --- a/salt/states/drac.py +++ b/salt/states/drac.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of Dell DRAC @@ -36,7 +35,6 @@ Ensure DRAC network is in a consistent state - gateway: 10.225.108.1 """ -from __future__ import absolute_import, print_function, unicode_literals import salt.exceptions import salt.utils.path @@ -70,18 +68,18 @@ def present(name, password, permission): if __opts__["test"]: if name in users: - ret["comment"] = "`{0}` already exists".format(name) + ret["comment"] = "`{}` already exists".format(name) else: - ret["comment"] = "`{0}` will be created".format(name) + ret["comment"] = "`{}` will be created".format(name) ret["changes"] = {name: "will be created"} return ret if name in users: - ret["comment"] = "`{0}` already exists".format(name) + ret["comment"] = "`{}` already exists".format(name) else: if __salt__["drac.create_user"](name, password, permission, users): - ret["comment"] = "`{0}` user created".format(name) + ret["comment"] = "`{}` user created".format(name) ret["changes"] = {name: "new user created"} else: ret["comment"] = "Unable to create user" @@ -103,22 +101,22 @@ def absent(name): if __opts__["test"]: if name in users: - ret["comment"] = "`{0}` is set to be deleted".format(name) + ret["comment"] = "`{}` is set to be deleted".format(name) ret["changes"] = {name: "will be deleted"} else: - ret["comment"] = "`{0}` does not exist".format(name) + ret["comment"] = "`{}` does not exist".format(name) return ret if name in users: if __salt__["drac.delete_user"](name, users[name]["index"]): - ret["comment"] = "`{0}` deleted".format(name) + ret["comment"] = "`{}` deleted".format(name) ret["changes"] = {name: "deleted"} else: ret["comment"] = "Unable to delete user" ret["result"] = False else: - ret["comment"] = "`{0}` does not exist".format(name) + ret["comment"] = "`{}` does not exist".format(name) return ret diff --git a/salt/states/dvs.py b/salt/states/dvs.py index 81eae6fd6eb..d9eae4bef3c 100644 --- a/salt/states/dvs.py +++ b/salt/states/dvs.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage VMware distributed virtual switches (DVSs) and their distributed virtual portgroups (DVportgroups). @@ -201,19 +200,13 @@ The 5.5.0.2014.1.1 is a known stable version that this original ESXi State Module was developed against. """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals import logging import sys import traceback -# Import Salt Libs import salt.exceptions -from salt.ext import six -from salt.ext.six.moves import range -# Import Third Party Libs try: from pyVmomi import VmomiSupport @@ -268,7 +261,7 @@ def _get_datacenter_name(): details = __salt__["esxdatacenter.get_details"]() if not details: raise salt.exceptions.CommandExecutionError( - "details for proxy type '{0}' not loaded".format(proxy_type) + "details for proxy type '{}' not loaded".format(proxy_type) ) return details["datacenter"] @@ -286,8 +279,8 @@ def dvs_configured(name, dvs): datacenter_name = _get_datacenter_name() dvs_name = dvs["name"] if dvs.get("name") else name log.info( - "Running state {0} for DVS '{1}' in datacenter " - "'{2}'".format(name, dvs_name, datacenter_name) + "Running state {} for DVS '{}' in datacenter " + "'{}'".format(name, dvs_name, datacenter_name) ) changes_required = False ret = {"name": name, "changes": {}, "result": None, "comment": None} @@ -303,8 +296,8 @@ def dvs_configured(name, dvs): changes_required = True if __opts__["test"]: comments.append( - "State {0} will create a new DVS " - "'{1}' in datacenter '{2}'" + "State {} will create a new DVS " + "'{}' in datacenter '{}'" "".format(name, dvs_name, datacenter_name) ) log.info(comments[-1]) @@ -314,8 +307,8 @@ def dvs_configured(name, dvs): dvs_dict=dvs, dvs_name=dvs_name, service_instance=si ) comments.append( - "Created a new DVS '{0}' in datacenter " - "'{1}'".format(dvs_name, datacenter_name) + "Created a new DVS '{}' in datacenter " + "'{}'".format(dvs_name, datacenter_name) ) log.info(comments[-1]) changes.update({"dvs": {"new": dvs}}) @@ -332,9 +325,9 @@ def dvs_configured(name, dvs): "network_resource_management_enabled", ] log.trace( - "DVS '{0}' found in datacenter '{1}'. Checking " + "DVS '{}' found in datacenter '{}'. Checking " "for any updates in " - "{2}".format(dvs_name, datacenter_name, props) + "{}".format(dvs_name, datacenter_name, props) ) props_to_original_values = {} props_to_updated_values = {} @@ -387,18 +380,18 @@ def dvs_configured(name, dvs): d = props_to_updated_values[p][idx] s = props_to_original_values[p][idx] changes_string += ( - "\t\t{0} from '{1}' to '{2}'\n" + "\t\t{} from '{}' to '{}'\n" "".format(d["key"], s, d) ) else: - changes_string += "\t{0} from '{1}' to '{2}'\n" "".format( + changes_string += "\t{} from '{}' to '{}'\n" "".format( p, props_to_original_values[p], props_to_updated_values[p], ) comments.append( - "State dvs_configured will update DVS '{0}' " - "in datacenter '{1}':\n{2}" + "State dvs_configured will update DVS '{}' " + "in datacenter '{}':\n{}" "".format(dvs_name, datacenter_name, changes_string) ) log.info(comments[-1]) @@ -409,7 +402,7 @@ def dvs_configured(name, dvs): service_instance=si, ) comments.append( - "Updated DVS '{0}' in datacenter '{1}'" + "Updated DVS '{}' in datacenter '{}'" "".format(dvs_name, datacenter_name) ) log.info(comments[-1]) @@ -423,16 +416,13 @@ def dvs_configured(name, dvs): ) __salt__["vsphere.disconnect"](si) except salt.exceptions.CommandExecutionError as exc: - log.error("Error: {0}\n{1}".format(exc, traceback.format_exc())) + log.error("Error: {}\n{}".format(exc, traceback.format_exc())) if si: __salt__["vsphere.disconnect"](si) if not __opts__["test"]: ret["result"] = False ret.update( - { - "comment": six.text_type(exc), - "result": False if not __opts__["test"] else None, - } + {"comment": str(exc), "result": False if not __opts__["test"] else None} ) return ret if not comments: @@ -440,7 +430,7 @@ def dvs_configured(name, dvs): ret.update( { "comment": ( - "DVS '{0}' in datacenter '{1}' is " + "DVS '{}' in datacenter '{}' is " "correctly configured. Nothing to be done." "".format(dvs_name, datacenter_name) ), @@ -485,7 +475,7 @@ def _get_val2_dict_from_diff_dict(diff_dict): ret_dict = {} for p in diff_dict.keys(): if not isinstance(diff_dict[p], dict): - raise ValueError("Unexpected diff difct '{0}'".format(diff_dict)) + raise ValueError("Unexpected diff difct '{}'".format(diff_dict)) if "val2" in diff_dict[p].keys(): ret_dict.update({p: diff_dict[p]["val2"]}) else: @@ -500,7 +490,7 @@ def _get_val1_dict_from_diff_dict(diff_dict): ret_dict = {} for p in diff_dict.keys(): if not isinstance(diff_dict[p], dict): - raise ValueError("Unexpected diff difct '{0}'".format(diff_dict)) + raise ValueError("Unexpected diff difct '{}'".format(diff_dict)) if "val1" in diff_dict[p].keys(): ret_dict.update({p: diff_dict[p]["val1"]}) else: @@ -517,25 +507,25 @@ def _get_changes_from_diff_dict(diff_dict): changes_strings = [] for p in diff_dict.keys(): if not isinstance(diff_dict[p], dict): - raise ValueError("Unexpected diff difct '{0}'".format(diff_dict)) + raise ValueError("Unexpected diff difct '{}'".format(diff_dict)) if sorted(diff_dict[p].keys()) == ["val1", "val2"]: # Some string formatting from_str = diff_dict[p]["val1"] - if isinstance(diff_dict[p]["val1"], six.string_types): - from_str = "'{0}'".format(diff_dict[p]["val1"]) + if isinstance(diff_dict[p]["val1"], str): + from_str = "'{}'".format(diff_dict[p]["val1"]) elif isinstance(diff_dict[p]["val1"], list): - from_str = "'{0}'".format(", ".join(diff_dict[p]["val1"])) + from_str = "'{}'".format(", ".join(diff_dict[p]["val1"])) to_str = diff_dict[p]["val2"] - if isinstance(diff_dict[p]["val2"], six.string_types): - to_str = "'{0}'".format(diff_dict[p]["val2"]) + if isinstance(diff_dict[p]["val2"], str): + to_str = "'{}'".format(diff_dict[p]["val2"]) elif isinstance(diff_dict[p]["val2"], list): - to_str = "'{0}'".format(", ".join(diff_dict[p]["val2"])) - changes_strings.append("{0} from {1} to {2}".format(p, from_str, to_str)) + to_str = "'{}'".format(", ".join(diff_dict[p]["val2"])) + changes_strings.append("{} from {} to {}".format(p, from_str, to_str)) else: sub_changes = _get_changes_from_diff_dict(diff_dict[p]) if sub_changes: - changes_strings.append("{0}:".format(p)) - changes_strings.extend(["\t{0}".format(c) for c in sub_changes]) + changes_strings.append("{}:".format(p)) + changes_strings.extend(["\t{}".format(c) for c in sub_changes]) return changes_strings @@ -553,8 +543,7 @@ def portgroups_configured(name, dvs, portgroups): """ datacenter = _get_datacenter_name() log.info( - "Running state {0} on DVS '{1}', datacenter " - "'{2}'".format(name, dvs, datacenter) + "Running state {} on DVS '{}', datacenter " "'{}'".format(name, dvs, datacenter) ) changes_required = False ret = {"name": name, "changes": {}, "result": None, "comment": None} @@ -573,15 +562,15 @@ def portgroups_configured(name, dvs, portgroups): pg_name = pg["name"] expected_pg_names.append(pg_name) del pg["name"] - log.info("Checking pg '{0}'".format(pg_name)) + log.info("Checking pg '{}'".format(pg_name)) filtered_current_pgs = [p for p in current_pgs if p.get("name") == pg_name] if not filtered_current_pgs: changes_required = True if __opts__["test"]: comments.append( - "State {0} will create a new portgroup " - "'{1}' in DVS '{2}', datacenter " - "'{3}'".format(name, pg_name, dvs, datacenter) + "State {} will create a new portgroup " + "'{}' in DVS '{}', datacenter " + "'{}'".format(name, pg_name, dvs, datacenter) ) else: __salt__["vsphere.create_dvportgroup"]( @@ -591,8 +580,8 @@ def portgroups_configured(name, dvs, portgroups): service_instance=si, ) comments.append( - "Created a new portgroup '{0}' in DVS " - "'{1}', datacenter '{2}'" + "Created a new portgroup '{}' in DVS " + "'{}', datacenter '{}'" "".format(pg_name, dvs, datacenter) ) log.info(comments[-1]) @@ -600,8 +589,8 @@ def portgroups_configured(name, dvs, portgroups): else: # Porgroup already exists. Checking the config log.trace( - "Portgroup '{0}' found in DVS '{1}', datacenter " - "'{2}'. Checking for any updates." + "Portgroup '{}' found in DVS '{}', datacenter " + "'{}'. Checking for any updates." "".format(pg_name, dvs, datacenter) ) current_pg = filtered_current_pgs[0] @@ -611,16 +600,16 @@ def portgroups_configured(name, dvs, portgroups): changes_required = True if __opts__["test"]: changes_strings = _get_changes_from_diff_dict(diff_dict) - log.trace("changes_strings = " "{0}".format(changes_strings)) + log.trace("changes_strings = " "{}".format(changes_strings)) comments.append( - "State {0} will update portgroup '{1}' in " - "DVS '{2}', datacenter '{3}':\n{4}" + "State {} will update portgroup '{}' in " + "DVS '{}', datacenter '{}':\n{}" "".format( name, pg_name, dvs, datacenter, - "\n".join(["\t{0}".format(c) for c in changes_strings]), + "\n".join(["\t{}".format(c) for c in changes_strings]), ) ) else: @@ -631,8 +620,8 @@ def portgroups_configured(name, dvs, portgroups): service_instance=si, ) comments.append( - "Updated portgroup '{0}' in DVS " - "'{1}', datacenter '{2}'" + "Updated portgroup '{}' in DVS " + "'{}', datacenter '{}'" "".format(pg_name, dvs, datacenter) ) log.info(comments[-1]) @@ -655,9 +644,9 @@ def portgroups_configured(name, dvs, portgroups): changes_required = True if __opts__["test"]: comments.append( - "State {0} will remove " - "the portgroup '{1}' from DVS '{2}', " - "datacenter '{3}'" + "State {} will remove " + "the portgroup '{}' from DVS '{}', " + "datacenter '{}'" "".format(name, current_pg["name"], dvs, datacenter) ) else: @@ -665,15 +654,15 @@ def portgroups_configured(name, dvs, portgroups): portgroup=current_pg["name"], dvs=dvs, service_instance=si ) comments.append( - "Removed the portgroup '{0}' from DVS " - "'{1}', datacenter '{2}'" + "Removed the portgroup '{}' from DVS " + "'{}', datacenter '{}'" "".format(current_pg["name"], dvs, datacenter) ) log.info(comments[-1]) changes.update({current_pg["name"]: {"old": current_pg}}) __salt__["vsphere.disconnect"](si) except salt.exceptions.CommandExecutionError as exc: - log.error("Error: {0}\n{1}".format(exc, traceback.format_exc())) + log.error("Error: {}\n{}".format(exc, traceback.format_exc())) if si: __salt__["vsphere.disconnect"](si) if not __opts__["test"]: @@ -687,8 +676,8 @@ def portgroups_configured(name, dvs, portgroups): ret.update( { "comment": ( - "All portgroups in DVS '{0}', datacenter " - "'{1}' exist and are correctly configured. " + "All portgroups in DVS '{}', datacenter " + "'{}' exist and are correctly configured. " "Nothing to be done.".format(dvs, datacenter) ), "result": True, @@ -718,9 +707,7 @@ def uplink_portgroup_configured(name, dvs, uplink_portgroup): """ datacenter = _get_datacenter_name() - log.info( - "Running {0} on DVS '{1}', datacenter '{2}'" "".format(name, dvs, datacenter) - ) + log.info("Running {} on DVS '{}', datacenter '{}'" "".format(name, dvs, datacenter)) changes_required = False ret = {"name": name, "changes": {}, "result": None, "comment": None} comments = [] @@ -733,22 +720,22 @@ def uplink_portgroup_configured(name, dvs, uplink_portgroup): current_uplink_portgroup = __salt__["vsphere.list_uplink_dvportgroup"]( dvs=dvs, service_instance=si ) - log.trace("current_uplink_portgroup = " "{0}".format(current_uplink_portgroup)) + log.trace("current_uplink_portgroup = " "{}".format(current_uplink_portgroup)) diff_dict = _get_diff_dict(current_uplink_portgroup, uplink_portgroup) if diff_dict: changes_required = True if __opts__["test"]: changes_strings = _get_changes_from_diff_dict(diff_dict) - log.trace("changes_strings = " "{0}".format(changes_strings)) + log.trace("changes_strings = " "{}".format(changes_strings)) comments.append( - "State {0} will update the " - "uplink portgroup in DVS '{1}', datacenter " - "'{2}':\n{3}" + "State {} will update the " + "uplink portgroup in DVS '{}', datacenter " + "'{}':\n{}" "".format( name, dvs, datacenter, - "\n".join(["\t{0}".format(c) for c in changes_strings]), + "\n".join(["\t{}".format(c) for c in changes_strings]), ) ) else: @@ -760,7 +747,7 @@ def uplink_portgroup_configured(name, dvs, uplink_portgroup): ) comments.append( "Updated the uplink portgroup in DVS " - "'{0}', datacenter '{1}'" + "'{}', datacenter '{}'" "".format(dvs, datacenter) ) log.info(comments[-1]) @@ -774,7 +761,7 @@ def uplink_portgroup_configured(name, dvs, uplink_portgroup): ) __salt__["vsphere.disconnect"](si) except salt.exceptions.CommandExecutionError as exc: - log.error("Error: {0}\n{1}".format(exc, traceback.format_exc())) + log.error("Error: {}\n{}".format(exc, traceback.format_exc())) if si: __salt__["vsphere.disconnect"](si) if not __opts__["test"]: @@ -788,8 +775,8 @@ def uplink_portgroup_configured(name, dvs, uplink_portgroup): ret.update( { "comment": ( - "Uplink portgroup in DVS '{0}', datacenter " - "'{1}' is correctly configured. " + "Uplink portgroup in DVS '{}', datacenter " + "'{}' is correctly configured. " "Nothing to be done.".format(dvs, datacenter) ), "result": True, diff --git a/salt/states/elasticsearch.py b/salt/states/elasticsearch.py index 83c498bc6e8..598d4e35029 100644 --- a/salt/states/elasticsearch.py +++ b/salt/states/elasticsearch.py @@ -1,20 +1,14 @@ -# -*- coding: utf-8 -*- """ State module to manage Elasticsearch. .. versionadded:: 2017.7.0 """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import logging import salt.utils.json -# Import salt libs -from salt.ext import six - log = logging.getLogger(__name__) @@ -32,23 +26,23 @@ def index_absent(name): index = __salt__["elasticsearch.index_get"](index=name) if index and name in index: if __opts__["test"]: - ret["comment"] = "Index {0} will be removed".format(name) + ret["comment"] = "Index {} will be removed".format(name) ret["changes"]["old"] = index[name] ret["result"] = None else: ret["result"] = __salt__["elasticsearch.index_delete"](index=name) if ret["result"]: - ret["comment"] = "Successfully removed index {0}".format(name) + ret["comment"] = "Successfully removed index {}".format(name) ret["changes"]["old"] = index[name] else: ret[ "comment" - ] = "Failed to remove index {0} for unknown reasons".format(name) + ] = "Failed to remove index {} for unknown reasons".format(name) else: - ret["comment"] = "Index {0} is already absent".format(name) + ret["comment"] = "Index {} is already absent".format(name) except Exception as err: # pylint: disable=broad-except ret["result"] = False - ret["comment"] = six.text_type(err) + ret["comment"] = str(err) return ret @@ -85,7 +79,7 @@ def index_present(name, definition=None): index_exists = __salt__["elasticsearch.index_exists"](index=name) if not index_exists: if __opts__["test"]: - ret["comment"] = "Index {0} does not exist and will be created".format( + ret["comment"] = "Index {} does not exist and will be created".format( name ) ret["changes"] = {"new": definition} @@ -95,18 +89,18 @@ def index_present(name, definition=None): index=name, body=definition ) if output: - ret["comment"] = "Successfully created index {0}".format(name) + ret["comment"] = "Successfully created index {}".format(name) ret["changes"] = { "new": __salt__["elasticsearch.index_get"](index=name)[name] } else: ret["result"] = False - ret["comment"] = "Cannot create index {0}, {1}".format(name, output) + ret["comment"] = "Cannot create index {}, {}".format(name, output) else: - ret["comment"] = "Index {0} is already present".format(name) + ret["comment"] = "Index {} is already present".format(name) except Exception as err: # pylint: disable=broad-except ret["result"] = False - ret["comment"] = six.text_type(err) + ret["comment"] = str(err) return ret @@ -130,7 +124,7 @@ def alias_absent(name, index): and alias.get(index, {}).get("aliases", {}).get(name, None) is not None ): if __opts__["test"]: - ret["comment"] = "Alias {0} for index {1} will be removed".format( + ret["comment"] = "Alias {} for index {} will be removed".format( name, index ) ret["changes"]["old"] = ( @@ -144,25 +138,23 @@ def alias_absent(name, index): if ret["result"]: ret[ "comment" - ] = "Successfully removed alias {0} for index {1}".format( - name, index - ) + ] = "Successfully removed alias {} for index {}".format(name, index) ret["changes"]["old"] = ( alias.get(index, {}).get("aliases", {}).get(name, {}) ) else: ret[ "comment" - ] = "Failed to remove alias {0} for index {1} for unknown reasons".format( + ] = "Failed to remove alias {} for index {} for unknown reasons".format( name, index ) else: - ret["comment"] = "Alias {0} for index {1} is already absent".format( + ret["comment"] = "Alias {} for index {} is already absent".format( name, index ) except Exception as err: # pylint: disable=broad-except ret["result"] = False - ret["comment"] = six.text_type(err) + ret["comment"] = str(err) return ret @@ -208,13 +200,13 @@ def alias_present(name, index, definition=None): if not old: ret[ "comment" - ] = "Alias {0} for index {1} does not exist and will be created".format( + ] = "Alias {} for index {} does not exist and will be created".format( name, index ) else: ret[ "comment" - ] = "Alias {0} for index {1} exists with wrong configuration and will be overridden".format( + ] = "Alias {} for index {} exists with wrong configuration and will be overridden".format( name, index ) @@ -227,29 +219,27 @@ def alias_present(name, index, definition=None): if not old: ret[ "comment" - ] = "Successfully created alias {0} for index {1}".format( + ] = "Successfully created alias {} for index {}".format( name, index ) else: ret[ "comment" - ] = "Successfully replaced alias {0} for index {1}".format( + ] = "Successfully replaced alias {} for index {}".format( name, index ) else: ret["result"] = False - ret[ - "comment" - ] = "Cannot create alias {0} for index {1}, {2}".format( + ret["comment"] = "Cannot create alias {} for index {}, {}".format( name, index, output ) else: - ret["comment"] = "Alias {0} for index {1} is already present".format( + ret["comment"] = "Alias {} for index {} is already present".format( name, index ) except Exception as err: # pylint: disable=broad-except ret["result"] = False - ret["comment"] = six.text_type(err) + ret["comment"] = str(err) return ret @@ -268,7 +258,7 @@ def index_template_absent(name): index_template = __salt__["elasticsearch.index_template_get"](name=name) if index_template and name in index_template: if __opts__["test"]: - ret["comment"] = "Index template {0} will be removed".format(name) + ret["comment"] = "Index template {} will be removed".format(name) ret["changes"]["old"] = index_template[name] ret["result"] = None else: @@ -276,21 +266,21 @@ def index_template_absent(name): name=name ) if ret["result"]: - ret["comment"] = "Successfully removed index template {0}".format( + ret["comment"] = "Successfully removed index template {}".format( name ) ret["changes"]["old"] = index_template[name] else: ret[ "comment" - ] = "Failed to remove index template {0} for unknown reasons".format( + ] = "Failed to remove index template {} for unknown reasons".format( name ) else: - ret["comment"] = "Index template {0} is already absent".format(name) + ret["comment"] = "Index template {} is already absent".format(name) except Exception as err: # pylint: disable=broad-except ret["result"] = False - ret["comment"] = six.text_type(err) + ret["comment"] = str(err) return ret @@ -329,7 +319,7 @@ def index_template_present(name, definition, check_definition=False): if __opts__["test"]: ret[ "comment" - ] = "Index template {0} does not exist and will be created".format(name) + ] = "Index template {} does not exist and will be created".format(name) ret["changes"] = {"new": definition} ret["result"] = None else: @@ -337,7 +327,7 @@ def index_template_present(name, definition, check_definition=False): name=name, body=definition ) if output: - ret["comment"] = "Successfully created index template {0}".format( + ret["comment"] = "Successfully created index template {}".format( name ) ret["changes"] = { @@ -347,7 +337,7 @@ def index_template_present(name, definition, check_definition=False): } else: ret["result"] = False - ret["comment"] = "Cannot create index template {0}, {1}".format( + ret["comment"] = "Cannot create index template {}, {}".format( name, output ) else: @@ -370,7 +360,7 @@ def index_template_present(name, definition, check_definition=False): if __opts__["test"]: ret[ "comment" - ] = "Index template {0} exist but need to be updated".format( + ] = "Index template {} exist but need to be updated".format( name ) ret["changes"] = diff @@ -382,26 +372,26 @@ def index_template_present(name, definition, check_definition=False): if output: ret[ "comment" - ] = "Successfully updated index template {0}".format(name) + ] = "Successfully updated index template {}".format(name) ret["changes"] = diff else: ret["result"] = False ret[ "comment" - ] = "Cannot update index template {0}, {1}".format( + ] = "Cannot update index template {}, {}".format( name, output ) else: ret[ "comment" - ] = "Index template {0} is already present and up to date".format( + ] = "Index template {} is already present and up to date".format( name ) else: - ret["comment"] = "Index template {0} is already present".format(name) + ret["comment"] = "Index template {} is already present".format(name) except Exception as err: # pylint: disable=broad-except ret["result"] = False - ret["comment"] = six.text_type(err) + ret["comment"] = str(err) return ret @@ -420,23 +410,23 @@ def pipeline_absent(name): pipeline = __salt__["elasticsearch.pipeline_get"](id=name) if pipeline and name in pipeline: if __opts__["test"]: - ret["comment"] = "Pipeline {0} will be removed".format(name) + ret["comment"] = "Pipeline {} will be removed".format(name) ret["changes"]["old"] = pipeline[name] ret["result"] = None else: ret["result"] = __salt__["elasticsearch.pipeline_delete"](id=name) if ret["result"]: - ret["comment"] = "Successfully removed pipeline {0}".format(name) + ret["comment"] = "Successfully removed pipeline {}".format(name) ret["changes"]["old"] = pipeline[name] else: ret[ "comment" - ] = "Failed to remove pipeline {0} for unknown reasons".format(name) + ] = "Failed to remove pipeline {} for unknown reasons".format(name) else: - ret["comment"] = "Pipeline {0} is already absent".format(name) + ret["comment"] = "Pipeline {} is already absent".format(name) except Exception as err: # pylint: disable=broad-except ret["result"] = False - ret["comment"] = six.text_type(err) + ret["comment"] = str(err) return ret @@ -478,11 +468,11 @@ def pipeline_present(name, definition): if not pipeline: ret[ "comment" - ] = "Pipeline {0} does not exist and will be created".format(name) + ] = "Pipeline {} does not exist and will be created".format(name) else: ret[ "comment" - ] = "Pipeline {0} exists with wrong configuration and will be overridden".format( + ] = "Pipeline {} exists with wrong configuration and will be overridden".format( name ) @@ -493,23 +483,21 @@ def pipeline_present(name, definition): ) if output: if not pipeline: - ret["comment"] = "Successfully created pipeline {0}".format( - name - ) + ret["comment"] = "Successfully created pipeline {}".format(name) else: - ret["comment"] = "Successfully replaced pipeline {0}".format( + ret["comment"] = "Successfully replaced pipeline {}".format( name ) else: ret["result"] = False - ret["comment"] = "Cannot create pipeline {0}, {1}".format( + ret["comment"] = "Cannot create pipeline {}, {}".format( name, output ) else: - ret["comment"] = "Pipeline {0} is already present".format(name) + ret["comment"] = "Pipeline {} is already present".format(name) except Exception as err: # pylint: disable=broad-except ret["result"] = False - ret["comment"] = six.text_type(err) + ret["comment"] = str(err) return ret @@ -528,7 +516,7 @@ def search_template_absent(name): template = __salt__["elasticsearch.search_template_get"](id=name) if template: if __opts__["test"]: - ret["comment"] = "Search template {0} will be removed".format(name) + ret["comment"] = "Search template {} will be removed".format(name) ret["changes"]["old"] = salt.utils.json.loads(template["template"]) ret["result"] = None else: @@ -536,21 +524,21 @@ def search_template_absent(name): id=name ) if ret["result"]: - ret["comment"] = "Successfully removed search template {0}".format( + ret["comment"] = "Successfully removed search template {}".format( name ) ret["changes"]["old"] = salt.utils.json.loads(template["template"]) else: ret[ "comment" - ] = "Failed to remove search template {0} for unknown reasons".format( + ] = "Failed to remove search template {} for unknown reasons".format( name ) else: - ret["comment"] = "Search template {0} is already absent".format(name) + ret["comment"] = "Search template {} is already absent".format(name) except Exception as err: # pylint: disable=broad-except ret["result"] = False - ret["comment"] = six.text_type(err) + ret["comment"] = str(err) return ret @@ -591,13 +579,13 @@ def search_template_present(name, definition): if not template: ret[ "comment" - ] = "Search template {0} does not exist and will be created".format( + ] = "Search template {} does not exist and will be created".format( name ) else: ret[ "comment" - ] = "Search template {0} exists with wrong configuration and will be overridden".format( + ] = "Search template {} exists with wrong configuration and will be overridden".format( name ) @@ -610,20 +598,20 @@ def search_template_present(name, definition): if not template: ret[ "comment" - ] = "Successfully created search template {0}".format(name) + ] = "Successfully created search template {}".format(name) else: ret[ "comment" - ] = "Successfully replaced search template {0}".format(name) + ] = "Successfully replaced search template {}".format(name) else: ret["result"] = False - ret["comment"] = "Cannot create search template {0}, {1}".format( + ret["comment"] = "Cannot create search template {}, {}".format( name, output ) else: - ret["comment"] = "Search template {0} is already present".format(name) + ret["comment"] = "Search template {} is already present".format(name) except Exception as err: # pylint: disable=broad-except ret["result"] = False - ret["comment"] = six.text_type(err) + ret["comment"] = str(err) return ret diff --git a/salt/states/eselect.py b/salt/states/eselect.py index 112bf5abbcf..18d4f644771 100644 --- a/salt/states/eselect.py +++ b/salt/states/eselect.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of Gentoo configuration using eselect ================================================ @@ -7,8 +6,6 @@ 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"} @@ -52,20 +49,18 @@ def set_(name, target, module_parameter=None, action_parameter=None): ) if target == old_target: - ret["comment"] = "Target '{0}' is already set on '{1}' module.".format( + ret["comment"] = "Target '{}' is already set on '{}' 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( + ret["comment"] = "Target '{}' is not available for '{}' module.".format( target, name ) ret["result"] = False elif __opts__["test"]: - ret["comment"] = "Target '{0}' will be set on '{1}' module.".format( - target, name - ) + ret["comment"] = "Target '{}' will be set on '{}' module.".format(target, name) ret["result"] = None else: result = __salt__["eselect.set_target"]( @@ -76,9 +71,9 @@ def set_(name, target, module_parameter=None, action_parameter=None): ) if result: ret["changes"][name] = {"old": old_target, "new": target} - ret["comment"] = "Target '{0}' set on '{1}' module.".format(target, name) + ret["comment"] = "Target '{}' set on '{}' module.".format(target, name) else: - ret["comment"] = "Target '{0}' failed to be set on '{1}' module.".format( + ret["comment"] = "Target '{}' failed to be set on '{}' module.".format( target, name ) ret["result"] = False diff --git a/salt/states/esxdatacenter.py b/salt/states/esxdatacenter.py index f62353e51d0..48dd8d06339 100644 --- a/salt/states/esxdatacenter.py +++ b/salt/states/esxdatacenter.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Salt states to create and manage VMware vSphere datacenters (datacenters). @@ -49,16 +48,11 @@ State configuration: esxdatacenter.datacenter_configured """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals import logging import salt.exceptions -# Import Salt Libs -from salt.ext import six - # Get Logging Started log = logging.getLogger(__name__) LOGIN_DETAILS = {} @@ -90,7 +84,7 @@ def datacenter_configured(name): dc_name = __salt__["esxdatacenter.get_details"]()["datacenter"] else: dc_name = name - log.info("Running datacenter_configured for datacenter '{0}'" "".format(dc_name)) + log.info("Running datacenter_configured for datacenter '{}'" "".format(dc_name)) ret = {"name": name, "changes": {}, "result": None, "comment": "Default"} comments = [] si = None @@ -101,19 +95,16 @@ def datacenter_configured(name): ) if not dcs: if __opts__["test"]: - comments.append( - "State will create " "datacenter '{0}'.".format(dc_name) - ) + comments.append("State will create " "datacenter '{}'.".format(dc_name)) else: - log.debug("Creating datacenter '{0}'. ".format(dc_name)) + log.debug("Creating datacenter '{}'. ".format(dc_name)) __salt__["vsphere.create_datacenter"](dc_name, si) - comments.append("Created datacenter '{0}'.".format(dc_name)) + comments.append("Created datacenter '{}'.".format(dc_name)) log.info(comments[-1]) ret["changes"].update({"new": {"name": dc_name}}) else: comments.append( - "Datacenter '{0}' already exists. Nothing to be " - "done.".format(dc_name) + "Datacenter '{}' already exists. Nothing to be " "done.".format(dc_name) ) log.info(comments[-1]) __salt__["vsphere.disconnect"](si) @@ -125,9 +116,6 @@ def datacenter_configured(name): if si: __salt__["vsphere.disconnect"](si) ret.update( - { - "result": False if not __opts__["test"] else None, - "comment": six.text_type(exc), - } + {"result": False if not __opts__["test"] else None, "comment": str(exc)} ) return ret diff --git a/salt/states/esxvm.py b/salt/states/esxvm.py index e4c93b04bd1..b5c0020fdc8 100644 --- a/salt/states/esxvm.py +++ b/salt/states/esxvm.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Salt state to create, update VMware ESXi Virtual Machines. @@ -183,15 +182,11 @@ execution functions against ESXi hosts via a Salt Proxy Minion, and a larger sta example. """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import logging import sys -# Import Salt libs import salt.exceptions -import salt.ext.six as six from salt.config.schemas.esxvm import ESXVirtualMachineConfigSchema # External libraries @@ -307,7 +302,7 @@ def vm_configured( if __opts__["test"]: result.update( { - "comment": "The virtual machine {0}" + "comment": "The virtual machine {}" " will be registered.".format(vm_name) } ) @@ -321,7 +316,7 @@ def vm_configured( if __opts__["test"]: result.update( { - "comment": "The virtual machine {0}" + "comment": "The virtual machine {}" " will be created.".format(vm_name) } ) @@ -437,21 +432,21 @@ def vm_updated( { "result": True, "changes": {}, - "comment": "Virtual machine {0} is already up to date".format(vm_name), + "comment": "Virtual machine {} is already up to date".format(vm_name), } ) return result if __opts__["test"]: comment = ( - "State vm_updated will update virtual machine '{0}' " - "in datacenter '{1}':\n{2}".format( + "State vm_updated will update virtual machine '{}' " + "in datacenter '{}':\n{}".format( vm_name, datacenter, "\n".join( [ ":\n".join([key, difference.changes_str]) - for key, difference in six.iteritems(diffs) + for key, difference in diffs.items() ] ), ) @@ -482,7 +477,7 @@ def vm_updated( log.error("Error: %s", exc) if service_instance: __salt__["vsphere.disconnect"](service_instance) - result.update({"result": False, "comment": six.text_type(exc)}) + result.update({"result": False, "comment": str(exc)}) return result if power_on: @@ -492,7 +487,7 @@ def vm_updated( log.error("Error: %s", exc) if service_instance: __salt__["vsphere.disconnect"](service_instance) - result.update({"result": False, "comment": six.text_type(exc)}) + result.update({"result": False, "comment": str(exc)}) return result changes.update({"power_on": True}) @@ -502,7 +497,7 @@ def vm_updated( "name": name, "result": True, "changes": changes, - "comment": "Virtual machine " "{0} was updated successfully".format(vm_name), + "comment": "Virtual machine " "{} was updated successfully".format(vm_name), } return result @@ -534,7 +529,7 @@ def vm_created( result = {"name": name, "result": None, "changes": {}, "comment": ""} if __opts__["test"]: - result["comment"] = "Virtual machine {0} will be created".format(vm_name) + result["comment"] = "Virtual machine {} will be created".format(vm_name) return result service_instance = __salt__["vsphere.get_service_instance_via_proxy"]() @@ -562,7 +557,7 @@ def vm_created( log.error("Error: %s", exc) if service_instance: __salt__["vsphere.disconnect"](service_instance) - result.update({"result": False, "comment": six.text_type(exc)}) + result.update({"result": False, "comment": str(exc)}) return result if power_on: @@ -574,7 +569,7 @@ def vm_created( log.error("Error: %s", exc) if service_instance: __salt__["vsphere.disconnect"](service_instance) - result.update({"result": False, "comment": six.text_type(exc)}) + result.update({"result": False, "comment": str(exc)}) return result info["power_on"] = power_on @@ -584,7 +579,7 @@ def vm_created( "name": name, "result": True, "changes": changes, - "comment": "Virtual machine " "{0} created successfully".format(vm_name), + "comment": "Virtual machine " "{} created successfully".format(vm_name), } return result @@ -597,8 +592,8 @@ def vm_registered(vm_name, datacenter, placement, vm_file, power_on=False): """ result = {"name": vm_name, "result": None, "changes": {}, "comment": ""} - vmx_path = "{0}{1}".format(vm_file.folderPath, vm_file.file[0].path) - log.trace("Registering virtual machine with vmx file: {0}".format(vmx_path)) + vmx_path = "{}{}".format(vm_file.folderPath, vm_file.file[0].path) + log.trace("Registering virtual machine with vmx file: {}".format(vmx_path)) service_instance = __salt__["vsphere.get_service_instance_via_proxy"]() try: __salt__["vsphere.register_vm"]( @@ -608,13 +603,13 @@ def vm_registered(vm_name, datacenter, placement, vm_file, power_on=False): log.error("Error: %s", exc) if service_instance: __salt__["vsphere.disconnect"](service_instance) - result.update({"result": False, "comment": six.text_type(exc)}) + result.update({"result": False, "comment": str(exc)}) return result except salt.exceptions.VMwareVmRegisterError as exc: log.error("Error: %s", exc) if service_instance: __salt__["vsphere.disconnect"](service_instance) - result.update({"result": False, "comment": six.text_type(exc)}) + result.update({"result": False, "comment": str(exc)}) return result if power_on: @@ -626,14 +621,14 @@ def vm_registered(vm_name, datacenter, placement, vm_file, power_on=False): log.error("Error: %s", exc) if service_instance: __salt__["vsphere.disconnect"](service_instance) - result.update({"result": False, "comment": six.text_type(exc)}) + result.update({"result": False, "comment": str(exc)}) return result __salt__["vsphere.disconnect"](service_instance) result.update( { "result": True, "changes": {"name": vm_name, "power_on": power_on}, - "comment": "Virtual machine " "{0} registered successfully".format(vm_name), + "comment": "Virtual machine " "{} registered successfully".format(vm_name), } ) diff --git a/salt/states/ethtool.py b/salt/states/ethtool.py index 80e62da1e99..b636aa99488 100644 --- a/salt/states/ethtool.py +++ b/salt/states/ethtool.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Configuration of network device @@ -30,14 +29,9 @@ Configuration of network device """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import logging -# Import Salt libs -from salt.ext import six - # Set up logging log = logging.getLogger(__name__) @@ -91,9 +85,7 @@ def coalesce(name, **kwargs): "name": name, "changes": {}, "result": True, - "comment": "Network device {0} coalescing settings are up to date.".format( - name - ), + "comment": "Network device {} coalescing settings are up to date.".format(name), } apply_coalescing = False if "test" not in kwargs: @@ -104,7 +96,7 @@ def coalesce(name, **kwargs): old = __salt__["ethtool.show_coalesce"](name) if not isinstance(old, dict): ret["result"] = False - ret["comment"] = "Device {0} coalescing settings are not supported".format( + ret["comment"] = "Device {} coalescing settings are not supported".format( name ) return ret @@ -116,7 +108,7 @@ def coalesce(name, **kwargs): for key, value in kwargs.items(): if key in old and value != old[key]: new.update({key: value}) - diff.append("{0}: {1}".format(key, value)) + diff.append("{}: {}".format(key, value)) # Dry run if kwargs["test"]: @@ -125,20 +117,20 @@ def coalesce(name, **kwargs): if new: ret["result"] = None ret["comment"] = ( - "Device {0} coalescing settings are set to be " - "updated:\n{1}".format(name, "\n".join(diff)) + "Device {} coalescing settings are set to be " + "updated:\n{}".format(name, "\n".join(diff)) ) return ret # Prepare return output if new: apply_coalescing = True - ret["comment"] = "Device {0} coalescing settings updated.".format(name) + ret["comment"] = "Device {} coalescing settings updated.".format(name) ret["changes"]["ethtool_coalesce"] = "\n".join(diff) except AttributeError as error: ret["result"] = False - ret["comment"] = six.text_type(error) + ret["comment"] = str(error) return ret # Apply coalescing settings @@ -147,7 +139,7 @@ def coalesce(name, **kwargs): __salt__["ethtool.set_coalesce"](name, **new) except AttributeError as error: ret["result"] = False - ret["comment"] = six.text_type(error) + ret["comment"] = str(error) return ret return ret @@ -177,7 +169,7 @@ def ring(name, **kwargs): "name": name, "changes": {}, "result": True, - "comment": "Network device {0} ring parameters are up to date.".format(name), + "comment": "Network device {} ring parameters are up to date.".format(name), } apply_ring = False if "test" not in kwargs: @@ -188,7 +180,7 @@ def ring(name, **kwargs): old = __salt__["ethtool.show_ring"](name) if not isinstance(old, dict): ret["result"] = False - ret["comment"] = "Device {0} ring parameters are not supported".format(name) + ret["comment"] = "Device {} ring parameters are not supported".format(name) return ret new = {} @@ -198,11 +190,11 @@ def ring(name, **kwargs): for key, value in kwargs.items(): if key in old: if value == "max": - value = old["{0}_max".format(key)] + value = old["{}_max".format(key)] if value != old[key]: new.update({key: value}) - diff.append("{0}: {1}".format(key, value)) + diff.append("{}: {}".format(key, value)) # Dry run if kwargs["test"]: @@ -211,20 +203,20 @@ def ring(name, **kwargs): if new: ret["result"] = None ret["comment"] = ( - "Device {0} ring parameters are set to be " - "updated:\n{1}".format(name, "\n".join(diff)) + "Device {} ring parameters are set to be " + "updated:\n{}".format(name, "\n".join(diff)) ) return ret # Prepare return output if new: apply_ring = True - ret["comment"] = "Device {0} ring parameters updated.".format(name) + ret["comment"] = "Device {} ring parameters updated.".format(name) ret["changes"]["ethtool_ring"] = "\n".join(diff) except AttributeError as error: ret["result"] = False - ret["comment"] = six.text_type(error) + ret["comment"] = str(error) return ret # Apply ring parameters @@ -233,7 +225,7 @@ def ring(name, **kwargs): __salt__["ethtool.set_ring"](name, **new) except AttributeError as error: ret["result"] = False - ret["comment"] = six.text_type(error) + ret["comment"] = str(error) return ret return ret @@ -258,7 +250,7 @@ def offload(name, **kwargs): "name": name, "changes": {}, "result": True, - "comment": "Network device {0} offload settings are up to date.".format(name), + "comment": "Network device {} offload settings are up to date.".format(name), } apply_offload = False if "test" not in kwargs: @@ -269,9 +261,7 @@ def offload(name, **kwargs): old = __salt__["ethtool.show_offload"](name) if not isinstance(old, dict): ret["result"] = False - ret["comment"] = "Device {0} offload settings are not supported".format( - name - ) + ret["comment"] = "Device {} offload settings are not supported".format(name) return ret new = {} @@ -282,7 +272,7 @@ def offload(name, **kwargs): value = value and "on" or "off" if key in old and value != old[key]: new.update({key: value}) - diff.append("{0}: {1}".format(key, value)) + diff.append("{}: {}".format(key, value)) # Dry run if kwargs["test"]: @@ -291,20 +281,20 @@ def offload(name, **kwargs): if new: ret["result"] = None ret["comment"] = ( - "Device {0} offload settings are set to be " - "updated:\n{1}".format(name, "\n".join(diff)) + "Device {} offload settings are set to be " + "updated:\n{}".format(name, "\n".join(diff)) ) return ret # Prepare return output if new: apply_offload = True - ret["comment"] = "Device {0} offload settings updated.".format(name) + ret["comment"] = "Device {} offload settings updated.".format(name) ret["changes"]["ethtool_offload"] = "\n".join(diff) except AttributeError as error: ret["result"] = False - ret["comment"] = six.text_type(error) + ret["comment"] = str(error) return ret # Apply offload settings @@ -313,7 +303,7 @@ def offload(name, **kwargs): __salt__["ethtool.set_offload"](name, **new) except AttributeError as error: ret["result"] = False - ret["comment"] = six.text_type(error) + ret["comment"] = str(error) return ret return ret diff --git a/salt/states/gem.py b/salt/states/gem.py index 56e5f9e12ce..e5a1ab26b8b 100644 --- a/salt/states/gem.py +++ b/salt/states/gem.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Installation of Ruby modules packaged as gems ============================================= @@ -14,7 +13,6 @@ you can specify what ruby version and gemset to target. - user: rvm - ruby: jruby@jgemset """ -from __future__ import absolute_import, print_function, unicode_literals import logging import re @@ -120,7 +118,7 @@ def installed( return ret if __opts__["test"]: - ret["comment"] = "The gem {0} would have been installed".format(name) + ret["comment"] = "The gem {} would have been installed".format(name) return ret if __salt__["gem.install"]( name, @@ -171,7 +169,7 @@ def removed(name, ruby=None, user=None, gem_bin=None): return ret if __opts__["test"]: - ret["comment"] = "The gem {0} would have been removed".format(name) + ret["comment"] = "The gem {} would have been removed".format(name) return ret if __salt__["gem.uninstall"](name, ruby, gem_bin=gem_bin, runas=user): ret["result"] = True @@ -205,7 +203,7 @@ def sources_add(name, ruby=None, user=None): ret["comment"] = "Gem source is already added." return ret if __opts__["test"]: - ret["comment"] = "The gem source {0} would have been added.".format(name) + ret["comment"] = "The gem source {} would have been added.".format(name) return ret if __salt__["gem.sources_add"](source_uri=name, ruby=ruby, runas=user): ret["result"] = True diff --git a/salt/states/glance_image.py b/salt/states/glance_image.py index 6b501559a4e..090ce522bba 100644 --- a/salt/states/glance_image.py +++ b/salt/states/glance_image.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of OpenStack Glance Images ======================================== @@ -23,7 +22,6 @@ Example States - name: cirros """ -from __future__ import absolute_import, print_function, unicode_literals __virtualname__ = "glance_image" diff --git a/salt/states/glusterfs.py b/salt/states/glusterfs.py index c3ecd631aa2..1437c721631 100644 --- a/salt/states/glusterfs.py +++ b/salt/states/glusterfs.py @@ -1,14 +1,10 @@ -# -*- coding: utf-8 -*- """ Manage GlusterFS pool. """ -# Import python libs -from __future__ import absolute_import, generators, print_function, unicode_literals import logging -# Import salt libs import salt.utils.cloud as suc import salt.utils.network from salt.exceptions import SaltCloudException @@ -85,16 +81,16 @@ def peered(name): if peers and any(name in v["hostnames"] for v in peers.values()): ret["result"] = True - ret["comment"] = "Host {0} already peered".format(name) + ret["comment"] = "Host {} already peered".format(name) return ret if __opts__["test"]: - ret["comment"] = "Peer {0} will be added.".format(name) + ret["comment"] = "Peer {} will be added.".format(name) ret["result"] = None return ret if not __salt__["glusterfs.peer"](name): - ret["comment"] = "Failed to peer with {0}, please check logs for errors".format( + ret["comment"] = "Failed to peer with {}, please check logs for errors".format( name ) return ret @@ -103,12 +99,12 @@ def peered(name): newpeers = __salt__["glusterfs.peer_status"]() if newpeers and any(name in v["hostnames"] for v in newpeers.values()): ret["result"] = True - ret["comment"] = "Host {0} successfully peered".format(name) + ret["comment"] = "Host {} successfully peered".format(name) ret["changes"] = {"new": newpeers, "old": peers} else: ret[ "comment" - ] = "Host {0} was successfully peered but did not appear in the list of peers".format( + ] = "Host {} was successfully peered but did not appear in the list of peers".format( name ) return ret @@ -183,7 +179,7 @@ def volume_present( volumes = __salt__["glusterfs.list_volumes"]() if name not in volumes: if __opts__["test"]: - comment = "Volume {0} will be created".format(name) + comment = "Volume {} will be created".format(name) if start: comment += " and started" ret["comment"] = comment @@ -195,16 +191,16 @@ def volume_present( ) if not vol_created: - ret["comment"] = "Creation of volume {0} failed".format(name) + ret["comment"] = "Creation of volume {} failed".format(name) return ret old_volumes = volumes volumes = __salt__["glusterfs.list_volumes"]() if name in volumes: ret["changes"] = {"new": volumes, "old": old_volumes} - ret["comment"] = "Volume {0} is created".format(name) + ret["comment"] = "Volume {} is created".format(name) else: - ret["comment"] = "Volume {0} already exists".format(name) + ret["comment"] = "Volume {} already exists".format(name) if start: if __opts__["test"]: @@ -253,26 +249,26 @@ def started(name): volinfo = __salt__["glusterfs.info"]() if name not in volinfo: ret["result"] = False - ret["comment"] = "Volume {0} does not exist".format(name) + ret["comment"] = "Volume {} does not exist".format(name) return ret if int(volinfo[name]["status"]) == 1: - ret["comment"] = "Volume {0} is already started".format(name) + ret["comment"] = "Volume {} is already started".format(name) ret["result"] = True return ret elif __opts__["test"]: - ret["comment"] = "Volume {0} will be started".format(name) + ret["comment"] = "Volume {} will be started".format(name) ret["result"] = None return ret vol_started = __salt__["glusterfs.start_volume"](name) if vol_started: ret["result"] = True - ret["comment"] = "Volume {0} is started".format(name) + ret["comment"] = "Volume {} is started".format(name) ret["change"] = {"new": "started", "old": "stopped"} else: ret["result"] = False - ret["comment"] = "Failed to start volume {0}".format(name) + ret["comment"] = "Failed to start volume {}".format(name) return ret @@ -306,23 +302,23 @@ def add_volume_bricks(name, bricks): volinfo = __salt__["glusterfs.info"]() if name not in volinfo: - ret["comment"] = "Volume {0} does not exist".format(name) + ret["comment"] = "Volume {} does not exist".format(name) return ret if int(volinfo[name]["status"]) != 1: - ret["comment"] = "Volume {0} is not started".format(name) + ret["comment"] = "Volume {} is not started".format(name) return ret current_bricks = [brick["path"] for brick in volinfo[name]["bricks"].values()] if not set(bricks) - set(current_bricks): ret["result"] = True - ret["comment"] = "Bricks already added in volume {0}".format(name) + ret["comment"] = "Bricks already added in volume {}".format(name) return ret bricks_added = __salt__["glusterfs.add_volume_bricks"](name, bricks) if bricks_added: ret["result"] = True - ret["comment"] = "Bricks successfully added to volume {0}".format(name) + ret["comment"] = "Bricks successfully added to volume {}".format(name) new_bricks = [ brick["path"] for brick in __salt__["glusterfs.info"]()[name]["bricks"].values() @@ -330,7 +326,7 @@ def add_volume_bricks(name, bricks): ret["changes"] = {"new": new_bricks, "old": current_bricks} return ret - ret["comment"] = "Adding bricks to volume {0} failed".format(name) + ret["comment"] = "Adding bricks to volume {} failed".format(name) return ret @@ -363,9 +359,7 @@ def op_version(name, version): return ret if current == version: - ret[ - "comment" - ] = "Glusterfs cluster.op-version for {0} already set to {1}".format( + ret["comment"] = "Glusterfs cluster.op-version for {} already set to {}".format( name, version ) ret["result"] = True @@ -373,7 +367,7 @@ def op_version(name, version): elif __opts__["test"]: ret[ "comment" - ] = "An attempt would be made to set the cluster.op-version for {0} to {1}.".format( + ] = "An attempt would be made to set the cluster.op-version for {} to {}.".format( name, version ) ret["result"] = None @@ -426,7 +420,7 @@ def max_op_version(name): if current == max_version: ret[ "comment" - ] = "The cluster.op-version is already set to the cluster.max-op-version of {0}".format( + ] = "The cluster.op-version is already set to the cluster.max-op-version of {}".format( current ) ret["result"] = True @@ -434,7 +428,7 @@ def max_op_version(name): elif __opts__["test"]: ret[ "comment" - ] = "An attempt would be made to set the cluster.op-version to {0}.".format( + ] = "An attempt would be made to set the cluster.op-version to {}.".format( max_version ) ret["result"] = None diff --git a/salt/states/gnomedesktop.py b/salt/states/gnomedesktop.py index 4a7d53e6e67..24c9df87796 100644 --- a/salt/states/gnomedesktop.py +++ b/salt/states/gnomedesktop.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Configuration of the GNOME desktop ======================================== @@ -24,15 +23,10 @@ Control the GNOME settings - clock_show_date: true - clock_format: 12h """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import logging import re -# Import 3rd-party libs -from salt.ext import six - log = logging.getLogger(__name__) @@ -41,7 +35,7 @@ def _check_current_value(gnome_kwargs, value): Check the current value with the passed value """ current_value = __salt__["gnome.get"](**gnome_kwargs) - return six.text_type(current_value) == six.text_type(value) + return str(current_value) == str(value) def _do(name, gnome_kwargs, preferences): @@ -62,11 +56,11 @@ def _do(name, gnome_kwargs, preferences): # need to convert boolean values to strings and make lowercase to # pass to gsettings - value = six.text_type(value).lower() + value = str(value).lower() elif isinstance(value, int): ftype = "int" - elif isinstance(value, six.string_types): + elif isinstance(value, str): ftype = "string" else: ftype = "string" @@ -74,12 +68,12 @@ def _do(name, gnome_kwargs, preferences): gnome_kwargs.update({"key": key, "value": value}) if _check_current_value(gnome_kwargs, value): - messages.append("{0} is already set to {1}".format(key, value)) + messages.append("{} is already set to {}".format(key, value)) else: result = __salt__["gnome.set"](**gnome_kwargs) if result["retcode"] == 0: - messages.append("Setting {0} to {1}".format(key, value)) - ret["changes"][key] = "{0}:{1}".format(key, value) + messages.append("Setting {} to {}".format(key, value)) + ret["changes"][key] = "{}:{}".format(key, value) ret["result"] = True else: messages.append(result["stdout"]) diff --git a/salt/states/grafana.py b/salt/states/grafana.py index a40579a4172..b8cf6a68dc7 100644 --- a/salt/states/grafana.py +++ b/salt/states/grafana.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage Grafana Dashboards @@ -166,17 +165,11 @@ add rows if they do not exist in existing dashboards, and to update rows if they exist in dashboards. The module will not manage rows that are not defined, allowing users to manage their own custom rows. """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import copy -# Import Salt libs import salt.utils.json from salt.exceptions import SaltInvocationError - -# Import 3rd-party -from salt.ext.six import string_types from salt.utils.dictdiffer import DictDiffer @@ -193,10 +186,10 @@ def _parse_profile(profile): """ From a pillar key, or a dictionary, return index and host keys. """ - if isinstance(profile, string_types): + if isinstance(profile, str): _profile = __salt__["config.option"](profile) if not _profile: - msg = "Pillar key for profile {0} not found.".format(profile) + msg = "Pillar key for profile {} not found.".format(profile) raise SaltInvocationError(msg) else: _profile = profile @@ -299,7 +292,7 @@ def dashboard_present( " dashboard template was provided." ) if __opts__["test"]: - ret["comment"] = "Dashboard {0} is set to be created.".format(name) + ret["comment"] = "Dashboard {} is set to be created.".format(name) ret["result"] = None return ret _dashboard = dashboard @@ -337,14 +330,12 @@ def dashboard_present( update_rows.append(title) if not update_rows: ret["result"] = True - ret["comment"] = "Dashboard {0} is up to date".format(name) + ret["comment"] = "Dashboard {} is up to date".format(name) return ret if __opts__["test"]: - msg = "Dashboard {0} is set to be updated.".format(name) + msg = "Dashboard {} is set to be updated.".format(name) if update_rows: - msg = "{0} The following rows set to be updated: {1}".format( - msg, update_rows - ) + msg = "{} The following rows set to be updated: {}".format(msg, update_rows) ret["comment"] = msg return ret body = { @@ -359,13 +350,13 @@ def dashboard_present( if updated: ret["result"] = True ret["changes"]["changed"] = name - msg = "Updated dashboard {0}.".format(name) + msg = "Updated dashboard {}.".format(name) if update_rows: - msg = "{0} The following rows were updated: {1}".format(msg, update_rows) + msg = "{} The following rows were updated: {}".format(msg, update_rows) ret["comment"] = msg else: ret["result"] = False - msg = "Failed to update dashboard {0}.".format(name) + msg = "Failed to update dashboard {}.".format(name) ret["comment"] = msg return ret @@ -394,7 +385,7 @@ def dashboard_absent(name, hosts=None, profile="grafana"): if exists: if __opts__["test"]: - ret["comment"] = "Dashboard {0} is set to be removed.".format(name) + ret["comment"] = "Dashboard {} is set to be removed.".format(name) return ret deleted = __salt__["elasticsearch.delete"]( index=index, doc_type="dashboard", id=name, hosts=hosts @@ -405,9 +396,9 @@ def dashboard_absent(name, hosts=None, profile="grafana"): ret["changes"]["new"] = None else: ret["result"] = False - ret["comment"] = "Failed to delete {0} dashboard.".format(name) + ret["comment"] = "Failed to delete {} dashboard.".format(name) else: ret["result"] = True - ret["comment"] = "Dashboard {0} does not exist.".format(name) + ret["comment"] = "Dashboard {} does not exist.".format(name) return ret diff --git a/salt/states/grafana4_dashboard.py b/salt/states/grafana4_dashboard.py index 5621058b075..27f33be68e9 100644 --- a/salt/states/grafana4_dashboard.py +++ b/salt/states/grafana4_dashboard.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage Grafana v4.0 Dashboards @@ -53,14 +52,10 @@ allowing users to manage their own custom rows. type: graph """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import copy -# Import Salt libs import salt.utils.json -from salt.ext import six from salt.utils.dictdiffer import DictDiffer @@ -114,7 +109,7 @@ def present( ret = {"name": name, "result": True, "comment": "", "changes": {}} dashboard = dashboard or {} - if isinstance(profile, six.string_types): + if isinstance(profile, str): profile = __salt__["config.option"](profile) # Add pillar keys for default configuration @@ -144,18 +139,18 @@ def present( if not old_dashboard: if __opts__["test"]: ret["result"] = None - ret["comment"] = "Dashboard {0} is set to be created.".format(name) + ret["comment"] = "Dashboard {} is set to be created.".format(name) return ret response = __salt__["grafana4.create_update_dashboard"]( dashboard=new_dashboard, overwrite=True, profile=profile ) if response.get("status") == "success": - ret["comment"] = "Dashboard {0} created.".format(name) - ret["changes"]["new"] = "Dashboard {0} created.".format(name) + ret["comment"] = "Dashboard {} created.".format(name) + ret["changes"]["new"] = "Dashboard {} created.".format(name) else: ret["result"] = False - ret["comment"] = ("Failed to create dashboard {0}, " "response={1}").format( + ret["comment"] = ("Failed to create dashboard {}, " "response={}").format( name, response ) return ret @@ -199,13 +194,13 @@ def present( dashboard_diff = DictDiffer( _cleaned(updated_dashboard), _cleaned(old_dashboard) ) - ret["comment"] = "Dashboard {0} updated.".format(name) + ret["comment"] = "Dashboard {} updated.".format(name) ret["changes"] = _dashboard_diff( _cleaned(new_dashboard), _cleaned(old_dashboard) ) else: ret["result"] = False - ret["comment"] = ("Failed to update dashboard {0}, " "response={1}").format( + ret["comment"] = ("Failed to update dashboard {}, " "response={}").format( name, response ) return ret @@ -230,19 +225,19 @@ def absent(name, orgname=None, profile="grafana"): """ ret = {"name": name, "result": True, "comment": "", "changes": {}} - if isinstance(profile, six.string_types): + if isinstance(profile, str): profile = __salt__["config.option"](profile) existing_dashboard = __salt__["grafana4.get_dashboard"](name, orgname, profile) if existing_dashboard: if __opts__["test"]: ret["result"] = None - ret["comment"] = "Dashboard {0} is set to be deleted.".format(name) + ret["comment"] = "Dashboard {} is set to be deleted.".format(name) return ret __salt__["grafana4.delete_dashboard"](name, profile=profile) - ret["comment"] = "Dashboard {0} deleted.".format(name) - ret["changes"]["new"] = "Dashboard {0} deleted.".format(name) + ret["comment"] = "Dashboard {} deleted.".format(name) + ret["changes"]["new"] = "Dashboard {} deleted.".format(name) return ret ret["comment"] = "Dashboard absent" @@ -295,7 +290,7 @@ def _inherited_dashboard(dashboard, base_dashboards_from_pillar, ret): base_dashboards.append(base_dashboard) elif base_dashboard_from_pillar != _DEFAULT_DASHBOARD_PILLAR: ret.setdefault("warnings", []) - warning_message = 'Cannot find dashboard pillar "{0}".'.format( + warning_message = 'Cannot find dashboard pillar "{}".'.format( base_dashboard_from_pillar ) if warning_message not in ret["warnings"]: @@ -320,7 +315,7 @@ def _inherited_row(row, base_rows_from_pillar, ret): base_rows.append(base_row) elif base_row_from_pillar != _DEFAULT_ROW_PILLAR: ret.setdefault("warnings", []) - warning_message = 'Cannot find row pillar "{0}".'.format( + warning_message = 'Cannot find row pillar "{}".'.format( base_row_from_pillar ) if warning_message not in ret["warnings"]: @@ -342,7 +337,7 @@ def _inherited_panel(panel, base_panels_from_pillar, ret): base_panels.append(base_panel) elif base_panel_from_pillar != _DEFAULT_PANEL_PILLAR: ret.setdefault("warnings", []) - warning_message = 'Cannot find panel pillar "{0}".'.format( + warning_message = 'Cannot find panel pillar "{}".'.format( base_panel_from_pillar ) if warning_message not in ret["warnings"]: @@ -530,7 +525,7 @@ def _dashboard_diff(_new_dashboard, _old_dashboard): def _stripped(d): """Strip falsey entries.""" ret = {} - for k, v in six.iteritems(d): + for k, v in d.items(): if v: ret[k] = v return ret diff --git a/salt/states/grafana4_datasource.py b/salt/states/grafana4_datasource.py index 7d7d0df88e6..b0ebe8d02d3 100644 --- a/salt/states/grafana4_datasource.py +++ b/salt/states/grafana4_datasource.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage Grafana v4.0 data sources @@ -43,9 +42,7 @@ to update data sources if the already exists. - basic_auth_password: mypass - is_default: true """ -from __future__ import absolute_import, print_function, unicode_literals -from salt.ext.six import string_types from salt.utils.dictdiffer import deep_diff @@ -129,7 +126,7 @@ def present( Configuration profile used to connect to the Grafana instance. Default is 'grafana'. """ - if isinstance(profile, string_types): + if isinstance(profile, str): profile = __salt__["config.option"](profile) ret = {"name": name, "result": None, "comment": None, "changes": {}} @@ -155,12 +152,12 @@ def present( if not datasource: if __opts__["test"]: - ret["comment"] = "Datasource {0} will be created".format(name) + ret["comment"] = "Datasource {} will be created".format(name) return ret __salt__["grafana4.create_datasource"](profile=profile, **data) datasource = __salt__["grafana4.get_datasource"](name, profile=profile) ret["result"] = True - ret["comment"] = "New data source {0} added".format(name) + ret["comment"] = "New data source {} added".format(name) ret["changes"] = data return ret @@ -171,16 +168,16 @@ def present( datasource[key] = None if data == datasource: - ret["comment"] = "Data source {0} already up-to-date".format(name) + ret["comment"] = "Data source {} already up-to-date".format(name) return ret if __opts__["test"]: - ret["comment"] = "Datasource {0} will be updated".format(name) + ret["comment"] = "Datasource {} will be updated".format(name) return ret __salt__["grafana4.update_datasource"](datasource["id"], profile=profile, **data) ret["result"] = True ret["changes"] = deep_diff(datasource, data, ignore=["id", "orgId", "readOnly"]) - ret["comment"] = "Data source {0} updated".format(name) + ret["comment"] = "Data source {} updated".format(name) return ret @@ -198,7 +195,7 @@ def absent(name, orgname=None, profile="grafana"): Configuration profile used to connect to the Grafana instance. Default is 'grafana'. """ - if isinstance(profile, string_types): + if isinstance(profile, str): profile = __salt__["config.option"](profile) ret = {"name": name, "result": None, "comment": None, "changes": {}} @@ -206,17 +203,17 @@ def absent(name, orgname=None, profile="grafana"): if not datasource: ret["result"] = True - ret["comment"] = "Data source {0} already absent".format(name) + ret["comment"] = "Data source {} already absent".format(name) return ret if __opts__["test"]: - ret["comment"] = "Datasource {0} will be deleted".format(name) + ret["comment"] = "Datasource {} will be deleted".format(name) return ret __salt__["grafana4.delete_datasource"](datasource["id"], profile=profile) ret["result"] = True ret["changes"][name] = "Absent" - ret["comment"] = "Data source {0} was deleted".format(name) + ret["comment"] = "Data source {} was deleted".format(name) return ret diff --git a/salt/states/grafana4_org.py b/salt/states/grafana4_org.py index bb48e953358..25ff2ccbcfb 100644 --- a/salt/states/grafana4_org.py +++ b/salt/states/grafana4_org.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage Grafana v4.0 orgs @@ -42,13 +41,9 @@ Manage Grafana v4.0 orgs - state: "" - country: "" """ -from __future__ import absolute_import, print_function, unicode_literals import salt.utils.dictupdate as dictupdate from requests.exceptions import HTTPError - -# Import 3rd-party libs -from salt.ext.six import string_types from salt.utils.dictdiffer import deep_diff @@ -119,7 +114,7 @@ def present( Configuration profile used to connect to the Grafana instance. Default is 'grafana'. """ - if isinstance(profile, string_types): + if isinstance(profile, str): profile = __salt__["config.option"](profile) ret = {"name": name, "result": None, "comment": None, "changes": {}} @@ -134,12 +129,12 @@ def present( if create: if __opts__["test"]: - ret["comment"] = "Org {0} will be created".format(name) + ret["comment"] = "Org {} will be created".format(name) return ret __salt__["grafana4.create_org"](profile=profile, name=name) org = __salt__["grafana4.get_org"](name, profile) ret["changes"] = org - ret["comment"] = "New org {0} added".format(name) + ret["comment"] = "New org {} added".format(name) data = _get_json_data( address1=address1, @@ -152,7 +147,7 @@ def present( ) if data != org["address"]: if __opts__["test"]: - ret["comment"] = "Org {0} address will be updated".format(name) + ret["comment"] = "Org {} address will be updated".format(name) return ret __salt__["grafana4.update_org_address"](name, profile=profile, **data) if create: @@ -169,7 +164,7 @@ def present( ) if data != prefs: if __opts__["test"]: - ret["comment"] = "Org {0} prefs will be updated".format(name) + ret["comment"] = "Org {} prefs will be updated".format(name) return ret __salt__["grafana4.update_org_prefs"](name, profile=profile, **data) if create: @@ -188,7 +183,7 @@ def present( if username in db_users: if role is False: if __opts__["test"]: - ret["comment"] = "Org {0} user {1} will be " "deleted".format( + ret["comment"] = "Org {} user {} will be " "deleted".format( name, username ) return ret @@ -198,7 +193,7 @@ def present( elif role != db_users[username]["role"]: if __opts__["test"]: ret["comment"] = ( - "Org {0} user {1} role will be " + "Org {} user {} role will be " "updated".format(name, username) ) return ret @@ -210,7 +205,7 @@ def present( ) elif role: if __opts__["test"]: - ret["comment"] = "Org {0} user {1} will be created".format( + ret["comment"] = "Org {} user {} will be created".format( name, username ) return ret @@ -232,10 +227,10 @@ def present( ret["result"] = True if not create: if ret["changes"]: - ret["comment"] = "Org {0} updated".format(name) + ret["comment"] = "Org {} updated".format(name) else: ret["changes"] = {} - ret["comment"] = "Org {0} already up-to-date".format(name) + ret["comment"] = "Org {} already up-to-date".format(name) return ret @@ -251,7 +246,7 @@ def absent(name, profile="grafana"): Configuration profile used to connect to the Grafana instance. Default is 'grafana'. """ - if isinstance(profile, string_types): + if isinstance(profile, str): profile = __salt__["config.option"](profile) ret = {"name": name, "result": None, "comment": None, "changes": {}} @@ -259,17 +254,17 @@ def absent(name, profile="grafana"): if not org: ret["result"] = True - ret["comment"] = "Org {0} already absent".format(name) + ret["comment"] = "Org {} already absent".format(name) return ret if __opts__["test"]: - ret["comment"] = "Org {0} will be deleted".format(name) + ret["comment"] = "Org {} will be deleted".format(name) return ret __salt__["grafana4.delete_org"](org["id"], profile=profile) ret["result"] = True ret["changes"][name] = "Absent" - ret["comment"] = "Org {0} was deleted".format(name) + ret["comment"] = "Org {} was deleted".format(name) return ret diff --git a/salt/states/grafana4_user.py b/salt/states/grafana4_user.py index 6e444daace4..813c4e5aae4 100644 --- a/salt/states/grafana4_user.py +++ b/salt/states/grafana4_user.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage Grafana v4.0 users @@ -37,12 +36,8 @@ Manage Grafana v4.0 users - fullname: Foo Bar - is_admin: true """ -from __future__ import absolute_import, print_function, unicode_literals import salt.utils.dictupdate as dictupdate - -# Import 3rd-party libs -from salt.ext.six import string_types from salt.utils.dictdiffer import deep_diff @@ -81,7 +76,7 @@ def present( Configuration profile used to connect to the Grafana instance. Default is 'grafana'. """ - if isinstance(profile, string_types): + if isinstance(profile, str): profile = __salt__["config.option"](profile) ret = {"name": name, "result": None, "comment": None, "changes": {}} @@ -90,7 +85,7 @@ def present( if create: if __opts__["test"]: - ret["comment"] = "User {0} will be created".format(name) + ret["comment"] = "User {} will be created".format(name) return ret __salt__["grafana4.create_user"]( login=name, password=password, email=email, name=fullname, profile=profile @@ -106,7 +101,7 @@ def present( login=None, email=None, name=None, theme=None, defaults=user_data ): if __opts__["test"]: - ret["comment"] = "User {0} will be updated".format(name) + ret["comment"] = "User {} will be updated".format(name) return ret __salt__["grafana4.update_user"](user["id"], profile=profile, **data) dictupdate.update( @@ -116,7 +111,7 @@ def present( if user["isAdmin"] != is_admin: if __opts__["test"]: - ret["comment"] = "User {0} isAdmin status will be updated".format(name) + ret["comment"] = "User {} isAdmin status will be updated".format(name) return ret __salt__["grafana4.update_user_permissions"]( user["id"], isGrafanaAdmin=is_admin, profile=profile @@ -129,13 +124,13 @@ def present( ret["result"] = True if create: ret["changes"] = ret["changes"]["new"] - ret["comment"] = "New user {0} added".format(name) + ret["comment"] = "New user {} added".format(name) else: if ret["changes"]: - ret["comment"] = "User {0} updated".format(name) + ret["comment"] = "User {} updated".format(name) else: ret["changes"] = {} - ret["comment"] = "User {0} already up-to-date".format(name) + ret["comment"] = "User {} already up-to-date".format(name) return ret @@ -151,7 +146,7 @@ def absent(name, profile="grafana"): Configuration profile used to connect to the Grafana instance. Default is 'grafana'. """ - if isinstance(profile, string_types): + if isinstance(profile, str): profile = __salt__["config.option"](profile) ret = {"name": name, "result": None, "comment": None, "changes": {}} @@ -159,7 +154,7 @@ def absent(name, profile="grafana"): if user: if __opts__["test"]: - ret["comment"] = "User {0} will be deleted".format(name) + ret["comment"] = "User {} will be deleted".format(name) return ret orgs = __salt__["grafana4.get_user_orgs"](user["id"], profile=profile) __salt__["grafana4.delete_user"](user["id"], profile=profile) @@ -176,12 +171,12 @@ def absent(name, profile="grafana"): ) else: ret["result"] = True - ret["comment"] = "User {0} already absent".format(name) + ret["comment"] = "User {} already absent".format(name) return ret ret["result"] = True ret["changes"][name] = "Absent" - ret["comment"] = "User {0} was deleted".format(name) + ret["comment"] = "User {} was deleted".format(name) return ret diff --git a/salt/states/grafana_dashboard.py b/salt/states/grafana_dashboard.py index 09e0fde7a16..a56551c28e6 100644 --- a/salt/states/grafana_dashboard.py +++ b/salt/states/grafana_dashboard.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage Grafana v2.0 Dashboards @@ -38,16 +37,11 @@ they exist in dashboards. The module will not manage rows that are not defined, allowing users to manage their own custom rows. """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import copy import requests - -# Import Salt libs import salt.utils.json -from salt.ext import six from salt.utils.dictdiffer import DictDiffer @@ -102,7 +96,7 @@ def present( base_rows_from_pillar = base_rows_from_pillar or [] dashboard = dashboard or {} - if isinstance(profile, six.string_types): + if isinstance(profile, str): profile = __salt__["config.option"](profile) # Add pillar keys for default configuration @@ -127,21 +121,21 @@ def present( _ensure_annotations(new_dashboard) # Create dashboard if it does not exist - url = "db/{0}".format(name) + url = "db/{}".format(name) old_dashboard = _get(url, profile) if not old_dashboard: if __opts__["test"]: ret["result"] = None - ret["comment"] = "Dashboard {0} is set to be created.".format(name) + ret["comment"] = "Dashboard {} is set to be created.".format(name) return ret response = _update(new_dashboard, profile) if response.get("status") == "success": - ret["comment"] = "Dashboard {0} created.".format(name) - ret["changes"]["new"] = "Dashboard {0} created.".format(name) + ret["comment"] = "Dashboard {} created.".format(name) + ret["changes"]["new"] = "Dashboard {} created.".format(name) else: ret["result"] = False - ret["comment"] = ("Failed to create dashboard {0}, " "response={1}").format( + ret["comment"] = ("Failed to create dashboard {}, " "response={}").format( name, response ) return ret @@ -181,13 +175,13 @@ def present( dashboard_diff = DictDiffer( _cleaned(updated_dashboard), _cleaned(old_dashboard) ) - ret["comment"] = "Dashboard {0} updated.".format(name) + ret["comment"] = "Dashboard {} updated.".format(name) ret["changes"] = _dashboard_diff( _cleaned(new_dashboard), _cleaned(old_dashboard) ) else: ret["result"] = False - ret["comment"] = ("Failed to update dashboard {0}, " "response={1}").format( + ret["comment"] = ("Failed to update dashboard {}, " "response={}").format( name, response ) return ret @@ -208,20 +202,20 @@ def absent(name, profile="grafana"): """ ret = {"name": name, "result": True, "comment": "", "changes": {}} - if isinstance(profile, six.string_types): + if isinstance(profile, str): profile = __salt__["config.option"](profile) - url = "db/{0}".format(name) + url = "db/{}".format(name) existing_dashboard = _get(url, profile) if existing_dashboard: if __opts__["test"]: ret["result"] = None - ret["comment"] = "Dashboard {0} is set to be deleted.".format(name) + ret["comment"] = "Dashboard {} is set to be deleted.".format(name) return ret _delete(url, profile) - ret["comment"] = "Dashboard {0} deleted.".format(name) - ret["changes"]["new"] = "Dashboard {0} deleted.".format(name) + ret["comment"] = "Dashboard {} deleted.".format(name) + ret["changes"]["new"] = "Dashboard {} deleted.".format(name) return ret ret["comment"] = "Dashboard absent" @@ -273,7 +267,7 @@ def _inherited_dashboard(dashboard, base_dashboards_from_pillar, ret): base_dashboards.append(base_dashboard) elif base_dashboard_from_pillar != _DEFAULT_DASHBOARD_PILLAR: ret.setdefault("warnings", []) - warning_message = 'Cannot find dashboard pillar "{0}".'.format( + warning_message = 'Cannot find dashboard pillar "{}".'.format( base_dashboard_from_pillar ) if warning_message not in ret["warnings"]: @@ -298,7 +292,7 @@ def _inherited_row(row, base_rows_from_pillar, ret): base_rows.append(base_row) elif base_row_from_pillar != _DEFAULT_ROW_PILLAR: ret.setdefault("warnings", []) - warning_message = 'Cannot find row pillar "{0}".'.format( + warning_message = 'Cannot find row pillar "{}".'.format( base_row_from_pillar ) if warning_message not in ret["warnings"]: @@ -320,7 +314,7 @@ def _inherited_panel(panel, base_panels_from_pillar, ret): base_panels.append(base_panel) elif base_panel_from_pillar != _DEFAULT_PANEL_PILLAR: ret.setdefault("warnings", []) - warning_message = 'Cannot find panel pillar "{0}".'.format( + warning_message = 'Cannot find panel pillar "{}".'.format( base_panel_from_pillar ) if warning_message not in ret["warnings"]: @@ -426,12 +420,12 @@ def _ensure_annotations(dashboard): def _get(url, profile): """Get a specific dashboard.""" - request_url = "{0}/api/dashboards/{1}".format(profile.get("grafana_url"), url) + request_url = "{}/api/dashboards/{}".format(profile.get("grafana_url"), url) response = requests.get( request_url, headers={ "Accept": "application/json", - "Authorization": "Bearer {0}".format(profile.get("grafana_token")), + "Authorization": "Bearer {}".format(profile.get("grafana_token")), }, timeout=profile.get("grafana_timeout", 3), ) @@ -445,12 +439,12 @@ def _get(url, profile): def _delete(url, profile): """Delete a specific dashboard.""" - request_url = "{0}/api/dashboards/{1}".format(profile.get("grafana_url"), url) + request_url = "{}/api/dashboards/{}".format(profile.get("grafana_url"), url) response = requests.delete( request_url, headers={ "Accept": "application/json", - "Authorization": "Bearer {0}".format(profile.get("grafana_token")), + "Authorization": "Bearer {}".format(profile.get("grafana_token")), }, timeout=profile.get("grafana_timeout"), ) @@ -461,10 +455,10 @@ def _delete(url, profile): def _update(dashboard, profile): """Update a specific dashboard.""" payload = {"dashboard": dashboard, "overwrite": True} - request_url = "{0}/api/dashboards/db".format(profile.get("grafana_url")) + request_url = "{}/api/dashboards/db".format(profile.get("grafana_url")) response = requests.post( request_url, - headers={"Authorization": "Bearer {0}".format(profile.get("grafana_token"))}, + headers={"Authorization": "Bearer {}".format(profile.get("grafana_token"))}, json=payload, ) return response.json() @@ -554,7 +548,7 @@ def _dashboard_diff(_new_dashboard, _old_dashboard): def _stripped(d): """Strip falsey entries.""" ret = {} - for k, v in six.iteritems(d): + for k, v in d.items(): if v: ret[k] = v return ret diff --git a/salt/states/grafana_datasource.py b/salt/states/grafana_datasource.py index 06e9b08defc..e513802c890 100644 --- a/salt/states/grafana_datasource.py +++ b/salt/states/grafana_datasource.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage Grafana v2.0 data sources @@ -24,10 +23,8 @@ Manage Grafana v2.0 data sources - basic_auth_password: mypass - is_default: true """ -from __future__ import absolute_import, print_function, unicode_literals import requests -from salt.ext.six import string_types def __virtual__(): @@ -83,7 +80,7 @@ def present( is_default Default: False """ - if isinstance(profile, string_types): + if isinstance(profile, str): profile = __salt__["config.option"](profile) ret = {"name": name, "result": None, "comment": None, "changes": {}} @@ -113,19 +110,19 @@ def present( ret["result"] = True ret["changes"] = _diff(datasource, data) if ret["changes"]["new"] or ret["changes"]["old"]: - ret["comment"] = "Data source {0} updated".format(name) + ret["comment"] = "Data source {} updated".format(name) else: ret["changes"] = {} - ret["comment"] = "Data source {0} already up-to-date".format(name) + ret["comment"] = "Data source {} already up-to-date".format(name) else: requests.post( - "{0}/api/datasources".format(profile["grafana_url"]), + "{}/api/datasources".format(profile["grafana_url"]), data, headers=_get_headers(profile), timeout=profile.get("grafana_timeout", 3), ) ret["result"] = True - ret["comment"] = "New data source {0} added".format(name) + ret["comment"] = "New data source {} added".format(name) ret["changes"] = data return ret @@ -138,7 +135,7 @@ def absent(name, profile="grafana"): name Name of the data source to remove. """ - if isinstance(profile, string_types): + if isinstance(profile, str): profile = __salt__["config.option"](profile) ret = {"result": None, "comment": None, "changes": {}} @@ -146,7 +143,7 @@ def absent(name, profile="grafana"): if not datasource: ret["result"] = True - ret["comment"] = "Data source {0} already absent".format(name) + ret["comment"] = "Data source {} already absent".format(name) return ret requests.delete( @@ -156,18 +153,18 @@ def absent(name, profile="grafana"): ) ret["result"] = True - ret["comment"] = "Data source {0} was deleted".format(name) + ret["comment"] = "Data source {} was deleted".format(name) return ret def _get_url(profile, datasource_id): - return "{0}/api/datasources/{1}".format(profile["grafana_url"], datasource_id) + return "{}/api/datasources/{}".format(profile["grafana_url"], datasource_id) def _get_datasource(profile, name): response = requests.get( - "{0}/api/datasources".format(profile["grafana_url"]), + "{}/api/datasources".format(profile["grafana_url"]), headers=_get_headers(profile), timeout=profile.get("grafana_timeout", 3), ) @@ -181,7 +178,7 @@ def _get_datasource(profile, name): def _get_headers(profile): return { "Accept": "application/json", - "Authorization": "Bearer {0}".format(profile["grafana_token"]), + "Authorization": "Bearer {}".format(profile["grafana_token"]), } diff --git a/salt/states/helm.py b/salt/states/helm.py index 1f1aabf9642..f80a766a956 100644 --- a/salt/states/helm.py +++ b/salt/states/helm.py @@ -1,11 +1,5 @@ -# -*- coding: utf-8 -*- - -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - import logging -# Import Salt libs from salt.exceptions import CommandExecutionError log = logging.getLogger(__name__) diff --git a/salt/states/hg.py b/salt/states/hg.py index ecb4f7c7317..c9ac9769f1a 100644 --- a/salt/states/hg.py +++ b/salt/states/hg.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Interaction with Mercurial repositories ======================================= @@ -14,14 +13,11 @@ in ~/.ssh/known_hosts, and the remote host has this host's public key. - target: /tmp/example_repo """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import logging import os import shutil -# Import Salt libs import salt.utils.platform from salt.exceptions import CommandExecutionError from salt.states.git import _fail, _neutral_test @@ -37,7 +33,7 @@ def __virtual__(): """ if __salt__["cmd.has_exec"](HG_BINARY): return True - return (False, "Command {0} not found".format(HG_BINARY)) + return (False, "Command {} not found".format(HG_BINARY)) def latest( @@ -93,7 +89,7 @@ def latest( if not target: return _fail(ret, '"target option is required') - is_repository = os.path.isdir(target) and os.path.isdir("{0}/.hg".format(target)) + is_repository = os.path.isdir(target) and os.path.isdir("{}/.hg".format(target)) if is_repository: ret = _update_repo( @@ -108,7 +104,7 @@ def latest( log.debug('target %s is not found, "hg clone" is required', target) if __opts__["test"]: return _neutral_test( - ret, "Repository {0} is about to be cloned to {1}".format(name, target) + ret, "Repository {} is about to be cloned to {}".format(name, target) ) _clone_repo(ret, target, name, user, identity, rev, opts) return ret @@ -122,11 +118,11 @@ def _update_repo(ret, name, target, clean, user, identity, rev, opts, update_hea current_rev = __salt__["hg.revision"](target, user=user, rev=".") if not current_rev: - return _fail(ret, "Seems that {0} is not a valid hg repo".format(target)) + return _fail(ret, "Seems that {} is not a valid hg repo".format(target)) if __opts__["test"]: test_result = ( - "Repository {0} update is probably required (current " "revision is {1})" + "Repository {} update is probably required (current " "revision is {})" ).format(target, current_rev) return _neutral_test(ret, test_result) @@ -169,12 +165,12 @@ def _update_repo(ret, name, target, clean, user, identity, rev, opts, update_hea new_rev = __salt__["hg.revision"](cwd=target, user=user, rev=".") if current_rev != new_rev: - revision_text = "{0} => {1}".format(current_rev, new_rev) + revision_text = "{} => {}".format(current_rev, new_rev) log.info("Repository %s updated: %s", target, revision_text) - ret["comment"] = "Repository {0} updated.".format(target) + ret["comment"] = "Repository {} updated.".format(target) ret["changes"]["revision"] = revision_text elif "error:" in pull_out: - return _fail(ret, "An error was thrown by hg:\n{0}".format(pull_out)) + return _fail(ret, "An error was thrown by hg:\n{}".format(pull_out)) return ret @@ -218,7 +214,7 @@ def _clone_repo(ret, target, name, user, identity, rev, opts): return ret new_rev = __salt__["hg.revision"](cwd=target, user=user) - message = "Repository {0} cloned to {1}".format(name, target) + message = "Repository {} cloned to {}".format(name, target) log.info(message) ret["comment"] = message diff --git a/salt/states/icinga2.py b/salt/states/icinga2.py index 27d369bec19..8c1d2231de4 100644 --- a/salt/states/icinga2.py +++ b/salt/states/icinga2.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Icinga2 state ============= @@ -19,16 +18,11 @@ Its output may be stored in a file or in a grain. - output: "/tmp/query_id.txt" """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import os.path import salt.utils.files import salt.utils.stringutils - -# Import Salt libs -from salt.ext import six from salt.utils.icinga2 import get_certs_path @@ -69,7 +63,7 @@ def generate_ticket(name, output=None, grain=None, key=None, overwrite=True): if output == "grain": if grain and not key: if not overwrite and grain in __salt__["grains.ls"](): - ret["comment"] = "No execution needed. Grain {0} already set".format( + ret["comment"] = "No execution needed. Grain {} already set".format( grain ) return ret @@ -77,7 +71,7 @@ def generate_ticket(name, output=None, grain=None, key=None, overwrite=True): ret["result"] = None ret[ "comment" - ] = "Ticket generation would be executed, storing result in grain: {0}".format( + ] = "Ticket generation would be executed, storing result in grain: {}".format( grain ) return ret @@ -87,15 +81,15 @@ def generate_ticket(name, output=None, grain=None, key=None, overwrite=True): else: grain_value = {} if not overwrite and key in grain_value: - ret[ - "comment" - ] = "No execution needed. Grain {0}:{1} already set".format(grain, key) + ret["comment"] = "No execution needed. Grain {}:{} already set".format( + grain, key + ) return ret elif __opts__["test"]: ret["result"] = None ret[ "comment" - ] = "Ticket generation would be executed, storing result in grain: {0}:{1}".format( + ] = "Ticket generation would be executed, storing result in grain: {}:{}".format( grain, key ) return ret @@ -105,13 +99,13 @@ def generate_ticket(name, output=None, grain=None, key=None, overwrite=True): return ret elif output: if not overwrite and os.path.isfile(output): - ret["comment"] = "No execution needed. File {0} already set".format(output) + ret["comment"] = "No execution needed. File {} already set".format(output) return ret elif __opts__["test"]: ret["result"] = None ret[ "comment" - ] = "Ticket generation would be executed, storing result in file: {0}".format( + ] = "Ticket generation would be executed, storing result in file: {}".format( output ) return ret @@ -124,12 +118,12 @@ def generate_ticket(name, output=None, grain=None, key=None, overwrite=True): ticket_res = __salt__["icinga2.generate_ticket"](name) ticket = ticket_res["stdout"] if not ticket_res["retcode"]: - ret["comment"] = six.text_type(ticket) + ret["comment"] = str(ticket) if output == "grain": if grain and not key: __salt__["grains.setval"](grain, ticket) - ret["changes"]["ticket"] = "Executed. Output into grain: {0}".format(grain) + ret["changes"]["ticket"] = "Executed. Output into grain: {}".format(grain) elif grain: if grain in __salt__["grains.ls"](): grain_value = __salt__["grains.get"](grain) @@ -137,11 +131,11 @@ def generate_ticket(name, output=None, grain=None, key=None, overwrite=True): grain_value = {} grain_value[key] = ticket __salt__["grains.setval"](grain, grain_value) - ret["changes"]["ticket"] = "Executed. Output into grain: {0}:{1}".format( + ret["changes"]["ticket"] = "Executed. Output into grain: {}:{}".format( grain, key ) elif output: - ret["changes"]["ticket"] = "Executed. Output into {0}".format(output) + ret["changes"]["ticket"] = "Executed. Output into {}".format(output) with salt.utils.files.fopen(output, "w") as output_file: output_file.write(salt.utils.stringutils.to_str(ticket)) else: @@ -158,14 +152,14 @@ def generate_cert(name): The domain name for which this certificate and key will be generated """ ret = {"name": name, "changes": {}, "result": True, "comment": ""} - cert = "{0}{1}.crt".format(get_certs_path(), name) - key = "{0}{1}.key".format(get_certs_path(), name) + cert = "{}{}.crt".format(get_certs_path(), name) + key = "{}{}.key".format(get_certs_path(), name) # Checking if execution is needed. if os.path.isfile(cert) and os.path.isfile(key): ret[ "comment" - ] = "No execution needed. Cert: {0} and key: {1} already generated.".format( + ] = "No execution needed. Cert: {} and key: {} already generated.".format( cert, key ) return ret @@ -178,8 +172,8 @@ def generate_cert(name): cert_save = __salt__["icinga2.generate_cert"](name) if not cert_save["retcode"]: ret["comment"] = "Certificate and key generated" - ret["changes"]["cert"] = "Executed. Certificate saved: {0}".format(cert) - ret["changes"]["key"] = "Executed. Key saved: {0}".format(key) + ret["changes"]["cert"] = "Executed. Certificate saved: {}".format(cert) + ret["changes"]["key"] = "Executed. Key saved: {}".format(key) return ret @@ -194,11 +188,11 @@ def save_cert(name, master): Icinga2 master node for which this certificate will be saved """ ret = {"name": name, "changes": {}, "result": True, "comment": ""} - cert = "{0}trusted-master.crt".format(get_certs_path()) + cert = "{}trusted-master.crt".format(get_certs_path()) # Checking if execution is needed. if os.path.isfile(cert): - ret["comment"] = "No execution needed. Cert: {0} already saved.".format(cert) + ret["comment"] = "No execution needed. Cert: {} already saved.".format(cert) return ret if __opts__["test"]: ret["result"] = None @@ -209,7 +203,7 @@ def save_cert(name, master): cert_save = __salt__["icinga2.save_cert"](name, master) if not cert_save["retcode"]: ret["comment"] = "Certificate for icinga2 master saved" - ret["changes"]["cert"] = "Executed. Certificate saved: {0}".format(cert) + ret["changes"]["cert"] = "Executed. Certificate saved: {}".format(cert) return ret @@ -230,11 +224,11 @@ def request_cert(name, master, ticket, port="5665"): Icinga2 port, defaults to 5665 """ ret = {"name": name, "changes": {}, "result": True, "comment": ""} - cert = "{0}ca.crt".format(get_certs_path()) + cert = "{}ca.crt".format(get_certs_path()) # Checking if execution is needed. if os.path.isfile(cert): - ret["comment"] = "No execution needed. Cert: {0} already exists.".format(cert) + ret["comment"] = "No execution needed. Cert: {} already exists.".format(cert) return ret if __opts__["test"]: ret["result"] = None @@ -245,10 +239,10 @@ def request_cert(name, master, ticket, port="5665"): cert_request = __salt__["icinga2.request_cert"](name, master, ticket, port) if not cert_request["retcode"]: ret["comment"] = "Certificate request from icinga2 master executed" - ret["changes"]["cert"] = "Executed. Certificate requested: {0}".format(cert) + ret["changes"]["cert"] = "Executed. Certificate requested: {}".format(cert) return ret - ret["comment"] = "FAILED. Certificate requested failed with output: {0}".format( + ret["comment"] = "FAILED. Certificate requested failed with output: {}".format( cert_request["stdout"] ) ret["result"] = False @@ -269,8 +263,8 @@ def node_setup(name, master, ticket): Authentication ticket generated on icinga2 master """ ret = {"name": name, "changes": {}, "result": True, "comment": ""} - cert = "{0}{1}.crt.orig".format(get_certs_path(), name) - key = "{0}{1}.key.orig".format(get_certs_path(), name) + cert = "{}{}.crt.orig".format(get_certs_path(), name) + key = "{}{}.key.orig".format(get_certs_path(), name) # Checking if execution is needed. if os.path.isfile(cert) and os.path.isfile(cert): @@ -288,7 +282,7 @@ def node_setup(name, master, ticket): ret["changes"]["cert"] = "Node setup finished successfully." return ret - ret["comment"] = "FAILED. Node setup failed with outpu: {0}".format( + ret["comment"] = "FAILED. Node setup failed with outpu: {}".format( node_setup["stdout"] ) ret["result"] = False diff --git a/salt/states/ifttt.py b/salt/states/ifttt.py index db0ec900a04..f7378576783 100644 --- a/salt/states/ifttt.py +++ b/salt/states/ifttt.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Trigger an event in IFTTT ========================= @@ -24,9 +23,6 @@ The api key can be specified in the master or minion configuration like below: """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - def __virtual__(): """ @@ -72,7 +68,7 @@ def trigger_event(name, event, value1=None, value2=None, value3=None): ret = {"name": name, "changes": {}, "result": False, "comment": ""} if __opts__["test"]: - ret["comment"] = "The following trigger would be sent to IFTTT: {0}".format( + ret["comment"] = "The following trigger would be sent to IFTTT: {}".format( event ) ret["result"] = None @@ -84,8 +80,8 @@ def trigger_event(name, event, value1=None, value2=None, value3=None): if ret and ret["result"]: ret["result"] = True - ret["comment"] = "Triggered Event: {0}".format(name) + ret["comment"] = "Triggered Event: {}".format(name) else: - ret["comment"] = "Failed to trigger event: {0}".format(name) + ret["comment"] = "Failed to trigger event: {}".format(name) return ret diff --git a/salt/states/incron.py b/salt/states/incron.py index e71427d7516..6baad30808f 100644 --- a/salt/states/incron.py +++ b/salt/states/incron.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of incron, the inotify cron ============================================== @@ -41,8 +40,6 @@ then a new cron job will be added to the user's crontab. .. versionadded:: 0.17.0 """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import logging @@ -122,29 +119,29 @@ def present(name, path, mask, cmd, user="root"): status = _check_cron(user, path, mask, cmd) ret["result"] = None if status == "absent": - ret["comment"] = "Incron {0} is set to be added".format(name) + ret["comment"] = "Incron {} is set to be added".format(name) elif status == "present": ret["result"] = True - ret["comment"] = "Incron {0} already present".format(name) + ret["comment"] = "Incron {} already present".format(name) elif status == "update": - ret["comment"] = "Incron {0} is set to be updated".format(name) + ret["comment"] = "Incron {} is set to be updated".format(name) return ret data = __salt__["incron.set_job"](user=user, path=path, mask=mask, cmd=cmd) if data == "present": - ret["comment"] = "Incron {0} already present".format(name) + ret["comment"] = "Incron {} already present".format(name) return ret if data == "new": - ret["comment"] = "Incron {0} added to {1}'s incrontab".format(name, user) + ret["comment"] = "Incron {} added to {}'s incrontab".format(name, user) ret["changes"] = {user: name} return ret if data == "updated": - ret["comment"] = "Incron {0} updated".format(name) + ret["comment"] = "Incron {} updated".format(name) ret["changes"] = {user: name} return ret - ret["comment"] = "Incron {0} for user {1} failed to commit with error \n{2}".format( + ret["comment"] = "Incron {} for user {} failed to commit with error \n{}".format( name, user, data ) ret["result"] = False @@ -183,20 +180,20 @@ def absent(name, path, mask, cmd, user="root"): ret["result"] = None if status == "absent": ret["result"] = True - ret["comment"] = "Incron {0} is absent".format(name) + ret["comment"] = "Incron {} is absent".format(name) elif status == "present" or status == "update": - ret["comment"] = "Incron {0} is set to be removed".format(name) + ret["comment"] = "Incron {} is set to be removed".format(name) return ret data = __salt__["incron.rm_job"](user=user, path=path, mask=mask, cmd=cmd) if data == "absent": - ret["comment"] = "Incron {0} already absent".format(name) + ret["comment"] = "Incron {} already absent".format(name) return ret if data == "removed": - ret["comment"] = "Incron {0} removed from {1}'s crontab".format(name, user) + ret["comment"] = "Incron {} removed from {}'s crontab".format(name, user) ret["changes"] = {user: name} return ret - ret["comment"] = "Incron {0} for user {1} failed to commit with error {2}".format( + ret["comment"] = "Incron {} for user {} failed to commit with error {}".format( name, user, data ) ret["result"] = False diff --git a/salt/states/influxdb08_database.py b/salt/states/influxdb08_database.py index 063c44fcce0..fac790a0824 100644 --- a/salt/states/influxdb08_database.py +++ b/salt/states/influxdb08_database.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of Influxdb 0.8 databases ==================================== @@ -9,9 +8,6 @@ Management of Influxdb 0.8 databases """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - def __virtual__(): """ @@ -48,23 +44,21 @@ def present(name, user=None, password=None, host=None, port=None): if not __salt__["influxdb08.db_exists"](name, user, password, host, port): if __opts__["test"]: ret["result"] = None - ret["comment"] = "Database {0} is absent and needs to be created".format( + ret["comment"] = "Database {} is absent and needs to be created".format( name ) return ret if __salt__["influxdb08.db_create"](name, user, password, host, port): - ret["comment"] = "Database {0} has been created".format(name) + ret["comment"] = "Database {} has been created".format(name) ret["changes"][name] = "Present" return ret else: - ret["comment"] = "Failed to create database {0}".format(name) + ret["comment"] = "Failed to create database {}".format(name) ret["result"] = False return ret # fallback - ret["comment"] = "Database {0} is already present, so cannot be created".format( - name - ) + ret["comment"] = "Database {} is already present, so cannot be created".format(name) return ret @@ -94,19 +88,19 @@ def absent(name, user=None, password=None, host=None, port=None): if __salt__["influxdb08.db_exists"](name, user, password, host, port): if __opts__["test"]: ret["result"] = None - ret["comment"] = "Database {0} is present and needs to be removed".format( + ret["comment"] = "Database {} is present and needs to be removed".format( name ) return ret if __salt__["influxdb08.db_remove"](name, user, password, host, port): - ret["comment"] = "Database {0} has been removed".format(name) + ret["comment"] = "Database {} has been removed".format(name) ret["changes"][name] = "Absent" return ret else: - ret["comment"] = "Failed to remove database {0}".format(name) + ret["comment"] = "Failed to remove database {}".format(name) ret["result"] = False return ret # fallback - ret["comment"] = "Database {0} is not present, so it cannot be removed".format(name) + ret["comment"] = "Database {} is not present, so it cannot be removed".format(name) return ret diff --git a/salt/states/influxdb08_user.py b/salt/states/influxdb08_user.py index b29b8972c46..19865232692 100644 --- a/salt/states/influxdb08_user.py +++ b/salt/states/influxdb08_user.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of InfluxDB 0.8 users ================================ @@ -9,9 +8,6 @@ Management of InfluxDB 0.8 users """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - def __virtual__(): """ @@ -57,7 +53,7 @@ def present( database, user, password, host, port ): ret["result"] = False - ret["comment"] = "Database {0} does not exist".format(database) + ret["comment"] = "Database {} does not exist".format(database) return ret # check if user exists @@ -66,7 +62,7 @@ def present( ): if __opts__["test"]: ret["result"] = None - ret["comment"] = "User {0} is not present and needs to be created".format( + ret["comment"] = "User {} is not present and needs to be created".format( name ) return ret @@ -74,16 +70,16 @@ def present( if __salt__["influxdb08.user_create"]( name, passwd, database, user, password, host, port ): - ret["comment"] = "User {0} has been created".format(name) + ret["comment"] = "User {} has been created".format(name) ret["changes"][name] = "Present" return ret else: - ret["comment"] = "Failed to create user {0}".format(name) + ret["comment"] = "Failed to create user {}".format(name) ret["result"] = False return ret # fallback - ret["comment"] = "User {0} is already present".format(name) + ret["comment"] = "User {} is already present".format(name) return ret @@ -116,19 +112,19 @@ def absent(name, database=None, user=None, password=None, host=None, port=None): if __salt__["influxdb08.user_exists"](name, database, user, password, host, port): if __opts__["test"]: ret["result"] = None - ret["comment"] = "User {0} is present and needs to be removed".format(name) + ret["comment"] = "User {} is present and needs to be removed".format(name) return ret if __salt__["influxdb08.user_remove"]( name, database, user, password, host, port ): - ret["comment"] = "User {0} has been removed".format(name) + ret["comment"] = "User {} has been removed".format(name) ret["changes"][name] = "Absent" return ret else: - ret["comment"] = "Failed to remove user {0}".format(name) + ret["comment"] = "Failed to remove user {}".format(name) ret["result"] = False return ret # fallback - ret["comment"] = "User {0} is not present, so it cannot be removed".format(name) + ret["comment"] = "User {} is not present, so it cannot be removed".format(name) return ret diff --git a/salt/states/influxdb_continuous_query.py b/salt/states/influxdb_continuous_query.py index e3f13f42bfa..1eda81b71db 100644 --- a/salt/states/influxdb_continuous_query.py +++ b/salt/states/influxdb_continuous_query.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of Influxdb continuous queries ========================================= @@ -8,9 +7,6 @@ Management of Influxdb continuous queries (compatible with InfluxDB version 0.9+) """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - def __virtual__(): """ @@ -46,7 +42,7 @@ def present( "name": name, "changes": {}, "result": True, - "comment": "continuous query {0} is already present".format(name), + "comment": "continuous query {} is already present".format(name), } if not __salt__["influxdb.continuous_query_exists"]( @@ -54,16 +50,16 @@ def present( ): if __opts__["test"]: ret["result"] = None - ret["comment"] = " {0} is absent and will be created".format(name) + ret["comment"] = " {} is absent and will be created".format(name) return ret if __salt__["influxdb.create_continuous_query"]( database, name, query, resample_time, coverage_period ): - ret["comment"] = "continuous query {0} has been created".format(name) + ret["comment"] = "continuous query {} has been created".format(name) ret["changes"][name] = "Present" return ret else: - ret["comment"] = "Failed to create continuous query {0}".format(name) + ret["comment"] = "Failed to create continuous query {}".format(name) ret["result"] = False return ret @@ -84,22 +80,22 @@ def absent(name, database, **client_args): "name": name, "changes": {}, "result": True, - "comment": "continuous query {0} is not present".format(name), + "comment": "continuous query {} is not present".format(name), } if __salt__["influxdb.continuous_query_exists"](database, name, **client_args): if __opts__["test"]: ret["result"] = None ret["comment"] = ( - "continuous query {0} is present and needs to be removed" + "continuous query {} is present and needs to be removed" ).format(name) return ret if __salt__["influxdb.drop_continuous_query"](database, name, **client_args): - ret["comment"] = "continuous query {0} has been removed".format(name) + ret["comment"] = "continuous query {} has been removed".format(name) ret["changes"][name] = "Absent" return ret else: - ret["comment"] = "Failed to remove continuous query {0}".format(name) + ret["comment"] = "Failed to remove continuous query {}".format(name) ret["result"] = False return ret diff --git a/salt/states/influxdb_database.py b/salt/states/influxdb_database.py index fbaf46a7c8b..cfa2a1c9d47 100644 --- a/salt/states/influxdb_database.py +++ b/salt/states/influxdb_database.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of Influxdb databases ================================ @@ -6,9 +5,6 @@ Management of Influxdb databases (compatible with InfluxDB version 0.9+) """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - def __virtual__(): """ @@ -30,20 +26,20 @@ def present(name, **client_args): "name": name, "changes": {}, "result": True, - "comment": "Database {0} is already present".format(name), + "comment": "Database {} is already present".format(name), } if not __salt__["influxdb.db_exists"](name, **client_args): if __opts__["test"]: ret["result"] = None - ret["comment"] = "Database {0} is absent and will be created".format(name) + ret["comment"] = "Database {} is absent and will be created".format(name) return ret if __salt__["influxdb.create_db"](name, **client_args): - ret["comment"] = "Database {0} has been created".format(name) + ret["comment"] = "Database {} has been created".format(name) ret["changes"][name] = "Present" return ret else: - ret["comment"] = "Failed to create database {0}".format(name) + ret["comment"] = "Failed to create database {}".format(name) ret["result"] = False return ret @@ -61,22 +57,22 @@ def absent(name, **client_args): "name": name, "changes": {}, "result": True, - "comment": "Database {0} is not present".format(name), + "comment": "Database {} is not present".format(name), } if __salt__["influxdb.db_exists"](name, **client_args): if __opts__["test"]: ret["result"] = None - ret["comment"] = "Database {0} is present and needs to be removed".format( + ret["comment"] = "Database {} is present and needs to be removed".format( name ) return ret if __salt__["influxdb.drop_db"](name, **client_args): - ret["comment"] = "Database {0} has been removed".format(name) + ret["comment"] = "Database {} has been removed".format(name) ret["changes"][name] = "Absent" return ret else: - ret["comment"] = "Failed to remove database {0}".format(name) + ret["comment"] = "Failed to remove database {}".format(name) ret["result"] = False return ret diff --git a/salt/states/influxdb_retention_policy.py b/salt/states/influxdb_retention_policy.py index 6331babbd4f..3945ae574cf 100644 --- a/salt/states/influxdb_retention_policy.py +++ b/salt/states/influxdb_retention_policy.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of Influxdb retention policies ========================================= @@ -8,9 +7,6 @@ Management of Influxdb retention policies (compatible with InfluxDB version 0.9+) """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - def __virtual__(): """ @@ -63,7 +59,7 @@ def present(name, database, duration="7d", replication=1, default=False, **clien "name": name, "changes": {}, "result": True, - "comment": "retention policy {0} is already present".format(name), + "comment": "retention policy {} is already present".format(name), } if not __salt__["influxdb.retention_policy_exists"]( @@ -71,16 +67,16 @@ def present(name, database, duration="7d", replication=1, default=False, **clien ): if __opts__["test"]: ret["result"] = None - ret["comment"] = " {0} is absent and will be created".format(name) + ret["comment"] = " {} is absent and will be created".format(name) return ret if __salt__["influxdb.create_retention_policy"]( database, name, duration, replication, default, **client_args ): - ret["comment"] = "retention policy {0} has been created".format(name) + ret["comment"] = "retention policy {} has been created".format(name) ret["changes"][name] = "Present" return ret else: - ret["comment"] = "Failed to create retention policy {0}".format(name) + ret["comment"] = "Failed to create retention policy {}".format(name) ret["result"] = False return ret @@ -91,41 +87,35 @@ def present(name, database, duration="7d", replication=1, default=False, **clien update_policy = False if current_policy["duration"] != convert_duration(duration): update_policy = True - ret["changes"]["duration"] = "Retention changed from {0} to {1}.".format( + ret["changes"]["duration"] = "Retention changed from {} to {}.".format( current_policy["duration"], duration ) if current_policy["replicaN"] != replication: update_policy = True - ret["changes"][ - "replication" - ] = "Replication changed from {0} to {1}.".format( + ret["changes"]["replication"] = "Replication changed from {} to {}.".format( current_policy["replicaN"], replication ) if current_policy["default"] != default: update_policy = True - ret["changes"]["default"] = "Default changed from {0} to {1}.".format( + ret["changes"]["default"] = "Default changed from {} to {}.".format( current_policy["default"], default ) if update_policy: if __opts__["test"]: ret["result"] = None - ret["comment"] = " {0} is present and set to be changed".format(name) + ret["comment"] = " {} is present and set to be changed".format(name) return ret else: if __salt__["influxdb.alter_retention_policy"]( database, name, duration, replication, default, **client_args ): - ret["comment"] = "retention policy {0} has been changed".format( - name - ) + ret["comment"] = "retention policy {} has been changed".format(name) return ret else: - ret["comment"] = "Failed to update retention policy {0}".format( - name - ) + ret["comment"] = "Failed to update retention policy {}".format(name) ret["result"] = False return ret @@ -146,22 +136,22 @@ def absent(name, database, **client_args): "name": name, "changes": {}, "result": True, - "comment": "retention policy {0} is not present".format(name), + "comment": "retention policy {} is not present".format(name), } if __salt__["influxdb.retention_policy_exists"](database, name, **client_args): if __opts__["test"]: ret["result"] = None ret["comment"] = ( - "retention policy {0} is present and needs to be removed" + "retention policy {} is present and needs to be removed" ).format(name) return ret if __salt__["influxdb.drop_retention_policy"](database, name, **client_args): - ret["comment"] = "retention policy {0} has been removed".format(name) + ret["comment"] = "retention policy {} has been removed".format(name) ret["changes"][name] = "Absent" return ret else: - ret["comment"] = "Failed to remove retention policy {0}".format(name) + ret["comment"] = "Failed to remove retention policy {}".format(name) ret["result"] = False return ret diff --git a/salt/states/influxdb_user.py b/salt/states/influxdb_user.py index 59fa5d87432..506174d1618 100644 --- a/salt/states/influxdb_user.py +++ b/salt/states/influxdb_user.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of InfluxDB users ============================ @@ -6,9 +5,6 @@ Management of InfluxDB users (compatible with InfluxDB version 0.9+) """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - def __virtual__(): """ @@ -59,20 +55,20 @@ def present(name, passwd, admin=False, grants=None, **client_args): "name": name, "changes": {}, "result": True, - "comment": "User {0} is present and up to date".format(name), + "comment": "User {} is present and up to date".format(name), } if not __salt__["influxdb.user_exists"](name, **client_args): create = True if __opts__["test"]: - ret["comment"] = "User {0} will be created".format(name) + ret["comment"] = "User {} will be created".format(name) ret["result"] = None return ret else: if not __salt__["influxdb.create_user"]( name, passwd, admin=admin, **client_args ): - ret["comment"] = "Failed to create user {0}".format(name) + ret["comment"] = "Failed to create user {}".format(name) ret["result"] = False return ret else: @@ -91,7 +87,7 @@ def present(name, passwd, admin=False, grants=None, **client_args): ): ret[ "comment" - ] = "Failed to set admin privilege to " "user {0}".format(name) + ] = "Failed to set admin privilege to " "user {}".format(name) ret["result"] = False return ret ret["changes"]["Admin privileges"] = admin @@ -108,7 +104,7 @@ def present(name, passwd, admin=False, grants=None, **client_args): del db_privileges[database] if database not in db_privileges: ret["changes"][ - "Grant on database {0} to user {1}".format(database, name) + "Grant on database {} to user {}".format(database, name) ] = privilege if not __opts__["test"]: __salt__["influxdb.grant_privilege"]( @@ -117,20 +113,20 @@ def present(name, passwd, admin=False, grants=None, **client_args): if ret["changes"]: if create: - ret["comment"] = "Created user {0}".format(name) + ret["comment"] = "Created user {}".format(name) ret["changes"][name] = "User created" else: if __opts__["test"]: ret["result"] = None ret["comment"] = ( - "User {0} will be updated with the " + "User {} will be updated with the " "following changes:".format(name) ) for k, v in ret["changes"].items(): - ret["comment"] += "\n{0} => {1}".format(k, v) + ret["comment"] += "\n{} => {}".format(k, v) ret["changes"] = {} else: - ret["comment"] = "Updated user {0}".format(name) + ret["comment"] = "Updated user {}".format(name) return ret @@ -146,21 +142,21 @@ def absent(name, **client_args): "name": name, "changes": {}, "result": True, - "comment": "User {0} is not present".format(name), + "comment": "User {} is not present".format(name), } if __salt__["influxdb.user_exists"](name, **client_args): if __opts__["test"]: ret["result"] = None - ret["comment"] = "User {0} will be removed".format(name) + ret["comment"] = "User {} will be removed".format(name) return ret else: if __salt__["influxdb.remove_user"](name, **client_args): - ret["comment"] = "Removed user {0}".format(name) + ret["comment"] = "Removed user {}".format(name) ret["changes"][name] = "removed" return ret else: - ret["comment"] = "Failed to remove user {0}".format(name) + ret["comment"] = "Failed to remove user {}".format(name) ret["result"] = False return ret return ret diff --git a/salt/states/infoblox_a.py b/salt/states/infoblox_a.py index 22679f7353b..2a50d2d908b 100644 --- a/salt/states/infoblox_a.py +++ b/salt/states/infoblox_a.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Infoblox A record management. @@ -10,9 +9,6 @@ functions accept api_opts: api_password: [default to pillar value] """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - def present(name=None, ipv4addr=None, data=None, ensure_data=True, **api_opts): """ @@ -54,7 +50,7 @@ def present(name=None, ipv4addr=None, data=None, ensure_data=True, **api_opts): ret["result"] = False ret[ "comment" - ] = "** please update the name: {0} to equal the updated data name {1}".format( + ] = "** please update the name: {} to equal the updated data name {}".format( name, data["name"] ) return ret @@ -94,7 +90,7 @@ def present(name=None, ipv4addr=None, data=None, ensure_data=True, **api_opts): if __opts__["test"]: ret["result"] = None - ret["comment"] = "would attempt to create infoblox record {0}".format( + ret["comment"] = "would attempt to create infoblox record {}".format( data["name"] ) return ret diff --git a/salt/states/infoblox_cname.py b/salt/states/infoblox_cname.py index d099462ee2d..2605e35cbfc 100644 --- a/salt/states/infoblox_cname.py +++ b/salt/states/infoblox_cname.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Infoblox CNAME management. @@ -10,9 +9,6 @@ functions accept api_opts: api_password: [default to pillar value] """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - def present(name=None, data=None, ensure_data=True, **api_opts): """ @@ -63,7 +59,7 @@ def present(name=None, data=None, ensure_data=True, **api_opts): ret["result"] = False ret[ "comment" - ] = "** please update the name: {0} to equal the updated data name {1}".format( + ] = "** please update the name: {} to equal the updated data name {}".format( name, data["name"] ) return ret @@ -101,7 +97,7 @@ def present(name=None, data=None, ensure_data=True, **api_opts): if __opts__["test"]: ret["result"] = None - ret["comment"] = "would attempt to create infoblox record {0}".format( + ret["comment"] = "would attempt to create infoblox record {}".format( data["name"] ) return ret diff --git a/salt/states/infoblox_host_record.py b/salt/states/infoblox_host_record.py index 4700bfd2aa7..b038dc4c4af 100644 --- a/salt/states/infoblox_host_record.py +++ b/salt/states/infoblox_host_record.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Infoblox host record management. @@ -10,9 +9,6 @@ functions accept api_opts: api_password: [default to pillar value] """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - def present(name=None, data=None, ensure_data=True, **api_opts): """ @@ -59,7 +55,7 @@ def present(name=None, data=None, ensure_data=True, **api_opts): ret["result"] = False ret[ "comment" - ] = "please update the name: {0} to equal the updated data name {1}".format( + ] = "please update the name: {} to equal the updated data name {}".format( name, data["name"] ) return ret @@ -116,7 +112,7 @@ def present(name=None, data=None, ensure_data=True, **api_opts): if found_matches > 1: ret[ "comment" - ] = "infoblox record cant updated because ipaddress {0} matches multiple func:nextavailableip".format( + ] = "infoblox record cant updated because ipaddress {} matches multiple func:nextavailableip".format( ip ) ret["result"] = False @@ -134,7 +130,7 @@ def present(name=None, data=None, ensure_data=True, **api_opts): if __opts__["test"]: ret["result"] = None - ret["comment"] = "would attempt to create infoblox record {0}".format(name) + ret["comment"] = "would attempt to create infoblox record {}".format(name) return ret new_obj_ref = __salt__["infoblox.create_host"](data=data, **api_opts) diff --git a/salt/states/infoblox_range.py b/salt/states/infoblox_range.py index ac231a60f5a..6eb0d193ebd 100644 --- a/salt/states/infoblox_range.py +++ b/salt/states/infoblox_range.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Infoblox host record management. @@ -10,9 +9,6 @@ functions accept api_opts: api_password: [default to pillar value] """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - def present(name=None, start_addr=None, end_addr=None, data=None, **api_opts): """ @@ -136,7 +132,7 @@ def present(name=None, start_addr=None, end_addr=None, data=None, **api_opts): if __opts__["test"]: ret["result"] = None - ret["comment"] = "would attempt to create record {0}".format(name) + ret["comment"] = "would attempt to create record {}".format(name) return ret new_obj_ref = __salt__["infoblox.create_ipv4_range"](data, **api_opts) @@ -203,7 +199,7 @@ def absent(name=None, start_addr=None, end_addr=None, data=None, **api_opts): if __salt__["infoblox.delete_object"](objref=obj["_ref"]): ret["result"] = True ret["changes"] = { - "old": "Found {0} - {1}".format(start_addr, end_addr), + "old": "Found {} - {}".format(start_addr, end_addr), "new": "Removed", } return ret diff --git a/salt/states/jboss7.py b/salt/states/jboss7.py index f2e30b7c945..e3a4851b277 100644 --- a/salt/states/jboss7.py +++ b/salt/states/jboss7.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage JBoss 7 Application Server via CLI interface @@ -36,21 +35,15 @@ For the sake of brevity, examples for each state assume that jboss_config is con """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import logging import re import time import traceback -# Import Salt libs import salt.utils.dictdiffer as dictdiffer from salt.exceptions import CommandExecutionError -# Import 3rd-party libs -from salt.ext import six - log = logging.getLogger(__name__) @@ -189,7 +182,7 @@ def datasource_exists( ) else: raise CommandExecutionError( - "Unable to handle error: {0}".format(ds_result["failure-description"]) + "Unable to handle error: {}".format(ds_result["failure-description"]) ) if ret["result"]: @@ -257,7 +250,7 @@ def __get_ds_value(dct, key): elif dct[key] is None: return "undefined" else: - return six.text_type(dct[key]) + return str(dct[key]) def bindings_exist(name, jboss_config, bindings, profile=None): @@ -300,7 +293,7 @@ def bindings_exist(name, jboss_config, bindings, profile=None): has_changed = False for key in bindings: - value = six.text_type(bindings[key]) + value = str(bindings[key]) query_result = __salt__["jboss7.read_simple_binding"]( binding_name=key, jboss_config=jboss_config, profile=profile ) @@ -512,9 +505,9 @@ def __find_deployment(jboss_config, salt_source=None): if result is not None: success = False comment = ( - "More than one deployment matches regular expression: {0}. \n" + "More than one deployment matches regular expression: {}. \n" "For deployments from Salt file system deployments on JBoss are searched to find one that matches regular expression in 'undeploy' parameter.\n" - "Existing deployments: {1}".format( + "Existing deployments: {}".format( salt_source["undeploy"], ",".join(deployments) ) ) @@ -584,7 +577,7 @@ def __get_artifact(salt_source): except Exception as e: # pylint: disable=broad-except log.debug(traceback.format_exc()) - comment = "Unable to manage file: {0}".format(e) + comment = "Unable to manage file: {}".format(e) else: resolved_source = salt_source["target_file"] @@ -655,7 +648,7 @@ def reloaded(name, jboss_config, timeout=60, interval=5): ret["result"] = False ret[ "comment" - ] = "Could not reload the configuration. Timeout ({0} s) exceeded. ".format( + ] = "Could not reload the configuration. Timeout ({} s) exceeded. ".format( timeout ) if not status["success"]: @@ -664,7 +657,7 @@ def reloaded(name, jboss_config, timeout=60, interval=5): ) else: ret["comment"] = __append_comment( - ("Server is in {0} state".format(status["result"])), ret["comment"] + ("Server is in {} state".format(status["result"])), ret["comment"] ) else: ret["result"] = False @@ -677,10 +670,10 @@ def reloaded(name, jboss_config, timeout=60, interval=5): def __check_dict_contains(dct, dict_name, keys, comment="", result=True): for key in keys: - if key not in six.iterkeys(dct): + if key not in dct.keys(): result = False comment = __append_comment( - "Missing {0} in {1}".format(key, dict_name), comment + "Missing {} in {}".format(key, dict_name), comment ) return result, comment diff --git a/salt/states/jenkins.py b/salt/states/jenkins.py index c962b03de47..3b04caf3b0c 100644 --- a/salt/states/jenkins.py +++ b/salt/states/jenkins.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of Jenkins ===================== @@ -7,10 +6,9 @@ Management of Jenkins """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import difflib +import io import logging # Import XML parser @@ -20,10 +18,6 @@ import salt.utils.files import salt.utils.stringutils from salt.exceptions import CommandExecutionError -# Import Salt libs -from salt.ext import six -from salt.ext.six.moves import zip - log = logging.getLogger(__name__) @@ -62,12 +56,12 @@ def present(name, config=None, **kwargs): "name": name, "result": True, "changes": {}, - "comment": ["Job {0} is up to date.".format(name)], + "comment": ["Job {} is up to date.".format(name)], } if __salt__["jenkins.job_exists"](name): _current_job_config = __salt__["jenkins.get_job_config"](name) - buf = six.moves.StringIO(_current_job_config) + buf = io.StringIO(_current_job_config) oldXML = ET.fromstring(buf.read()) cached_source_path = __salt__["cp.cache_file"](config, __env__) @@ -85,7 +79,7 @@ def present(name, config=None, **kwargs): return _fail(ret, exc.strerror) else: ret["changes"] = "".join(diff) - ret["comment"].append("Job '{0}' updated.".format(name)) + ret["comment"].append("Job '{}' updated.".format(name)) else: cached_source_path = __salt__["cp.cache_file"](config, __env__) @@ -97,10 +91,10 @@ def present(name, config=None, **kwargs): except CommandExecutionError as exc: return _fail(ret, exc.strerror) - buf = six.moves.StringIO(new_config_xml) + buf = io.StringIO(new_config_xml) diff = difflib.unified_diff("", buf.readlines(), lineterm="") ret["changes"][name] = "".join(diff) - ret["comment"].append("Job '{0}' added.".format(name)) + ret["comment"].append("Job '{}' added.".format(name)) ret["comment"] = "\n".join(ret["comment"]) return ret @@ -121,7 +115,7 @@ def absent(name, **kwargs): except CommandExecutionError as exc: return _fail(ret, exc.strerror) else: - ret["comment"] = "Job '{0}' deleted.".format(name) + ret["comment"] = "Job '{}' deleted.".format(name) else: - ret["comment"] = "Job '{0}' already absent.".format(name) + ret["comment"] = "Job '{}' already absent.".format(name) return ret diff --git a/salt/states/kapacitor.py b/salt/states/kapacitor.py index e5577f112b6..f50321989e7 100644 --- a/salt/states/kapacitor.py +++ b/salt/states/kapacitor.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Kapacitor state module. @@ -16,10 +15,6 @@ Kapacitor state module. .. versionadded:: 2016.11.0 """ - - -from __future__ import absolute_import, print_function, unicode_literals - import difflib import salt.utils.files @@ -79,7 +74,7 @@ def task_present( if not dbrps: dbrps = [] if database and retention_policy: - dbrp = "{0}.{1}".format(database, retention_policy) + dbrp = "{}.{}".format(database, retention_policy) dbrps.append(dbrp) task_dbrps = [ {"db": dbrp[0], "rp": dbrp[1]} for dbrp in (dbrp.split(".") for dbrp in dbrps) diff --git a/salt/states/keystone.py b/salt/states/keystone.py index 47cf7b33c5e..eeab1ce27c4 100644 --- a/salt/states/keystone.py +++ b/salt/states/keystone.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of Keystone users ============================ @@ -66,7 +65,6 @@ Management of Keystone users - description: OpenStack Compute Service """ -from __future__ import absolute_import, print_function, unicode_literals def __virtual__(): @@ -164,7 +162,7 @@ def user_present( "name": name, "changes": {}, "result": True, - "comment": 'User "{0}" will be updated'.format(name), + "comment": 'User "{}" will be updated'.format(name), } _api_version(profile=profile, **connection_args) @@ -179,7 +177,7 @@ def user_present( ) if "Error" in tenantdata: ret["result"] = False - ret["comment"] = 'Tenant / project "{0}" does not exist'.format(tenant) + ret["comment"] = 'Tenant / project "{}" does not exist'.format(tenant) return ret tenant_id = tenantdata[tenant]["id"] else: @@ -215,47 +213,45 @@ def user_present( change_email or change_enabled or change_tenant or change_password ): ret["result"] = None - ret["comment"] = 'User "{0}" will be updated'.format(name) + ret["comment"] = 'User "{}" will be updated'.format(name) if change_email is True: ret["changes"]["Email"] = "Will be updated" if change_enabled is True: ret["changes"]["Enabled"] = "Will be True" if change_tenant is True: - ret["changes"]["Tenant"] = 'Will be added to "{0}" tenant'.format( - tenant - ) + ret["changes"]["Tenant"] = 'Will be added to "{}" tenant'.format(tenant) if change_password is True: ret["changes"]["Password"] = "Will be updated" return ret - ret["comment"] = 'User "{0}" is already present'.format(name) + ret["comment"] = 'User "{}" is already present'.format(name) if change_email: __salt__["keystone.user_update"]( name=name, email=email, profile=profile, **connection_args ) - ret["comment"] = 'User "{0}" has been updated'.format(name) + ret["comment"] = 'User "{}" has been updated'.format(name) ret["changes"]["Email"] = "Updated" if change_enabled: __salt__["keystone.user_update"]( name=name, enabled=enabled, profile=profile, **connection_args ) - ret["comment"] = 'User "{0}" has been updated'.format(name) - ret["changes"]["Enabled"] = "Now {0}".format(enabled) + ret["comment"] = 'User "{}" has been updated'.format(name) + ret["changes"]["Enabled"] = "Now {}".format(enabled) if change_tenant: __salt__["keystone.user_update"]( name=name, tenant=tenant, profile=profile, **connection_args ) - ret["comment"] = 'User "{0}" has been updated'.format(name) - ret["changes"]["Tenant"] = 'Added to "{0}" tenant'.format(tenant) + ret["comment"] = 'User "{}" has been updated'.format(name) + ret["changes"]["Tenant"] = 'Added to "{}" tenant'.format(tenant) if change_password: __salt__["keystone.user_password_update"]( name=name, password=password, profile=profile, **connection_args ) - ret["comment"] = 'User "{0}" has been updated'.format(name) + ret["comment"] = 'User "{}" has been updated'.format(name) ret["changes"]["Password"] = "Updated" if roles: @@ -269,9 +265,9 @@ def user_present( if role not in tenant_roles: if __opts__.get("test"): ret["result"] = None - ret[ - "comment" - ] = 'User roles "{0}" will been updated'.format(name) + ret["comment"] = 'User roles "{}" will been updated'.format( + name + ) return ret addargs = dict( { @@ -291,7 +287,7 @@ def user_present( for role in roles_to_remove: if __opts__.get("test"): ret["result"] = None - ret["comment"] = 'User roles "{0}" will been updated'.format( + ret["comment"] = 'User roles "{}" will been updated'.format( name ) return ret @@ -313,7 +309,7 @@ def user_present( # Create that user! if __opts__.get("test"): ret["result"] = None - ret["comment"] = 'Keystone user "{0}" will be added'.format(name) + ret["comment"] = 'Keystone user "{}" will be added'.format(name) ret["changes"]["User"] = "Will be created" return ret __salt__["keystone.user_create"]( @@ -335,7 +331,7 @@ def user_present( profile=profile, **connection_args ) - ret["comment"] = "Keystone user {0} has been added".format(name) + ret["comment"] = "Keystone user {} has been added".format(name) ret["changes"]["User"] = "Created" return ret @@ -352,7 +348,7 @@ def user_absent(name, profile=None, **connection_args): "name": name, "changes": {}, "result": True, - "comment": 'User "{0}" is already absent'.format(name), + "comment": 'User "{}" is already absent'.format(name), } # Check if user is present @@ -360,11 +356,11 @@ def user_absent(name, profile=None, **connection_args): if "Error" not in user: if __opts__.get("test"): ret["result"] = None - ret["comment"] = 'User "{0}" will be deleted'.format(name) + ret["comment"] = 'User "{}" will be deleted'.format(name) return ret # Delete that user! __salt__["keystone.user_delete"](name=name, profile=profile, **connection_args) - ret["comment"] = 'User "{0}" has been deleted'.format(name) + ret["comment"] = 'User "{}" has been deleted'.format(name) ret["changes"]["User"] = "Deleted" return ret @@ -389,7 +385,7 @@ def tenant_present( "name": name, "changes": {}, "result": True, - "comment": 'Tenant / project "{0}" already exists'.format(name), + "comment": 'Tenant / project "{}" already exists'.format(name), } _api_version(profile=profile, **connection_args) @@ -403,7 +399,7 @@ def tenant_present( if tenant[name].get("description", None) != description: if __opts__.get("test"): ret["result"] = None - ret["comment"] = 'Tenant / project "{0}" will be updated'.format(name) + ret["comment"] = 'Tenant / project "{}" will be updated'.format(name) ret["changes"]["Description"] = "Will be updated" return ret __salt__["keystone.tenant_update"]( @@ -413,13 +409,13 @@ def tenant_present( profile=profile, **connection_args ) - ret["comment"] = 'Tenant / project "{0}" has been updated'.format(name) + ret["comment"] = 'Tenant / project "{}" has been updated'.format(name) ret["changes"]["Description"] = "Updated" if tenant[name].get("enabled", None) != enabled: if __opts__.get("test"): ret["result"] = None - ret["comment"] = 'Tenant / project "{0}" will be updated'.format(name) - ret["changes"]["Enabled"] = "Will be {0}".format(enabled) + ret["comment"] = 'Tenant / project "{}" will be updated'.format(name) + ret["changes"]["Enabled"] = "Will be {}".format(enabled) return ret __salt__["keystone.tenant_update"]( name=name, @@ -428,12 +424,12 @@ def tenant_present( profile=profile, **connection_args ) - ret["comment"] = 'Tenant / project "{0}" has been updated'.format(name) - ret["changes"]["Enabled"] = "Now {0}".format(enabled) + ret["comment"] = 'Tenant / project "{}" has been updated'.format(name) + ret["changes"]["Enabled"] = "Now {}".format(enabled) else: if __opts__.get("test"): ret["result"] = None - ret["comment"] = 'Tenant / project "{0}" will be added'.format(name) + ret["comment"] = 'Tenant / project "{}" will be added'.format(name) ret["changes"]["Tenant"] = "Will be created" return ret # Create tenant @@ -456,7 +452,7 @@ def tenant_present( ) ret["changes"]["Tenant"] = "Created" if created is True else "Failed" ret["result"] = created - ret["comment"] = 'Tenant / project "{0}" has been added'.format(name) + ret["comment"] = 'Tenant / project "{}" has been added'.format(name) return ret @@ -471,7 +467,7 @@ def tenant_absent(name, profile=None, **connection_args): "name": name, "changes": {}, "result": True, - "comment": 'Tenant / project "{0}" is already absent'.format(name), + "comment": 'Tenant / project "{}" is already absent'.format(name), } # Check if tenant is present @@ -481,13 +477,13 @@ def tenant_absent(name, profile=None, **connection_args): if "Error" not in tenant: if __opts__.get("test"): ret["result"] = None - ret["comment"] = 'Tenant / project "{0}" will be deleted'.format(name) + ret["comment"] = 'Tenant / project "{}" will be deleted'.format(name) return ret # Delete tenant __salt__["keystone.tenant_delete"]( name=name, profile=profile, **connection_args ) - ret["comment"] = 'Tenant / project "{0}" has been deleted'.format(name) + ret["comment"] = 'Tenant / project "{}" has been deleted'.format(name) ret["changes"]["Tenant/Project"] = "Deleted" return ret @@ -562,7 +558,7 @@ def role_present(name, profile=None, **connection_args): "name": name, "changes": {}, "result": True, - "comment": 'Role "{0}" already exists'.format(name), + "comment": 'Role "{}" already exists'.format(name), } # Check if role is already present @@ -573,11 +569,11 @@ def role_present(name, profile=None, **connection_args): else: if __opts__.get("test"): ret["result"] = None - ret["comment"] = 'Role "{0}" will be added'.format(name) + ret["comment"] = 'Role "{}" will be added'.format(name) return ret # Create role __salt__["keystone.role_create"](name, profile=profile, **connection_args) - ret["comment"] = 'Role "{0}" has been added'.format(name) + ret["comment"] = 'Role "{}" has been added'.format(name) ret["changes"]["Role"] = "Created" return ret @@ -593,7 +589,7 @@ def role_absent(name, profile=None, **connection_args): "name": name, "changes": {}, "result": True, - "comment": 'Role "{0}" is already absent'.format(name), + "comment": 'Role "{}" is already absent'.format(name), } # Check if role is present @@ -601,11 +597,11 @@ def role_absent(name, profile=None, **connection_args): if "Error" not in role: if __opts__.get("test"): ret["result"] = None - ret["comment"] = 'Role "{0}" will be deleted'.format(name) + ret["comment"] = 'Role "{}" will be deleted'.format(name) return ret # Delete role __salt__["keystone.role_delete"](name=name, profile=profile, **connection_args) - ret["comment"] = 'Role "{0}" has been deleted'.format(name) + ret["comment"] = 'Role "{}" has been deleted'.format(name) ret["changes"]["Role"] = "Deleted" return ret @@ -630,7 +626,7 @@ def service_present( "name": name, "changes": {}, "result": True, - "comment": 'Service "{0}" already exists'.format(name), + "comment": 'Service "{}" already exists'.format(name), } # Check if service is already present @@ -643,13 +639,13 @@ def service_present( else: if __opts__.get("test"): ret["result"] = None - ret["comment"] = 'Service "{0}" will be added'.format(name) + ret["comment"] = 'Service "{}" will be added'.format(name) return ret # Create service __salt__["keystone.service_create"]( name, service_type, description, profile=profile, **connection_args ) - ret["comment"] = 'Service "{0}" has been added'.format(name) + ret["comment"] = 'Service "{}" has been added'.format(name) ret["changes"]["Service"] = "Created" return ret @@ -666,7 +662,7 @@ def service_absent(name, profile=None, **connection_args): "name": name, "changes": {}, "result": True, - "comment": 'Service "{0}" is already absent'.format(name), + "comment": 'Service "{}" is already absent'.format(name), } # Check if service is present @@ -676,13 +672,13 @@ def service_absent(name, profile=None, **connection_args): if "Error" not in role: if __opts__.get("test"): ret["result"] = None - ret["comment"] = 'Service "{0}" will be deleted'.format(name) + ret["comment"] = 'Service "{}" will be deleted'.format(name) return ret # Delete service __salt__["keystone.service_delete"]( name=name, profile=profile, **connection_args ) - ret["comment"] = 'Service "{0}" has been deleted'.format(name) + ret["comment"] = 'Service "{}" has been deleted'.format(name) ret["changes"]["Service"] = "Deleted" return ret @@ -766,7 +762,7 @@ def endpoint_present( if endpoint.get("url", None) != url: ret["comment"] = _changes( - 'URL changes from "{0}" to "{1}"'.format( + 'URL changes from "{}" to "{}"'.format( endpoint.get("url", None), url ) ) @@ -774,7 +770,7 @@ def endpoint_present( if endpoint.get("interface", None) != interface: ret["comment"] = _changes( - 'Interface changes from "{0}" to "{1}"'.format( + 'Interface changes from "{}" to "{}"'.format( endpoint.get("interface", None), interface ) ) @@ -783,7 +779,7 @@ def endpoint_present( if __opts__.get("test") and (change_url or change_interface): ret["result"] = None ret["changes"]["Endpoint"] = "Will be updated" - ret["comment"] += 'Endpoint for service "{0}" will be updated'.format( + ret["comment"] += 'Endpoint for service "{}" will be updated'.format( name ) return ret @@ -803,7 +799,7 @@ def endpoint_present( change_publicurl = True ret["comment"] = _changes( - 'Public URL changes from "{0}" to "{1}"'.format( + 'Public URL changes from "{}" to "{}"'.format( endpoint.get("publicurl", None), publicurl ) ) @@ -811,7 +807,7 @@ def endpoint_present( if endpoint.get("adminurl", None) != adminurl: change_adminurl = True ret["comment"] = _changes( - 'Admin URL changes from "{0}" to "{1}"'.format( + 'Admin URL changes from "{}" to "{}"'.format( endpoint.get("adminurl", None), adminurl ) ) @@ -819,7 +815,7 @@ def endpoint_present( if endpoint.get("internalurl", None) != internalurl: change_internalurl = True ret["comment"] = _changes( - 'Internal URL changes from "{0}" to "{1}"'.format( + 'Internal URL changes from "{}" to "{}"'.format( endpoint.get("internalurl", None), internalurl ) ) @@ -828,7 +824,7 @@ def endpoint_present( change_publicurl or change_adminurl or change_internalurl ): ret["result"] = None - ret["comment"] += 'Endpoint for service "{0}" will be updated'.format( + ret["comment"] += 'Endpoint for service "{}" will be updated'.format( name ) ret["changes"]["Endpoint"] = "Will be updated" @@ -848,20 +844,20 @@ def endpoint_present( name, region, profile=profile, interface=interface, **connection_args ) _create_endpoint() - ret["comment"] += 'Endpoint for service "{0}" has been updated'.format(name) + ret["comment"] += 'Endpoint for service "{}" has been updated'.format(name) else: # Add new endpoint if __opts__.get("test"): ret["result"] = None ret["changes"]["Endpoint"] = "Will be created" - ret["comment"] = 'Endpoint for service "{0}" will be added'.format(name) + ret["comment"] = 'Endpoint for service "{}" will be added'.format(name) return ret _create_endpoint() - ret["comment"] = 'Endpoint for service "{0}" has been added'.format(name) + ret["comment"] = 'Endpoint for service "{}" has been added'.format(name) if ret["comment"] == "": # => no changes - ret["comment"] = 'Endpoint for service "{0}" already exists'.format(name) + ret["comment"] = 'Endpoint for service "{}" already exists'.format(name) return ret @@ -883,9 +879,9 @@ def endpoint_absent(name, region=None, profile=None, interface=None, **connectio "name": name, "changes": {}, "result": True, - "comment": 'Endpoint for service "{0}"{1} is already absent'.format( + "comment": 'Endpoint for service "{}"{} is already absent'.format( name, - ', interface "{0}",'.format(interface) if interface is not None else "", + ', interface "{}",'.format(interface) if interface is not None else "", ), } @@ -898,15 +894,15 @@ def endpoint_absent(name, region=None, profile=None, interface=None, **connectio else: if __opts__.get("test"): ret["result"] = None - ret["comment"] = 'Endpoint for service "{0}" will be deleted'.format(name) + ret["comment"] = 'Endpoint for service "{}" will be deleted'.format(name) return ret # Delete service __salt__["keystone.endpoint_delete"]( name, region, profile=profile, interface=interface, **connection_args ) - ret["comment"] = 'Endpoint for service "{0}"{1} has been deleted'.format( + ret["comment"] = 'Endpoint for service "{}"{} has been deleted'.format( name, - ', interface "{0}",'.format(interface) if interface is not None else "", + ', interface "{}",'.format(interface) if interface is not None else "", ) ret["changes"]["endpoint"] = "Deleted" return ret diff --git a/salt/states/keystone_domain.py b/salt/states/keystone_domain.py index c4a6ae93158..7f51084034d 100644 --- a/salt/states/keystone_domain.py +++ b/salt/states/keystone_domain.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of OpenStack Keystone Domains ======================================== @@ -27,7 +26,6 @@ Example States - name: domain1 """ -from __future__ import absolute_import, print_function, unicode_literals __virtualname__ = "keystone_domain" diff --git a/salt/states/keystone_endpoint.py b/salt/states/keystone_endpoint.py index 01a93f7b96d..8640a6cfa59 100644 --- a/salt/states/keystone_endpoint.py +++ b/salt/states/keystone_endpoint.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of OpenStack Keystone Endpoints ========================================== @@ -37,7 +36,6 @@ Example States - service_name: glance """ -from __future__ import absolute_import, print_function, unicode_literals __virtualname__ = "keystone_endpoint" diff --git a/salt/states/keystone_group.py b/salt/states/keystone_group.py index 375b5e159e0..182807bf9fa 100644 --- a/salt/states/keystone_group.py +++ b/salt/states/keystone_group.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of OpenStack Keystone Groups ======================================= @@ -27,7 +26,6 @@ Example States - description: 'my group' """ -from __future__ import absolute_import, print_function, unicode_literals __virtualname__ = "keystone_group" diff --git a/salt/states/keystone_project.py b/salt/states/keystone_project.py index 98fa36adaca..1552954f889 100644 --- a/salt/states/keystone_project.py +++ b/salt/states/keystone_project.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of OpenStack Keystone Projects ========================================= @@ -28,7 +27,6 @@ Example States - description: 'my project' """ -from __future__ import absolute_import, print_function, unicode_literals __virtualname__ = "keystone_project" diff --git a/salt/states/keystone_role.py b/salt/states/keystone_role.py index 9afd0ec7a55..9b5db2c9854 100644 --- a/salt/states/keystone_role.py +++ b/salt/states/keystone_role.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of OpenStack Keystone Roles ====================================== @@ -26,7 +25,6 @@ Example States - description: 'my group' """ -from __future__ import absolute_import, print_function, unicode_literals __virtualname__ = "keystone_role" diff --git a/salt/states/keystone_role_grant.py b/salt/states/keystone_role_grant.py index ad24e86289a..507b32e096b 100644 --- a/salt/states/keystone_role_grant.py +++ b/salt/states/keystone_role_grant.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of OpenStack Keystone Role Grants ============================================ @@ -27,7 +26,6 @@ Example States - description: 'my group' """ -from __future__ import absolute_import, print_function, unicode_literals __virtualname__ = "keystone_role_grant" diff --git a/salt/states/keystone_service.py b/salt/states/keystone_service.py index 58b47fbd695..1f6227c0d6b 100644 --- a/salt/states/keystone_service.py +++ b/salt/states/keystone_service.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of OpenStack Keystone Services ========================================= @@ -29,7 +28,6 @@ Example States - description: 'OpenStack Image' """ -from __future__ import absolute_import, print_function, unicode_literals __virtualname__ = "keystone_service" diff --git a/salt/states/keystone_user.py b/salt/states/keystone_user.py index 93a97f16d19..7c246ef0cf4 100644 --- a/salt/states/keystone_user.py +++ b/salt/states/keystone_user.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of OpenStack Keystone Users ====================================== @@ -30,7 +29,6 @@ Example States - description: 'my user' """ -from __future__ import absolute_import, print_function, unicode_literals __virtualname__ = "keystone_user" diff --git a/salt/states/keystore.py b/salt/states/keystore.py index 61cc9a7ec60..28cfc6f547a 100644 --- a/salt/states/keystore.py +++ b/salt/states/keystore.py @@ -1,10 +1,7 @@ -# -*- coding: utf-8 -*- """ State management of a java keystore """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import logging import os @@ -24,7 +21,7 @@ def __virtual__(): return ( False, ( - "Cannot load the {0} state module: " + "Cannot load the {} state module: " "keystore execution module not found".format(__virtualname__) ), ) @@ -112,11 +109,11 @@ def managed(name, passphrase, entries, force_remove=False): if __opts__["test"]: ret["result"] = None if existing_entry: - ret["comment"] += "Alias {0} would have been updated\n".format( + ret["comment"] += "Alias {} would have been updated\n".format( entry["alias"] ) else: - ret["comment"] += "Alias {0} would have been added\n".format( + ret["comment"] += "Alias {} would have been added\n".format( entry["alias"] ) else: @@ -133,7 +130,7 @@ def managed(name, passphrase, entries, force_remove=False): ) if result: ret["changes"][entry["alias"]] = "Updated" - ret["comment"] += "Alias {0} updated.\n".format(entry["alias"]) + ret["comment"] += "Alias {} updated.\n".format(entry["alias"]) else: result = __salt__["keystore.add"]( entry["alias"], @@ -144,7 +141,7 @@ def managed(name, passphrase, entries, force_remove=False): ) if result: ret["changes"][entry["alias"]] = "Added" - ret["comment"] += "Alias {0} added.\n".format(entry["alias"]) + ret["comment"] += "Alias {} added.\n".format(entry["alias"]) if force_remove: # Determine which aliases need to be removed @@ -152,12 +149,12 @@ def managed(name, passphrase, entries, force_remove=False): log.debug("Will remove: %s", remove_list) for alias_name in remove_list: if __opts__["test"]: - ret["comment"] += "Alias {0} would have been removed".format(alias_name) + ret["comment"] += "Alias {} would have been removed".format(alias_name) ret["result"] = None else: __salt__["keystore.remove"](alias_name, name, passphrase) ret["changes"][alias_name] = "Removed" - ret["comment"] += "Alias {0} removed.\n".format(alias_name) + ret["comment"] += "Alias {} removed.\n".format(alias_name) if not ret["changes"] and not ret["comment"]: ret["comment"] = "No changes made.\n" diff --git a/salt/states/kmod.py b/salt/states/kmod.py index 4f684e407cf..a20c3fbf45c 100644 --- a/salt/states/kmod.py +++ b/salt/states/kmod.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Loading and unloading of kernel modules ======================================= @@ -30,7 +29,6 @@ Multiple modules can be specified for both kmod.present and kmod.absent. - snd_timer - snd """ -from __future__ import absolute_import, print_function, unicode_literals def __virtual__(): @@ -84,10 +82,10 @@ def present(name, persist=False, mods=None): # Intersection of loaded and proposed modules already_loaded = list(set(loaded_mods) & set(mods)) if len(already_loaded) == 1: - comment = "Kernel module {0} is already present".format(already_loaded[0]) + comment = "Kernel module {} is already present".format(already_loaded[0]) _append_comment(ret, comment) elif len(already_loaded) > 1: - comment = "Kernel modules {0} are already present".format( + comment = "Kernel modules {} are already present".format( ", ".join(already_loaded) ) _append_comment(ret, comment) @@ -103,9 +101,9 @@ def present(name, persist=False, mods=None): if ret["comment"]: ret["comment"] += "\n" if len(not_loaded) == 1: - comment = "Kernel module {0} is set to be loaded".format(not_loaded[0]) + comment = "Kernel module {} is set to be loaded".format(not_loaded[0]) else: - comment = "Kernel modules {0} are set to be loaded".format( + comment = "Kernel modules {} are set to be loaded".format( ", ".join(not_loaded) ) _append_comment(ret, comment) @@ -115,11 +113,9 @@ def present(name, persist=False, mods=None): unavailable = list(set(not_loaded) - set(__salt__["kmod.available"]())) if unavailable: if len(unavailable) == 1: - comment = "Kernel module {0} is unavailable".format(unavailable[0]) + comment = "Kernel module {} is unavailable".format(unavailable[0]) else: - comment = "Kernel modules {0} are unavailable".format( - ", ".join(unavailable) - ) + comment = "Kernel modules {} are unavailable".format(", ".join(unavailable)) _append_comment(ret, comment) ret["result"] = False @@ -148,24 +144,22 @@ def present(name, persist=False, mods=None): # Update comment with results if len(loaded["yes"]) == 1: - _append_comment(ret, "Loaded kernel module {0}".format(loaded["yes"][0])) + _append_comment(ret, "Loaded kernel module {}".format(loaded["yes"][0])) elif len(loaded["yes"]) > 1: _append_comment( - ret, "Loaded kernel modules {0}".format(", ".join(loaded["yes"])) + ret, "Loaded kernel modules {}".format(", ".join(loaded["yes"])) ) if len(loaded["no"]) == 1: - _append_comment(ret, "Failed to load kernel module {0}".format(loaded["no"][0])) + _append_comment(ret, "Failed to load kernel module {}".format(loaded["no"][0])) if len(loaded["no"]) > 1: _append_comment( - ret, "Failed to load kernel modules {0}".format(", ".join(loaded["no"])) + ret, "Failed to load kernel modules {}".format(", ".join(loaded["no"])) ) if loaded["failed"]: for mod, msg in loaded["failed"]: - _append_comment( - ret, "Failed to load kernel module {0}: {1}".format(mod, msg) - ) + _append_comment(ret, "Failed to load kernel module {}: {}".format(mod, msg)) return ret @@ -207,12 +201,12 @@ def absent(name, persist=False, comment=True, mods=None): ret["result"] = None if len(to_unload) == 1: _append_comment( - ret, "Kernel module {0} is set to be removed".format(to_unload[0]) + ret, "Kernel module {} is set to be removed".format(to_unload[0]) ) elif len(to_unload) > 1: _append_comment( ret, - "Kernel modules {0} are set to be removed".format( + "Kernel modules {} are set to be removed".format( ", ".join(to_unload) ), ) @@ -236,35 +230,35 @@ def absent(name, persist=False, comment=True, mods=None): # Update comment with results if len(unloaded["yes"]) == 1: - _append_comment(ret, "Removed kernel module {0}".format(unloaded["yes"][0])) + _append_comment(ret, "Removed kernel module {}".format(unloaded["yes"][0])) elif len(unloaded["yes"]) > 1: _append_comment( - ret, "Removed kernel modules {0}".format(", ".join(unloaded["yes"])) + ret, "Removed kernel modules {}".format(", ".join(unloaded["yes"])) ) if len(unloaded["no"]) == 1: _append_comment( - ret, "Failed to remove kernel module {0}".format(unloaded["no"][0]) + ret, "Failed to remove kernel module {}".format(unloaded["no"][0]) ) if len(unloaded["no"]) > 1: _append_comment( ret, - "Failed to remove kernel modules {0}".format(", ".join(unloaded["no"])), + "Failed to remove kernel modules {}".format(", ".join(unloaded["no"])), ) if unloaded["failed"]: for mod, msg in unloaded["failed"]: _append_comment( - ret, "Failed to remove kernel module {0}: {1}".format(mod, msg) + ret, "Failed to remove kernel module {}: {}".format(mod, msg) ) return ret else: if len(mods) == 1: - ret["comment"] = "Kernel module {0} is already removed".format(mods[0]) + ret["comment"] = "Kernel module {} is already removed".format(mods[0]) else: - ret["comment"] = "Kernel modules {0} are already removed".format( + ret["comment"] = "Kernel modules {} are already removed".format( ", ".join(mods) ) diff --git a/salt/states/layman.py b/salt/states/layman.py index b67519b07a5..00d65c458be 100644 --- a/salt/states/layman.py +++ b/salt/states/layman.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of Gentoo Overlays using layman ========================================== @@ -10,8 +9,6 @@ A state module to manage Gentoo package overlays via layman sunrise: layman.present """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals def __virtual__(): @@ -34,15 +31,15 @@ def present(name): # Overlay already present if name in __salt__["layman.list_local"](): - ret["comment"] = "Overlay {0} already present".format(name) + ret["comment"] = "Overlay {} already present".format(name) elif __opts__["test"]: - ret["comment"] = "Overlay {0} is set to be added".format(name) + ret["comment"] = "Overlay {} is set to be added".format(name) ret["result"] = None return ret else: # Does the overlay exist? if name not in __salt__["layman.list_all"](): - ret["comment"] = "Overlay {0} not found".format(name) + ret["comment"] = "Overlay {} not found".format(name) ret["result"] = False else: # Attempt to add the overlay @@ -50,12 +47,12 @@ def present(name): # The overlay failed to add if len(changes) < 1: - ret["comment"] = "Overlay {0} failed to add".format(name) + ret["comment"] = "Overlay {} failed to add".format(name) ret["result"] = False # Success else: ret["changes"]["added"] = changes - ret["comment"] = "Overlay {0} added.".format(name) + ret["comment"] = "Overlay {} added.".format(name) return ret @@ -71,9 +68,9 @@ def absent(name): # Overlay is already absent if name not in __salt__["layman.list_local"](): - ret["comment"] = "Overlay {0} already absent".format(name) + ret["comment"] = "Overlay {} already absent".format(name) elif __opts__["test"]: - ret["comment"] = "Overlay {0} is set to be deleted".format(name) + ret["comment"] = "Overlay {} is set to be deleted".format(name) ret["result"] = None return ret else: @@ -82,11 +79,11 @@ def absent(name): # The overlay failed to delete if len(changes) < 1: - ret["comment"] = "Overlay {0} failed to delete".format(name) + ret["comment"] = "Overlay {} failed to delete".format(name) ret["result"] = False # Success else: ret["changes"]["deleted"] = changes - ret["comment"] = "Overlay {0} deleted.".format(name) + ret["comment"] = "Overlay {} deleted.".format(name) return ret diff --git a/salt/states/locale.py b/salt/states/locale.py index 6f9bd6a8c7d..23a8c8684f7 100644 --- a/salt/states/locale.py +++ b/salt/states/locale.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of languages/locales =============================== @@ -18,10 +17,7 @@ Manage the available locales and the system default: - locale: us_locale """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals -# Import salt libs from salt.exceptions import CommandExecutionError @@ -45,23 +41,23 @@ def system(name): try: if __salt__["locale.get_locale"]() == name: ret["result"] = True - ret["comment"] = "System locale {0} already set".format(name) + ret["comment"] = "System locale {} already set".format(name) return ret if __opts__["test"]: - ret["comment"] = "System locale {0} needs to be set".format(name) + ret["comment"] = "System locale {} needs to be set".format(name) return ret if __salt__["locale.set_locale"](name): ret["changes"] = {"locale": name} ret["result"] = True - ret["comment"] = "Set system locale {0}".format(name) + ret["comment"] = "Set system locale {}".format(name) return ret else: ret["result"] = False - ret["comment"] = "Failed to set system locale to {0}".format(name) + ret["comment"] = "Failed to set system locale to {}".format(name) return ret except CommandExecutionError as err: ret["result"] = False - ret["comment"] = "Failed to set system locale: {0}".format(err) + ret["comment"] = "Failed to set system locale: {}".format(err) return ret @@ -78,17 +74,17 @@ def present(name): ret = {"name": name, "changes": {}, "result": None, "comment": ""} if __salt__["locale.avail"](name): ret["result"] = True - ret["comment"] = "Locale {0} is already present".format(name) + ret["comment"] = "Locale {} is already present".format(name) return ret if __opts__["test"]: - ret["comment"] = "Locale {0} needs to be generated".format(name) + ret["comment"] = "Locale {} needs to be generated".format(name) return ret if __salt__["locale.gen_locale"](name): ret["changes"] = {"locale": name} ret["result"] = True - ret["comment"] = "Generated locale {0}".format(name) + ret["comment"] = "Generated locale {}".format(name) return ret else: ret["result"] = False - ret["comment"] = "Failed to generate locale {0}".format(name) + ret["comment"] = "Failed to generate locale {}".format(name) return ret diff --git a/salt/states/lvs_server.py b/salt/states/lvs_server.py index a25958b65e8..ccdf9dcb6cc 100644 --- a/salt/states/lvs_server.py +++ b/salt/states/lvs_server.py @@ -1,12 +1,8 @@ -# -*- coding: utf-8 -*- """ Management of LVS (Linux Virtual Server) Real Server ==================================================== """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - def __virtual__(): """ @@ -74,7 +70,7 @@ def present( weight=weight, ) if server_rule_check is True: - ret["comment"] = "LVS Server {0} in service {1}({2}) is present".format( + ret["comment"] = "LVS Server {} in service {}({}) is present".format( name, service_address, protocol ) return ret @@ -83,7 +79,7 @@ def present( ret["result"] = None ret[ "comment" - ] = "LVS Server {0} in service {1}({2}) is present but some options should update".format( + ] = "LVS Server {} in service {}({}) is present but some options should update".format( name, service_address, protocol ) return ret @@ -98,7 +94,7 @@ def present( if server_edit is True: ret[ "comment" - ] = "LVS Server {0} in service {1}({2}) has been updated".format( + ] = "LVS Server {} in service {}({}) has been updated".format( name, service_address, protocol ) ret["changes"][name] = "Update" @@ -107,7 +103,7 @@ def present( ret["result"] = False ret[ "comment" - ] = "LVS Server {0} in service {1}({2}) update failed({3})".format( + ] = "LVS Server {} in service {}({}) update failed({})".format( name, service_address, protocol, server_edit ) return ret @@ -115,7 +111,7 @@ def present( if __opts__["test"]: ret[ "comment" - ] = "LVS Server {0} in service {1}({2}) is not present and needs to be created".format( + ] = "LVS Server {} in service {}({}) is not present and needs to be created".format( name, service_address, protocol ) ret["result"] = None @@ -131,7 +127,7 @@ def present( if server_add is True: ret[ "comment" - ] = "LVS Server {0} in service {1}({2}) has been created".format( + ] = "LVS Server {} in service {}({}) has been created".format( name, service_address, protocol ) ret["changes"][name] = "Present" @@ -139,7 +135,7 @@ def present( else: ret[ "comment" - ] = "LVS Service {0} in service {1}({2}) create failed({3})".format( + ] = "LVS Service {} in service {}({}) create failed({})".format( name, service_address, protocol, server_add ) ret["result"] = False @@ -175,7 +171,7 @@ def absent(name, protocol=None, service_address=None, server_address=None): ret["result"] = None ret[ "comment" - ] = "LVS Server {0} in service {1}({2}) is present and needs to be removed".format( + ] = "LVS Server {} in service {}({}) is present and needs to be removed".format( name, service_address, protocol ) return ret @@ -185,9 +181,7 @@ def absent(name, protocol=None, service_address=None, server_address=None): server_address=server_address, ) if server_delete is True: - ret[ - "comment" - ] = "LVS Server {0} in service {1}({2}) has been removed".format( + ret["comment"] = "LVS Server {} in service {}({}) has been removed".format( name, service_address, protocol ) ret["changes"][name] = "Absent" @@ -195,7 +189,7 @@ def absent(name, protocol=None, service_address=None, server_address=None): else: ret[ "comment" - ] = "LVS Server {0} in service {1}({2}) removed failed({3})".format( + ] = "LVS Server {} in service {}({}) removed failed({})".format( name, service_address, protocol, server_delete ) ret["result"] = False @@ -203,7 +197,7 @@ def absent(name, protocol=None, service_address=None, server_address=None): else: ret[ "comment" - ] = "LVS Server {0} in service {1}({2}) is not present, so it cannot be removed".format( + ] = "LVS Server {} in service {}({}) is not present, so it cannot be removed".format( name, service_address, protocol ) diff --git a/salt/states/lvs_service.py b/salt/states/lvs_service.py index 5eb9f05311e..a45d4409509 100644 --- a/salt/states/lvs_service.py +++ b/salt/states/lvs_service.py @@ -1,12 +1,8 @@ -# -*- coding: utf-8 -*- """ Management of LVS (Linux Virtual Server) Service ================================================ """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - def __virtual__(): """ @@ -54,14 +50,14 @@ def present( protocol=protocol, service_address=service_address, scheduler=scheduler ) if service_rule_check is True: - ret["comment"] = "LVS Service {0} is present".format(name) + ret["comment"] = "LVS Service {} is present".format(name) return ret else: if __opts__["test"]: ret["result"] = None ret[ "comment" - ] = "LVS Service {0} is present but some options should update".format( + ] = "LVS Service {} is present but some options should update".format( name ) return ret @@ -72,18 +68,18 @@ def present( scheduler=scheduler, ) if service_edit is True: - ret["comment"] = "LVS Service {0} has been updated".format(name) + ret["comment"] = "LVS Service {} has been updated".format(name) ret["changes"][name] = "Update" return ret else: ret["result"] = False - ret["comment"] = "LVS Service {0} update failed".format(name) + ret["comment"] = "LVS Service {} update failed".format(name) return ret else: if __opts__["test"]: ret[ "comment" - ] = "LVS Service {0} is not present and needs to be created".format(name) + ] = "LVS Service {} is not present and needs to be created".format(name) ret["result"] = None return ret else: @@ -91,11 +87,11 @@ def present( protocol=protocol, service_address=service_address, scheduler=scheduler ) if service_add is True: - ret["comment"] = "LVS Service {0} has been created".format(name) + ret["comment"] = "LVS Service {} has been created".format(name) ret["changes"][name] = "Present" return ret else: - ret["comment"] = "LVS Service {0} create failed({1})".format( + ret["comment"] = "LVS Service {} create failed({})".format( name, service_add ) ret["result"] = False @@ -124,19 +120,19 @@ def absent(name, protocol=None, service_address=None): if service_check is True: if __opts__["test"]: ret["result"] = None - ret[ - "comment" - ] = "LVS Service {0} is present and needs to be removed".format(name) + ret["comment"] = "LVS Service {} is present and needs to be removed".format( + name + ) return ret service_delete = __salt__["lvs.delete_service"]( protocol=protocol, service_address=service_address ) if service_delete is True: - ret["comment"] = "LVS Service {0} has been removed".format(name) + ret["comment"] = "LVS Service {} has been removed".format(name) ret["changes"][name] = "Absent" return ret else: - ret["comment"] = "LVS Service {0} removed failed({1})".format( + ret["comment"] = "LVS Service {} removed failed({})".format( name, service_delete ) ret["result"] = False @@ -144,6 +140,6 @@ def absent(name, protocol=None, service_address=None): else: ret[ "comment" - ] = "LVS Service {0} is not present, so it cannot be removed".format(name) + ] = "LVS Service {} is not present, so it cannot be removed".format(name) return ret diff --git a/salt/states/lxc.py b/salt/states/lxc.py index e066b55706d..928926e989c 100644 --- a/salt/states/lxc.py +++ b/salt/states/lxc.py @@ -1,12 +1,9 @@ -# -*- coding: utf-8 -*- """ Manage Linux Containers ======================= """ -from __future__ import absolute_import, print_function, unicode_literals -# Import salt libs from salt.exceptions import CommandExecutionError, SaltInvocationError __docformat__ = "restructuredtext en" @@ -154,7 +151,7 @@ def present( ret = { "name": name, "result": True, - "comment": "Container '{0}' already exists".format(name), + "comment": "Container '{}' already exists".format(name), "changes": {}, } @@ -182,17 +179,17 @@ def present( # Sanity check(s) if clone_from and not __salt__["lxc.exists"](clone_from, path=path): ret["result"] = False - ret["comment"] = "Clone source '{0}' does not exist".format(clone_from) + ret["comment"] = "Clone source '{}' does not exist".format(clone_from) if not ret["result"]: return ret - action = "cloned from {0}".format(clone_from) if clone_from else "created" + action = "cloned from {}".format(clone_from) if clone_from else "created" state = {"old": __salt__["lxc.state"](name, path=path)} if __opts__["test"]: if state["old"] is None: - ret["comment"] = "Container '{0}' will be {1}".format( - name, "cloned from {0}".format(clone_from) if clone_from else "created" + ret["comment"] = "Container '{}' will be {}".format( + name, "cloned from {}".format(clone_from) if clone_from else "created" ) ret["result"] = None return ret @@ -203,7 +200,7 @@ def present( return ret elif running: if state["old"] in ("frozen", "stopped"): - ret["comment"] = "Container '{0}' would be {1}".format( + ret["comment"] = "Container '{}' would be {}".format( name, "unfrozen" if state["old"] == "frozen" else "started" ) ret["result"] = None @@ -213,7 +210,7 @@ def present( return ret else: if state["old"] in ("frozen", "running"): - ret["comment"] = "Container '{0}' would be stopped".format(name) + ret["comment"] = "Container '{}' would be stopped".format(name) ret["result"] = None return ret else: @@ -256,11 +253,11 @@ def present( ret["comment"] = exc.strerror else: if clone_from: - ret["comment"] = "Cloned container '{0}' as '{1}'".format( + ret["comment"] = "Cloned container '{}' as '{}'".format( clone_from, name ) else: - ret["comment"] = "Created container '{0}'".format(name) + ret["comment"] = "Created container '{}'".format(name) state["new"] = result["state"]["new"] if ret["result"] is True: @@ -282,12 +279,12 @@ def present( ret["comment"] += error except (SaltInvocationError, CommandExecutionError) as exc: ret["result"] = False - ret["comment"] += "{0}: {1}".format(error, exc) + ret["comment"] += "{}: {}".format(error, exc) else: if state["old"] is None: ret["comment"] += ", and the container was started" else: - ret["comment"] = "Container '{0}' was {1}".format( + ret["comment"] = "Container '{}' was {}".format( name, "unfrozen" if state["old"] == "frozen" else "started" ) @@ -305,12 +302,12 @@ def present( ret["comment"] += error except (SaltInvocationError, CommandExecutionError) as exc: ret["result"] = False - ret["comment"] += "{0}: {1}".format(error, exc) + ret["comment"] += "{}: {}".format(error, exc) else: if state["old"] is None: ret["comment"] += ", and the container was stopped" else: - ret["comment"] = "Container '{0}' was stopped".format(name) + ret["comment"] = "Container '{}' was stopped".format(name) if "new" not in state: # Make sure we know the final state of the container before we return @@ -349,7 +346,7 @@ def absent(name, stop=False, path=None): "name": name, "changes": {}, "result": True, - "comment": "Container '{0}' does not exist".format(name), + "comment": "Container '{}' does not exist".format(name), } if not __salt__["lxc.exists"](name, path=path): @@ -357,17 +354,17 @@ def absent(name, stop=False, path=None): if __opts__["test"]: ret["result"] = None - ret["comment"] = "Container '{0}' would be destroyed".format(name) + ret["comment"] = "Container '{}' would be destroyed".format(name) return ret try: result = __salt__["lxc.destroy"](name, stop=stop, path=path) except (SaltInvocationError, CommandExecutionError) as exc: ret["result"] = False - ret["comment"] = "Failed to destroy container: {0}".format(exc) + ret["comment"] = "Failed to destroy container: {}".format(exc) else: ret["changes"]["state"] = result["state"] - ret["comment"] = "Container '{0}' was destroyed".format(name) + ret["comment"] = "Container '{}' was destroyed".format(name) return ret @@ -411,14 +408,14 @@ def running(name, restart=False, path=None): ret = { "name": name, "result": True, - "comment": "Container '{0}' is already running".format(name), + "comment": "Container '{}' is already running".format(name), "changes": {}, } state = {"old": __salt__["lxc.state"](name, path=path)} if state["old"] is None: ret["result"] = False - ret["comment"] = "Container '{0}' does not exist".format(name) + ret["comment"] = "Container '{}' does not exist".format(name) return ret elif state["old"] == "running" and not restart: return ret @@ -439,7 +436,7 @@ def running(name, restart=False, path=None): if __opts__["test"]: ret["result"] = None - ret["comment"] = "Container '{0}' would be {1}".format(name, action[1]) + ret["comment"] = "Container '{}' would be {}".format(name, action[1]) return ret try: @@ -458,9 +455,9 @@ def running(name, restart=False, path=None): state["new"] = result["state"]["new"] if state["new"] != "running": ret["result"] = False - ret["comment"] = "Unable to {0} container '{1}'".format(action[0], name) + ret["comment"] = "Unable to {} container '{}'".format(action[0], name) else: - ret["comment"] = "Container '{0}' was successfully {1}".format( + ret["comment"] = "Container '{}' was successfully {}".format( name, action[1] ) try: @@ -511,17 +508,17 @@ def frozen(name, start=True, path=None): ret = { "name": name, "result": True, - "comment": "Container '{0}' is already frozen".format(name), + "comment": "Container '{}' is already frozen".format(name), "changes": {}, } state = {"old": __salt__["lxc.state"](name, path=path)} if state["old"] is None: ret["result"] = False - ret["comment"] = "Container '{0}' does not exist".format(name) + ret["comment"] = "Container '{}' does not exist".format(name) elif state["old"] == "stopped" and not start: ret["result"] = False - ret["comment"] = "Container '{0}' is stopped".format(name) + ret["comment"] = "Container '{}' is stopped".format(name) if ret["result"] is False or state["old"] == "frozen": return ret @@ -533,7 +530,7 @@ def frozen(name, start=True, path=None): if __opts__["test"]: ret["result"] = None - ret["comment"] = "Container '{0}' would be {1}".format(name, action[1]) + ret["comment"] = "Container '{}' would be {}".format(name, action[1]) return ret try: @@ -546,9 +543,9 @@ def frozen(name, start=True, path=None): state["new"] = result["state"]["new"] if state["new"] != "frozen": ret["result"] = False - ret["comment"] = "Unable to {0} container '{1}'".format(action[0], name) + ret["comment"] = "Unable to {} container '{}'".format(action[0], name) else: - ret["comment"] = "Container '{0}' was successfully {1}".format( + ret["comment"] = "Container '{}' was successfully {}".format( name, action[1] ) try: @@ -598,14 +595,14 @@ def stopped(name, kill=False, path=None): ret = { "name": name, "result": True, - "comment": "Container '{0}' is already stopped".format(name), + "comment": "Container '{}' is already stopped".format(name), "changes": {}, } state = {"old": __salt__["lxc.state"](name, path=path)} if state["old"] is None: ret["result"] = False - ret["comment"] = "Container '{0}' does not exist".format(name) + ret["comment"] = "Container '{}' does not exist".format(name) return ret elif state["old"] == "stopped": return ret @@ -617,7 +614,7 @@ def stopped(name, kill=False, path=None): if __opts__["test"]: ret["result"] = None - ret["comment"] = "Container '{0}' would be {1}".format(name, action[1]) + ret["comment"] = "Container '{}' would be {}".format(name, action[1]) return ret try: @@ -630,9 +627,9 @@ def stopped(name, kill=False, path=None): state["new"] = result["state"]["new"] if state["new"] != "stopped": ret["result"] = False - ret["comment"] = "Unable to {0} container '{1}'".format(action[0], name) + ret["comment"] = "Unable to {} container '{}'".format(action[0], name) else: - ret["comment"] = "Container '{0}' was successfully {1}".format( + ret["comment"] = "Container '{}' was successfully {}".format( name, action[1] ) @@ -709,7 +706,7 @@ def edited_conf(name, lxc_conf=None, lxc_conf_unset=None): if __opts__["test"]: return { "name": name, - "comment": "{0} lxc.conf will be edited".format(name), + "comment": "{} lxc.conf will be edited".format(name), "result": True, "changes": {}, } diff --git a/salt/states/lxd.py b/salt/states/lxd.py index 341ad21418b..408e10af796 100644 --- a/salt/states/lxd.py +++ b/salt/states/lxd.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage LXD profiles. @@ -28,14 +27,9 @@ Manage LXD profiles. :platform: Linux """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import os.path -import salt.ext.six as six - -# Import salt libs from salt.exceptions import CommandExecutionError, SaltInvocationError __docformat__ = "restructuredtext en" @@ -137,7 +131,7 @@ def init( storage_pool if storage_pool else None, ) except CommandExecutionError as e: - return _error(ret, six.text_type(e)) + return _error(ret, str(e)) return _success(ret, "Initialized the LXD Daemon") @@ -168,16 +162,16 @@ def config_managed(name, value, force_password=False): try: current_value = __salt__["lxd.config_get"](name) except CommandExecutionError as e: - return _error(ret, six.text_type(e)) + return _error(ret, str(e)) if name == _password_config_key and (not force_password or not current_value): msg = ( - '"{0}" is already set ' "(we don't known if the password is correct)" + '"{}" is already set ' "(we don't known if the password is correct)" ).format(name) return _success(ret, msg) - elif six.text_type(value) == current_value: - msg = '"{0}" is already set to "{1}"'.format(name, value) + elif str(value) == current_value: + msg = '"{}" is already set to "{}"'.format(name, value) return _success(ret, msg) if __opts__["test"]: @@ -186,7 +180,7 @@ def config_managed(name, value, force_password=False): ret["changes"] = {"password": msg} return _unchanged(ret, msg) else: - msg = 'Would set the "{0}" to "{1}"'.format(name, value) + msg = 'Would set the "{}" to "{}"'.format(name, value) ret["changes"] = {name: msg} return _unchanged(ret, msg) @@ -197,10 +191,10 @@ def config_managed(name, value, force_password=False): ret["changes"] = {name: "Changed the password"} else: ret["changes"] = { - name: 'Changed from "{0}" to {1}"'.format(current_value, value) + name: 'Changed from "{}" to {}"'.format(current_value, value) } except CommandExecutionError as e: - return _error(ret, six.text_type(e)) + return _error(ret, str(e)) return _success(ret, result_msg) @@ -256,9 +250,9 @@ def authenticate(name, remote_addr, password, cert, key, verify_cert=True): try: client = __salt__["lxd.pylxd_client_get"](remote_addr, cert, key, verify_cert) except SaltInvocationError as e: - return _error(ret, six.text_type(e)) + return _error(ret, str(e)) except CommandExecutionError as e: - return _error(ret, six.text_type(e)) + return _error(ret, str(e)) if client.trusted: return _success(ret, "Already authenticated.") @@ -268,12 +262,12 @@ def authenticate(name, remote_addr, password, cert, key, verify_cert=True): remote_addr, password, cert, key, verify_cert ) except CommandExecutionError as e: - return _error(ret, six.text_type(e)) + return _error(ret, str(e)) if result is not True: - return _error(ret, "Failed to authenticate with peer: {0}".format(remote_addr)) + return _error(ret, "Failed to authenticate with peer: {}".format(remote_addr)) - msg = "Successfully authenticated with peer: {0}".format(remote_addr) + msg = "Successfully authenticated with peer: {}".format(remote_addr) ret["changes"] = msg return _success(ret, msg) diff --git a/salt/states/lxd_container.py b/salt/states/lxd_container.py index ac355a96475..f81caf4cb03 100644 --- a/salt/states/lxd_container.py +++ b/salt/states/lxd_container.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage LXD containers. @@ -28,14 +27,8 @@ Manage LXD containers. :platform: Linux """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals -import salt.ext.six as six - -# Import salt libs from salt.exceptions import CommandExecutionError, SaltInvocationError -from salt.ext.six.moves import map __docformat__ = "restructuredtext en" @@ -218,7 +211,7 @@ def present( name, remote_addr, cert, key, verify_cert, _raw=True ) except CommandExecutionError as e: - return _error(ret, six.text_type(e)) + return _error(ret, str(e)) except SaltInvocationError as e: # Profile not found pass @@ -226,11 +219,11 @@ def present( if container is None: if __opts__["test"]: # Test is on, just return that we would create the container - msg = 'Would create the container "{0}"'.format(name) + msg = 'Would create the container "{}"'.format(name) ret["changes"] = {"created": msg} if running is True: msg = msg + " and start it." - ret["changes"]["started"] = 'Would start the container "{0}"'.format( + ret["changes"]["started"] = 'Would start the container "{}"'.format( name ) @@ -254,9 +247,9 @@ def present( verify_cert, ) except CommandExecutionError as e: - return _error(ret, six.text_type(e)) + return _error(ret, str(e)) - msg = 'Created the container "{0}"'.format(name) + msg = 'Created the container "{}"'.format(name) ret["changes"] = {"created": msg} if running is True: @@ -265,16 +258,16 @@ def present( name, remote_addr, cert, key, verify_cert ) except CommandExecutionError as e: - return _error(ret, six.text_type(e)) + return _error(ret, str(e)) msg = msg + " and started it." - ret["changes"] = {"started": 'Started the container "{0}"'.format(name)} + ret["changes"] = {"started": 'Started the container "{}"'.format(name)} return _success(ret, msg) # Container exists, lets check for differences - new_profiles = set(map(six.text_type, profiles)) - old_profiles = set(map(six.text_type, container.profiles)) + new_profiles = set(map(str, profiles)) + old_profiles = set(map(str, container.profiles)) container_changed = False @@ -282,18 +275,18 @@ def present( # Removed profiles for k in old_profiles.difference(new_profiles): if not __opts__["test"]: - profile_changes.append('Removed profile "{0}"'.format(k)) + profile_changes.append('Removed profile "{}"'.format(k)) old_profiles.discard(k) else: - profile_changes.append('Would remove profile "{0}"'.format(k)) + profile_changes.append('Would remove profile "{}"'.format(k)) # Added profiles for k in new_profiles.difference(old_profiles): if not __opts__["test"]: - profile_changes.append('Added profile "{0}"'.format(k)) + profile_changes.append('Added profile "{}"'.format(k)) old_profiles.add(k) else: - profile_changes.append('Would add profile "{0}"'.format(k)) + profile_changes.append('Would add profile "{}"'.format(k)) if profile_changes: container_changed = True @@ -315,7 +308,7 @@ def present( try: __salt__["lxd.pylxd_save_object"](container) except CommandExecutionError as e: - return _error(ret, six.text_type(e)) + return _error(ret, str(e)) if running != is_running: if running is True: @@ -323,7 +316,7 @@ def present( changes["running"] = "Would start the container" return _unchanged( ret, - ('Container "{0}" would get changed ' "and started.").format(name), + ('Container "{}" would get changed ' "and started.").format(name), ) else: container.start(wait=True) @@ -334,7 +327,7 @@ def present( changes["stopped"] = "Would stopped the container" return _unchanged( ret, - ('Container "{0}" would get changed ' "and stopped.").format(name), + ('Container "{}" would get changed ' "and stopped.").format(name), ) else: container.stop(wait=True) @@ -349,19 +342,19 @@ def present( if __opts__["test"]: changes["restarted"] = "Would restart the container" - return _unchanged(ret, 'Would restart the container "{0}"'.format(name)) + return _unchanged(ret, 'Would restart the container "{}"'.format(name)) else: container.restart(wait=True) - changes["restarted"] = 'Container "{0}" has been restarted'.format(name) - return _success(ret, 'Container "{0}" has been restarted'.format(name)) + changes["restarted"] = 'Container "{}" has been restarted'.format(name) + return _success(ret, 'Container "{}" has been restarted'.format(name)) if not container_changed: return _success(ret, "No changes") if __opts__["test"]: - return _unchanged(ret, 'Container "{0}" would get changed.'.format(name)) + return _unchanged(ret, 'Container "{}" would get changed.'.format(name)) - return _success(ret, "{0} changes".format(len(ret["changes"].keys()))) + return _success(ret, "{} changes".format(len(ret["changes"].keys()))) def absent(name, stop=False, remote_addr=None, cert=None, key=None, verify_cert=True): @@ -415,13 +408,13 @@ def absent(name, stop=False, remote_addr=None, cert=None, key=None, verify_cert= name, remote_addr, cert, key, verify_cert, _raw=True ) except CommandExecutionError as e: - return _error(ret, six.text_type(e)) + return _error(ret, str(e)) except SaltInvocationError as e: # Container not found - return _success(ret, 'Container "{0}" not found.'.format(name)) + return _success(ret, 'Container "{}" not found.'.format(name)) if __opts__["test"]: - ret["changes"] = {"removed": 'Container "{0}" would get deleted.'.format(name)} + ret["changes"] = {"removed": 'Container "{}" would get deleted.'.format(name)} return _unchanged(ret, ret["changes"]["removed"]) if stop and container.status_code == CONTAINER_STATUS_RUNNING: @@ -429,7 +422,7 @@ def absent(name, stop=False, remote_addr=None, cert=None, key=None, verify_cert= container.delete(wait=True) - ret["changes"]["deleted"] = 'Container "{0}" has been deleted.'.format(name) + ret["changes"]["deleted"] = 'Container "{}" has been deleted.'.format(name) return _success(ret, ret["changes"]["deleted"]) @@ -485,35 +478,35 @@ def running( name, remote_addr, cert, key, verify_cert, _raw=True ) except CommandExecutionError as e: - return _error(ret, six.text_type(e)) + return _error(ret, str(e)) except SaltInvocationError as e: # Container not found - return _error(ret, 'Container "{0}" not found'.format(name)) + return _error(ret, 'Container "{}" not found'.format(name)) is_running = container.status_code == CONTAINER_STATUS_RUNNING if is_running: if not restart: - return _success(ret, 'The container "{0}" is already running'.format(name)) + return _success(ret, 'The container "{}" is already running'.format(name)) else: if __opts__["test"]: - ret["changes"][ - "restarted" - ] = 'Would restart the container "{0}"'.format(name) + ret["changes"]["restarted"] = 'Would restart the container "{}"'.format( + name + ) return _unchanged(ret, ret["changes"]["restarted"]) else: container.restart(wait=True) - ret["changes"]["restarted"] = 'Restarted the container "{0}"'.format( + ret["changes"]["restarted"] = 'Restarted the container "{}"'.format( name ) return _success(ret, ret["changes"]["restarted"]) if __opts__["test"]: - ret["changes"]["started"] = 'Would start the container "{0}"'.format(name) + ret["changes"]["started"] = 'Would start the container "{}"'.format(name) return _unchanged(ret, ret["changes"]["started"]) container.start(wait=True) - ret["changes"]["started"] = 'Started the container "{0}"'.format(name) + ret["changes"]["started"] = 'Started the container "{}"'.format(name) return _success(ret, ret["changes"]["started"]) @@ -567,13 +560,13 @@ def frozen(name, start=True, remote_addr=None, cert=None, key=None, verify_cert= name, remote_addr, cert, key, verify_cert, _raw=True ) except CommandExecutionError as e: - return _error(ret, six.text_type(e)) + return _error(ret, str(e)) except SaltInvocationError as e: # Container not found - return _error(ret, 'Container "{0}" not found'.format(name)) + return _error(ret, 'Container "{}" not found'.format(name)) if container.status_code == CONTAINER_STATUS_FROZEN: - return _success(ret, 'Container "{0}" is alredy frozen'.format(name)) + return _success(ret, 'Container "{}" is alredy frozen'.format(name)) is_running = container.status_code == CONTAINER_STATUS_RUNNING @@ -581,7 +574,7 @@ def frozen(name, start=True, remote_addr=None, cert=None, key=None, verify_cert= return _error( ret, ( - 'Container "{0}" is not running and start is False, ' "cannot freeze it" + 'Container "{}" is not running and start is False, ' "cannot freeze it" ).format(name), ) @@ -589,18 +582,18 @@ def frozen(name, start=True, remote_addr=None, cert=None, key=None, verify_cert= if __opts__["test"]: ret["changes"][ "started" - ] = 'Would start the container "{0}" and freeze it after'.format(name) + ] = 'Would start the container "{}" and freeze it after'.format(name) return _unchanged(ret, ret["changes"]["started"]) else: container.start(wait=True) - ret["changes"]["started"] = 'Start the container "{0}"'.format(name) + ret["changes"]["started"] = 'Start the container "{}"'.format(name) if __opts__["test"]: - ret["changes"]["frozen"] = 'Would freeze the container "{0}"'.format(name) + ret["changes"]["frozen"] = 'Would freeze the container "{}"'.format(name) return _unchanged(ret, ret["changes"]["frozen"]) container.freeze(wait=True) - ret["changes"]["frozen"] = 'Froze the container "{0}"'.format(name) + ret["changes"]["frozen"] = 'Froze the container "{}"'.format(name) return _success(ret, ret["changes"]["frozen"]) @@ -655,20 +648,20 @@ def stopped(name, kill=False, remote_addr=None, cert=None, key=None, verify_cert name, remote_addr, cert, key, verify_cert, _raw=True ) except CommandExecutionError as e: - return _error(ret, six.text_type(e)) + return _error(ret, str(e)) except SaltInvocationError as e: # Container not found - return _error(ret, 'Container "{0}" not found'.format(name)) + return _error(ret, 'Container "{}" not found'.format(name)) if container.status_code == CONTAINER_STATUS_STOPPED: - return _success(ret, 'Container "{0}" is already stopped'.format(name)) + return _success(ret, 'Container "{}" is already stopped'.format(name)) if __opts__["test"]: - ret["changes"]["stopped"] = 'Would stop the container "{0}"'.format(name) + ret["changes"]["stopped"] = 'Would stop the container "{}"'.format(name) return _unchanged(ret, ret["changes"]["stopped"]) container.stop(force=kill, wait=True) - ret["changes"]["stopped"] = 'Stopped the container "{0}"'.format(name) + ret["changes"]["stopped"] = 'Stopped the container "{}"'.format(name) return _success(ret, ret["changes"]["stopped"]) @@ -765,13 +758,13 @@ def migrated( name, remote_addr, cert, key, verify_cert, _raw=True ) except CommandExecutionError as e: - return _error(ret, six.text_type(e)) + return _error(ret, str(e)) except SaltInvocationError as e: # Destination container not found pass if dest_container is not None: - return _success(ret, 'Container "{0}" exists on the destination'.format(name)) + return _success(ret, 'Container "{}" exists on the destination'.format(name)) if src_verify_cert is None: src_verify_cert = verify_cert @@ -781,14 +774,14 @@ def migrated( name, src_remote_addr, src_cert, src_key, src_verify_cert, _raw=True ) except CommandExecutionError as e: - return _error(ret, six.text_type(e)) + return _error(ret, str(e)) except SaltInvocationError as e: # Container not found - return _error(ret, 'Source Container "{0}" not found'.format(name)) + return _error(ret, 'Source Container "{}" not found'.format(name)) if __opts__["test"]: ret["changes"]["migrated"] = ( - 'Would migrate the container "{0}" from "{1}" to "{2}"' + 'Would migrate the container "{}" from "{}" to "{}"' ).format(name, src_remote_addr, remote_addr) return _unchanged(ret, ret["changes"]["migrated"]) @@ -806,10 +799,10 @@ def migrated( src_verify_cert, ) except CommandExecutionError as e: - return _error(ret, six.text_type(e)) + return _error(ret, str(e)) ret["changes"]["migrated"] = ( - 'Migrated the container "{0}" from "{1}" to "{2}"' + 'Migrated the container "{}" from "{}" to "{}"' ).format(name, src_remote_addr, remote_addr) return _success(ret, ret["changes"]["migrated"]) diff --git a/salt/states/lxd_image.py b/salt/states/lxd_image.py index 2a02a7184bd..c6d554ee284 100644 --- a/salt/states/lxd_image.py +++ b/salt/states/lxd_image.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage LXD images. @@ -29,14 +28,8 @@ Manage LXD images. :platform: Linux """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals -import salt.ext.six as six - -# Import salt libs from salt.exceptions import CommandExecutionError, SaltInvocationError -from salt.ext.six.moves import map __docformat__ = "restructuredtext en" @@ -180,7 +173,7 @@ def present( name, remote_addr, cert, key, verify_cert, _raw=True ) except CommandExecutionError as e: - return _error(ret, six.text_type(e)) + return _error(ret, str(e)) except SaltInvocationError as e: # Image not found pass @@ -188,7 +181,7 @@ def present( if image is None: if __opts__["test"]: # Test is on, just return that we would create the image - msg = 'Would create the image "{0}"'.format(name) + msg = 'Would create the image "{}"'.format(name) ret["changes"] = {"created": msg} return _unchanged(ret, msg) @@ -252,31 +245,31 @@ def present( _raw=True, ) except CommandExecutionError as e: - return _error(ret, six.text_type(e)) + return _error(ret, str(e)) # Sync aliases if name not in aliases: aliases.append(name) - old_aliases = set([six.text_type(a["name"]) for a in image.aliases]) - new_aliases = set(map(six.text_type, aliases)) + old_aliases = {str(a["name"]) for a in image.aliases} + new_aliases = set(map(str, aliases)) alias_changes = [] # Removed aliases for k in old_aliases.difference(new_aliases): if not __opts__["test"]: __salt__["lxd.image_alias_delete"](image, k) - alias_changes.append('Removed alias "{0}"'.format(k)) + alias_changes.append('Removed alias "{}"'.format(k)) else: - alias_changes.append('Would remove alias "{0}"'.format(k)) + alias_changes.append('Would remove alias "{}"'.format(k)) # New aliases for k in new_aliases.difference(old_aliases): if not __opts__["test"]: __salt__["lxd.image_alias_add"](image, k, "") - alias_changes.append('Added alias "{0}"'.format(k)) + alias_changes.append('Added alias "{}"'.format(k)) else: - alias_changes.append('Would add alias "{0}"'.format(k)) + alias_changes.append('Would add alias "{}"'.format(k)) if alias_changes: ret["changes"]["aliases"] = alias_changes @@ -284,20 +277,16 @@ def present( # Set public if public is not None and image.public != public: if not __opts__["test"]: - ret["changes"]["public"] = "Setting the image public to {0!s}".format( - public - ) + ret["changes"]["public"] = "Setting the image public to {!s}".format(public) image.public = public __salt__["lxd.pylxd_save_object"](image) else: - ret["changes"]["public"] = "Would set public to {0!s}".format(public) + ret["changes"]["public"] = "Would set public to {!s}".format(public) if __opts__["test"] and ret["changes"]: - return _unchanged( - ret, "Would do {0} changes".format(len(ret["changes"].keys())) - ) + return _unchanged(ret, "Would do {} changes".format(len(ret["changes"].keys()))) - return _success(ret, "{0} changes".format(len(ret["changes"].keys()))) + return _success(ret, "{} changes".format(len(ret["changes"].keys()))) def absent(name, remote_addr=None, cert=None, key=None, verify_cert=True): @@ -344,24 +333,24 @@ def absent(name, remote_addr=None, cert=None, key=None, verify_cert=True): name, remote_addr, cert, key, verify_cert, _raw=True ) except CommandExecutionError as e: - return _error(ret, six.text_type(e)) + return _error(ret, str(e)) except SaltInvocationError as e: try: image = __salt__["lxd.image_get"]( name, remote_addr, cert, key, verify_cert, _raw=True ) except CommandExecutionError as e: - return _error(ret, six.text_type(e)) + return _error(ret, str(e)) except SaltInvocationError as e: - return _success(ret, 'Image "{0}" not found.'.format(name)) + return _success(ret, 'Image "{}" not found.'.format(name)) if __opts__["test"]: - ret["changes"] = {"removed": 'Image "{0}" would get deleted.'.format(name)} + ret["changes"] = {"removed": 'Image "{}" would get deleted.'.format(name)} return _success(ret, ret["changes"]["removed"]) __salt__["lxd.image_delete"](image) - ret["changes"] = {"removed": 'Image "{0}" has been deleted.'.format(name)} + ret["changes"] = {"removed": 'Image "{}" has been deleted.'.format(name)} return _success(ret, ret["changes"]["removed"]) diff --git a/salt/states/lxd_profile.py b/salt/states/lxd_profile.py index 271e4f61fcb..92c8cf18695 100644 --- a/salt/states/lxd_profile.py +++ b/salt/states/lxd_profile.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage LXD profiles. @@ -28,12 +27,7 @@ Manage LXD profiles. :platform: Linux """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals -import salt.ext.six as six - -# Import salt libs from salt.exceptions import CommandExecutionError, SaltInvocationError __docformat__ = "restructuredtext en" @@ -128,18 +122,18 @@ def present( name, remote_addr, cert, key, verify_cert, _raw=True ) except CommandExecutionError as e: - return _error(ret, six.text_type(e)) + return _error(ret, str(e)) except SaltInvocationError as e: # Profile not found pass if description is None: - description = six.text_type() + description = "" if profile is None: if __opts__["test"]: # Test is on, just return that we would create the profile - msg = 'Would create the profile "{0}"'.format(name) + msg = 'Would create the profile "{}"'.format(name) ret["changes"] = {"created": msg} return _unchanged(ret, msg) @@ -150,9 +144,9 @@ def present( ) except CommandExecutionError as e: - return _error(ret, six.text_type(e)) + return _error(ret, str(e)) - msg = 'Profile "{0}" has been created'.format(name) + msg = 'Profile "{}" has been created'.format(name) ret["changes"] = {"created": msg} return _success(ret, msg) @@ -161,9 +155,9 @@ def present( # # Description change # - if six.text_type(profile.description) != six.text_type(description): + if str(profile.description) != str(description): ret["changes"]["description"] = ( - 'Description changed, from "{0}" to "{1}".' + 'Description changed, from "{}" to "{}".' ).format(profile.description, description) profile.description = description @@ -177,14 +171,14 @@ def present( return _success(ret, "No changes") if __opts__["test"]: - return _unchanged(ret, 'Profile "{0}" would get changed.'.format(name)) + return _unchanged(ret, 'Profile "{}" would get changed.'.format(name)) try: __salt__["lxd.pylxd_save_object"](profile) except CommandExecutionError as e: - return _error(ret, six.text_type(e)) + return _error(ret, str(e)) - return _success(ret, "{0} changes".format(len(ret["changes"].keys()))) + return _success(ret, "{} changes".format(len(ret["changes"].keys()))) def absent(name, remote_addr=None, cert=None, key=None, verify_cert=True): @@ -235,23 +229,23 @@ def absent(name, remote_addr=None, cert=None, key=None, verify_cert=True): try: __salt__["lxd.profile_get"](name, remote_addr, cert, key, verify_cert) except CommandExecutionError as e: - return _error(ret, six.text_type(e)) + return _error(ret, str(e)) except SaltInvocationError as e: # Profile not found - return _success(ret, 'Profile "{0}" not found.'.format(name)) + return _success(ret, 'Profile "{}" not found.'.format(name)) - ret["changes"] = {"removed": 'Profile "{0}" would get deleted.'.format(name)} + ret["changes"] = {"removed": 'Profile "{}" would get deleted.'.format(name)} return _success(ret, ret["changes"]["removed"]) try: __salt__["lxd.profile_delete"](name, remote_addr, cert, key, verify_cert) except CommandExecutionError as e: - return _error(ret, six.text_type(e)) + return _error(ret, str(e)) except SaltInvocationError as e: # Profile not found - return _success(ret, 'Profile "{0}" not found.'.format(name)) + return _success(ret, 'Profile "{}" not found.'.format(name)) - ret["changes"] = {"removed": 'Profile "{0}" has been deleted.'.format(name)} + ret["changes"] = {"removed": 'Profile "{}" has been deleted.'.format(name)} return _success(ret, ret["changes"]["removed"]) diff --git a/salt/states/marathon_app.py b/salt/states/marathon_app.py index c6f829ded41..1df39665f36 100644 --- a/salt/states/marathon_app.py +++ b/salt/states/marathon_app.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Configure Marathon apps via a salt proxy. @@ -14,7 +13,6 @@ Configure Marathon apps via a salt proxy. .. versionadded:: 2015.8.2 """ -from __future__ import absolute_import, print_function, unicode_literals import copy import logging @@ -66,22 +64,22 @@ def config(name, config): # if test, report there will be an update if __opts__["test"]: ret["result"] = None - ret["comment"] = "Marathon app {0} is set to be updated".format(name) + ret["comment"] = "Marathon app {} is set to be updated".format(name) return ret update_result = __salt__["marathon.update_app"](name, update_config) if "exception" in update_result: ret["result"] = False - ret["comment"] = "Failed to update app config for {0}: {1}".format( + ret["comment"] = "Failed to update app config for {}: {}".format( name, update_result["exception"], ) return ret else: ret["result"] = True - ret["comment"] = "Updated app config for {0}".format(name) + ret["comment"] = "Updated app config for {}".format(name) return ret ret["result"] = True - ret["comment"] = "Marathon app {0} configured correctly".format(name) + ret["comment"] = "Marathon app {} configured correctly".format(name) return ret @@ -95,20 +93,20 @@ def absent(name): ret = {"name": name, "changes": {}, "result": False, "comment": ""} if not __salt__["marathon.has_app"](name): ret["result"] = True - ret["comment"] = "App {0} already absent".format(name) + ret["comment"] = "App {} already absent".format(name) return ret if __opts__["test"]: ret["result"] = None - ret["comment"] = "App {0} is set to be removed".format(name) + ret["comment"] = "App {} is set to be removed".format(name) return ret if __salt__["marathon.rm_app"](name): ret["changes"] = {"app": name} ret["result"] = True - ret["comment"] = "Removed app {0}".format(name) + ret["comment"] = "Removed app {}".format(name) return ret else: ret["result"] = False - ret["comment"] = "Failed to remove app {0}".format(name) + ret["comment"] = "Failed to remove app {}".format(name) return ret @@ -124,17 +122,17 @@ def running(name, restart=False, force=True): ret = {"name": name, "changes": {}, "result": False, "comment": ""} if not __salt__["marathon.has_app"](name): ret["result"] = False - ret["comment"] = "App {0} cannot be restarted because it is absent".format(name) + ret["comment"] = "App {} cannot be restarted because it is absent".format(name) return ret if __opts__["test"]: ret["result"] = None qualifier = "is" if restart else "is not" - ret["comment"] = "App {0} {1} set to be restarted".format(name, qualifier) + ret["comment"] = "App {} {} set to be restarted".format(name, qualifier) return ret restart_result = __salt__["marathon.restart_app"](name, restart, force) if "exception" in restart_result: ret["result"] = False - ret["comment"] = "Failed to restart app {0}: {1}".format( + ret["comment"] = "Failed to restart app {}: {}".format( name, restart_result["exception"] ) return ret @@ -142,5 +140,5 @@ def running(name, restart=False, force=True): ret["changes"] = restart_result ret["result"] = True qualifier = "Restarted" if restart else "Did not restart" - ret["comment"] = "{0} app {1}".format(qualifier, name) + ret["comment"] = "{} app {}".format(qualifier, name) return ret diff --git a/salt/states/memcached.py b/salt/states/memcached.py index 1ee9ec51823..9f4a6d367dd 100644 --- a/salt/states/memcached.py +++ b/salt/states/memcached.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ States for Management of Memcached Keys ======================================= @@ -6,13 +5,8 @@ States for Management of Memcached Keys .. versionadded:: 2014.1.0 """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals from salt.exceptions import CommandExecutionError, SaltInvocationError -from salt.ext import six - -# Import Salt libs from salt.modules.memcached import ( DEFAULT_HOST, DEFAULT_MIN_COMPRESS_LEN, @@ -27,7 +21,7 @@ def __virtual__(): """ Only load if memcache module is available """ - if "{0}.status".format(__virtualname__) in __salt__: + if "{}.status".format(__virtualname__) in __salt__: return __virtualname__ return (False, "memcached module could not be loaded") @@ -67,20 +61,20 @@ def managed( try: cur = __salt__["memcached.get"](name, host, port) except CommandExecutionError as exc: - ret["comment"] = six.text_type(exc) + ret["comment"] = str(exc) return ret if cur == value: ret["result"] = True - ret["comment"] = "Key '{0}' does not need to be updated".format(name) + ret["comment"] = "Key '{}' does not need to be updated".format(name) return ret if __opts__["test"]: ret["result"] = None if cur is None: - ret["comment"] = "Key '{0}' would be added".format(name) + ret["comment"] = "Key '{}' would be added".format(name) else: - ret["comment"] = "Value of key '{0}' would be changed".format(name) + ret["comment"] = "Value of key '{}' would be changed".format(name) return ret try: @@ -88,16 +82,16 @@ def managed( name, value, host, port, time, min_compress_len ) except (CommandExecutionError, SaltInvocationError) as exc: - ret["comment"] = six.text_type(exc) + ret["comment"] = str(exc) else: if ret["result"]: - ret["comment"] = "Successfully set key '{0}'".format(name) + ret["comment"] = "Successfully set key '{}'".format(name) if cur is not None: ret["changes"] = {"old": cur, "new": value} else: ret["changes"] = {"key added": name, "value": value} else: - ret["comment"] = "Failed to set key '{0}'".format(name) + ret["comment"] = "Failed to set key '{}'".format(name) return ret @@ -133,34 +127,34 @@ def absent(name, value=None, host=DEFAULT_HOST, port=DEFAULT_PORT, time=DEFAULT_ try: cur = __salt__["memcached.get"](name, host, port) except CommandExecutionError as exc: - ret["comment"] = six.text_type(exc) + ret["comment"] = str(exc) return ret if value is not None: if cur is not None and cur != value: ret["result"] = True - ret["comment"] = "Value of key '{0}' ('{1}') is not '{2}'".format( + ret["comment"] = "Value of key '{}' ('{}') is not '{}'".format( name, cur, value ) return ret if cur is None: ret["result"] = True - ret["comment"] = "Key '{0}' does not exist".format(name) + ret["comment"] = "Key '{}' does not exist".format(name) return ret if __opts__["test"]: ret["result"] = None - ret["comment"] = "Key '{0}' would be deleted".format(name) + ret["comment"] = "Key '{}' would be deleted".format(name) return ret try: ret["result"] = __salt__["memcached.delete"](name, host, port, time) except (CommandExecutionError, SaltInvocationError) as exc: - ret["comment"] = six.text_type(exc) + ret["comment"] = str(exc) else: if ret["result"]: - ret["comment"] = "Successfully deleted key '{0}'".format(name) + ret["comment"] = "Successfully deleted key '{}'".format(name) ret["changes"] = {"key deleted": name, "value": cur} else: - ret["comment"] = "Failed to delete key '{0}'".format(name) + ret["comment"] = "Failed to delete key '{}'".format(name) return ret diff --git a/salt/states/modjk.py b/salt/states/modjk.py index b539223824a..0932715b129 100644 --- a/salt/states/modjk.py +++ b/salt/states/modjk.py @@ -1,16 +1,11 @@ -# -*- coding: utf-8 -*- """ State to control Apache modjk """ # Python Libs -from __future__ import absolute_import, print_function, unicode_literals import logging -# Import 3rd-party libs -from salt.ext import six - log = logging.getLogger(__name__) @@ -31,7 +26,7 @@ def _bulk_state(saltfunc, lbn, workers, profile): if not isinstance(workers, list): ret["result"] = False - ret["comment"] = "workers should be a list not a {0}".format(type(workers)) + ret["comment"] = "workers should be a list not a {}".format(type(workers)) return ret if __opts__["test"]: @@ -43,18 +38,18 @@ def _bulk_state(saltfunc, lbn, workers, profile): cmdret = __salt__[saltfunc](workers, lbn, profile=profile) except KeyError: ret["result"] = False - ret["comment"] = "unsupported function {0}".format(saltfunc) + ret["comment"] = "unsupported function {}".format(saltfunc) return ret errors = [] - for worker, ok in six.iteritems(cmdret): + for worker, ok in cmdret.items(): if not ok: errors.append(worker) ret["changes"] = {"status": cmdret} if errors: ret["result"] = False - ret["comment"] = "{0} failed on some workers".format(saltfunc) + ret["comment"] = "{} failed on some workers".format(saltfunc) return ret diff --git a/salt/states/modjk_worker.py b/salt/states/modjk_worker.py index b58431a234d..ca8709d22f1 100644 --- a/salt/states/modjk_worker.py +++ b/salt/states/modjk_worker.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage modjk workers ==================== @@ -18,7 +17,6 @@ Mandatory Settings: - The modjk load balancer must be configured as stated in the :strong:`modjk` execution module :mod:`documentation ` """ -from __future__ import absolute_import, print_function, unicode_literals def __virtual__(): @@ -46,7 +44,7 @@ def _send_command(cmd, worker, lbn, target, profile="default", tgt_type="glob"): } # Send the command to target - func = "modjk.{0}".format(cmd) + func = "modjk.{}".format(cmd) args = [worker, lbn, profile] response = __salt__["publish.publish"](target, func, args, tgt_type) @@ -60,7 +58,7 @@ def _send_command(cmd, worker, lbn, target, profile="default", tgt_type="glob"): # parse response if not response: - ret["msg"] = "no servers answered the published command {0}".format(cmd) + ret["msg"] = "no servers answered the published command {}".format(cmd) return ret elif len(errors) > 0: ret["msg"] = "the following minions return False" @@ -133,7 +131,7 @@ def _talk2modjk(name, lbn, target, action, profile="default", tgt_type="glob"): ret["result"] = False ret["comment"] = ( "the following balancers could not find the " - "worker {0}: {1}".format(name, status["errors"]) + "worker {}: {}".format(name, status["errors"]) ) return ret if not status["wrong_state"]: @@ -142,7 +140,7 @@ def _talk2modjk(name, lbn, target, action, profile="default", tgt_type="glob"): ) return ret else: - ret["comment"] = "the action {0} will be sent to the balancers " "{1}".format( + ret["comment"] = "the action {} will be sent to the balancers " "{}".format( action, status["wrong_state"] ) ret["changes"] = {action: status["wrong_state"]} diff --git a/salt/states/module.py b/salt/states/module.py index 193c97c2396..a196e325273 100644 --- a/salt/states/module.py +++ b/salt/states/module.py @@ -305,7 +305,6 @@ import salt.utils.args import salt.utils.functools import salt.utils.jid from salt.exceptions import SaltInvocationError -from salt.ext.six.moves import range from salt.utils.decorators import with_deprecated diff --git a/salt/states/mongodb_database.py b/salt/states/mongodb_database.py index 1563b5c2407..dfb73fc2675 100644 --- a/salt/states/mongodb_database.py +++ b/salt/states/mongodb_database.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of MongoDB Databases =============================== @@ -8,7 +7,6 @@ Management of MongoDB Databases Only deletion is supported, creation doesn't make sense and can be done using :py:func:`mongodb_user.present `. """ -from __future__ import absolute_import, print_function, unicode_literals # Define the module's virtual name __virtualname__ = "mongodb_database" @@ -48,16 +46,16 @@ def absent(name, user=None, password=None, host=None, port=None, authdb=None): if __salt__["mongodb.db_exists"](name, user, password, host, port, authdb=authdb): if __opts__["test"]: ret["result"] = None - ret["comment"] = ("Database {0} is present and needs to be removed").format( + ret["comment"] = ("Database {} is present and needs to be removed").format( name ) return ret if __salt__["mongodb.db_remove"]( name, user, password, host, port, authdb=authdb ): - ret["comment"] = "Database {0} has been removed".format(name) + ret["comment"] = "Database {} has been removed".format(name) ret["changes"][name] = "Absent" return ret - ret["comment"] = "Database {0} is not present".format(name) + ret["comment"] = "Database {} is not present".format(name) return ret diff --git a/salt/states/mongodb_user.py b/salt/states/mongodb_user.py index 2d684e08964..125032c34fb 100644 --- a/salt/states/mongodb_user.py +++ b/salt/states/mongodb_user.py @@ -1,11 +1,9 @@ -# -*- coding: utf-8 -*- """ Management of MongoDB Users =========================== :depends: - pymongo Python module """ -from __future__ import absolute_import, print_function, unicode_literals # Define the module's virtual name __virtualname__ = "mongodb_user" @@ -83,7 +81,7 @@ def present( "name": name, "changes": {}, "result": True, - "comment": "User {0} is already present".format(name), + "comment": "User {} is already present".format(name), } # setup default empty roles if not provided to preserve previous API interface @@ -95,7 +93,7 @@ def present( port = int(port) except TypeError: ret["result"] = False - ret["comment"] = "Port ({0}) is not an integer.".format(port) + ret["comment"] = "Port ({}) is not an integer.".format(port) return ret # check if user exists @@ -108,7 +106,7 @@ def present( # users= (False, 'not authorized on admin to execute command { usersInfo: "root" }') if not users[0]: ret["result"] = False - ret["comment"] = "Mongo Err: {0}".format(users[1]) + ret["comment"] = "Mongo Err: {}".format(users[1]) return ret # check each user occurrence @@ -154,9 +152,7 @@ def present( if __opts__["test"]: ret["result"] = None - ret["comment"] = ("User {0} is not present and needs to be created").format( - name - ) + ret["comment"] = ("User {} is not present and needs to be created").format(name) return ret # The user is not present, make it! if __salt__["mongodb.user_create"]( @@ -170,10 +166,10 @@ def present( authdb=authdb, roles=roles, ): - ret["comment"] = "User {0} has been created".format(name) + ret["comment"] = "User {} has been created".format(name) ret["changes"][name] = "Present" else: - ret["comment"] = "Failed to create database {0}".format(name) + ret["comment"] = "Failed to create database {}".format(name) ret["result"] = False return ret @@ -216,14 +212,12 @@ def absent( if user_exists is True: if __opts__["test"]: ret["result"] = None - ret["comment"] = ("User {0} is present and needs to be removed").format( - name - ) + ret["comment"] = ("User {} is present and needs to be removed").format(name) return ret if __salt__["mongodb.user_remove"]( name, user, password, host, port, database=database, authdb=authdb ): - ret["comment"] = "User {0} has been removed".format(name) + ret["comment"] = "User {} has been removed".format(name) ret["changes"][name] = "Absent" return ret @@ -235,5 +229,5 @@ def absent( return ret # fallback - ret["comment"] = "User {0} is not present".format(name) + ret["comment"] = "User {} is not present".format(name) return ret diff --git a/salt/states/monit.py b/salt/states/monit.py index cdf2fbc80de..3fd9c7f4f77 100644 --- a/salt/states/monit.py +++ b/salt/states/monit.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Monit state =========== @@ -20,9 +19,6 @@ Manage monit states execution module is available. """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - def __virtual__(): """ @@ -44,20 +40,20 @@ def monitor(name): try: for key, value in result.items(): if "Running" in value[name]: - ret["comment"] = ("{0} is being being monitored.").format(name) + ret["comment"] = ("{} is being being monitored.").format(name) ret["result"] = True else: if __opts__["test"]: - ret["comment"] = "Service {0} is set to be monitored.".format(name) + ret["comment"] = "Service {} is set to be monitored.".format(name) ret["result"] = None return ret __salt__["monit.monitor"](name) - ret["comment"] = ("{0} started to be monitored.").format(name) + ret["comment"] = ("{} started to be monitored.").format(name) ret["changes"][name] = "Running" ret["result"] = True break except KeyError: - ret["comment"] = ("{0} not found in configuration.").format(name) + ret["comment"] = ("{} not found in configuration.").format(name) ret["result"] = False return ret @@ -74,22 +70,20 @@ def unmonitor(name): try: for key, value in result.items(): if "Not monitored" in value[name]: - ret["comment"] = ("{0} is not being monitored.").format(name) + ret["comment"] = ("{} is not being monitored.").format(name) ret["result"] = True else: if __opts__["test"]: - ret["comment"] = "Service {0} is set to be unmonitored.".format( - name - ) + ret["comment"] = "Service {} is set to be unmonitored.".format(name) ret["result"] = None return ret __salt__["monit.unmonitor"](name) - ret["comment"] = ("{0} stopped being monitored.").format(name) + ret["comment"] = ("{} stopped being monitored.").format(name) ret["changes"][name] = "Not monitored" ret["result"] = True break except KeyError: - ret["comment"] = ("{0} not found in configuration.").format(name) + ret["comment"] = ("{} not found in configuration.").format(name) ret["result"] = False return ret diff --git a/salt/states/mssql_database.py b/salt/states/mssql_database.py index b10f749d593..e5c4c3cc67f 100644 --- a/salt/states/mssql_database.py +++ b/salt/states/mssql_database.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of Microsoft SQLServer Databases =========================================== @@ -11,7 +10,6 @@ and manage SQL Server Databases yolo: mssql_database.present """ -from __future__ import absolute_import, print_function, unicode_literals import collections @@ -27,7 +25,7 @@ def __virtual__(): def _normalize_options(options): if type(options) in [dict, collections.OrderedDict]: - return ["{0}={1}".format(k, v) for k, v in options.items()] + return ["{}={}".format(k, v) for k, v in options.items()] if type(options) is list and (not options or type(options[0]) is str): return options # Invalid options @@ -55,13 +53,13 @@ def present(name, containment="NONE", options=None, **kwargs): if __salt__["mssql.db_exists"](name, **kwargs): ret[ "comment" - ] = "Database {0} is already present (Not going to try to set its options)".format( + ] = "Database {} is already present (Not going to try to set its options)".format( name ) return ret if __opts__["test"]: ret["result"] = None - ret["comment"] = "Database {0} is set to be added".format(name) + ret["comment"] = "Database {} is set to be added".format(name) return ret db_created = __salt__["mssql.db_create"]( @@ -74,11 +72,11 @@ def present(name, containment="NONE", options=None, **kwargs): db_created is not True ): # Non-empty strings are also evaluated to True, so we cannot use if not db_created: ret["result"] = False - ret["comment"] += "Database {0} failed to be created: {1}".format( + ret["comment"] += "Database {} failed to be created: {}".format( name, db_created ) return ret - ret["comment"] += "Database {0} has been added".format(name) + ret["comment"] += "Database {} has been added".format(name) ret["changes"][name] = "Present" return ret @@ -93,17 +91,17 @@ def absent(name, **kwargs): ret = {"name": name, "changes": {}, "result": True, "comment": ""} if not __salt__["mssql.db_exists"](name): - ret["comment"] = "Database {0} is not present".format(name) + ret["comment"] = "Database {} is not present".format(name) return ret if __opts__["test"]: ret["result"] = None - ret["comment"] = "Database {0} is set to be removed".format(name) + ret["comment"] = "Database {} is set to be removed".format(name) return ret if __salt__["mssql.db_remove"](name, **kwargs): - ret["comment"] = "Database {0} has been removed".format(name) + ret["comment"] = "Database {} has been removed".format(name) ret["changes"][name] = "Absent" return ret # else: ret["result"] = False - ret["comment"] = "Database {0} failed to be removed".format(name) + ret["comment"] = "Database {} failed to be removed".format(name) return ret diff --git a/salt/states/mssql_login.py b/salt/states/mssql_login.py index f260e11db88..89ace89bcaf 100644 --- a/salt/states/mssql_login.py +++ b/salt/states/mssql_login.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of Microsoft SQLServer Logins ======================================== @@ -12,7 +11,6 @@ and manage SQL Server Logins mssql_login.present - domain: mydomain """ -from __future__ import absolute_import, print_function, unicode_literals import collections @@ -28,7 +26,7 @@ def __virtual__(): def _normalize_options(options): if type(options) in [dict, collections.OrderedDict]: - return ["{0}={1}".format(k, v) for k, v in options.items()] + return ["{}={}".format(k, v) for k, v in options.items()] if type(options) is list and (not options or type(options[0]) is str): return options # Invalid options @@ -71,13 +69,13 @@ def present( if __salt__["mssql.login_exists"](name, domain=domain, **kwargs): ret[ "comment" - ] = "Login {0} is already present (Not going to try to set its password)".format( + ] = "Login {} is already present (Not going to try to set its password)".format( name ) return ret if __opts__["test"]: ret["result"] = None - ret["comment"] = "Login {0} is set to be added".format(name) + ret["comment"] = "Login {} is set to be added".format(name) return ret login_created = __salt__["mssql.login_create"]( @@ -91,9 +89,9 @@ def present( # Non-empty strings are also evaluated to True, so we cannot use if not login_created: if login_created is not True: ret["result"] = False - ret["comment"] = "Login {0} failed to be added: {1}".format(name, login_created) + ret["comment"] = "Login {} failed to be added: {}".format(name, login_created) return ret - ret["comment"] = "Login {0} has been added. ".format(name) + ret["comment"] = "Login {} has been added. ".format(name) ret["changes"][name] = "Present" return ret @@ -108,17 +106,17 @@ def absent(name, **kwargs): ret = {"name": name, "changes": {}, "result": True, "comment": ""} if not __salt__["mssql.login_exists"](name): - ret["comment"] = "Login {0} is not present".format(name) + ret["comment"] = "Login {} is not present".format(name) return ret if __opts__["test"]: ret["result"] = None - ret["comment"] = "Login {0} is set to be removed".format(name) + ret["comment"] = "Login {} is set to be removed".format(name) return ret if __salt__["mssql.login_remove"](name, **kwargs): - ret["comment"] = "Login {0} has been removed".format(name) + ret["comment"] = "Login {} has been removed".format(name) ret["changes"][name] = "Absent" return ret # else: ret["result"] = False - ret["comment"] = "Login {0} failed to be removed".format(name) + ret["comment"] = "Login {} failed to be removed".format(name) return ret diff --git a/salt/states/mssql_role.py b/salt/states/mssql_role.py index 304bc35ef78..2fbdfe172a7 100644 --- a/salt/states/mssql_role.py +++ b/salt/states/mssql_role.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of Microsoft SQLServer Databases =========================================== @@ -11,7 +10,6 @@ and manage SQL Server Roles yolo: mssql_role.present """ -from __future__ import absolute_import, print_function, unicode_literals def __virtual__(): @@ -39,13 +37,13 @@ def present(name, owner=None, grants=None, **kwargs): if __salt__["mssql.role_exists"](name, **kwargs): ret[ "comment" - ] = "Role {0} is already present (Not going to try to set its grants)".format( + ] = "Role {} is already present (Not going to try to set its grants)".format( name ) return ret if __opts__["test"]: ret["result"] = None - ret["comment"] = "Role {0} is set to be added".format(name) + ret["comment"] = "Role {} is set to be added".format(name) return ret role_created = __salt__["mssql.role_create"]( @@ -55,11 +53,9 @@ def present(name, owner=None, grants=None, **kwargs): role_created is not True ): # Non-empty strings are also evaluated to True, so we cannot use if not role_created: ret["result"] = False - ret["comment"] += "Role {0} failed to be created: {1}".format( - name, role_created - ) + ret["comment"] += "Role {} failed to be created: {}".format(name, role_created) return ret - ret["comment"] += "Role {0} has been added".format(name) + ret["comment"] += "Role {} has been added".format(name) ret["changes"][name] = "Present" return ret @@ -74,17 +70,17 @@ def absent(name, **kwargs): ret = {"name": name, "changes": {}, "result": True, "comment": ""} if not __salt__["mssql.role_exists"](name): - ret["comment"] = "Role {0} is not present".format(name) + ret["comment"] = "Role {} is not present".format(name) return ret if __opts__["test"]: ret["result"] = None - ret["comment"] = "Role {0} is set to be removed".format(name) + ret["comment"] = "Role {} is set to be removed".format(name) return ret if __salt__["mssql.role_remove"](name, **kwargs): - ret["comment"] = "Role {0} has been removed".format(name) + ret["comment"] = "Role {} has been removed".format(name) ret["changes"][name] = "Absent" return ret # else: ret["result"] = False - ret["comment"] = "Role {0} failed to be removed".format(name) + ret["comment"] = "Role {} failed to be removed".format(name) return ret diff --git a/salt/states/mssql_user.py b/salt/states/mssql_user.py index cd5d2f4f466..d07c0d56cca 100644 --- a/salt/states/mssql_user.py +++ b/salt/states/mssql_user.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of Microsoft SQLServer Users ======================================= @@ -12,7 +11,6 @@ and manage SQL Server Users mssql_user.present: - database: yolo """ -from __future__ import absolute_import, print_function, unicode_literals import collections @@ -28,7 +26,7 @@ def __virtual__(): def _normalize_options(options): if type(options) in [dict, collections.OrderedDict]: - return ["{0}={1}".format(k, v) for k, v in options.items()] + return ["{}={}".format(k, v) for k, v in options.items()] if type(options) is list and (not options or type(options[0]) is str): return options # Invalid options @@ -70,13 +68,13 @@ def present( if __salt__["mssql.user_exists"](name, domain=domain, database=database, **kwargs): ret[ "comment" - ] = "User {0} is already present (Not going to try to set its roles or options)".format( + ] = "User {} is already present (Not going to try to set its roles or options)".format( name ) return ret if __opts__["test"]: ret["result"] = None - ret["comment"] = "User {0} is set to be added".format(name) + ret["comment"] = "User {} is set to be added".format(name) return ret user_created = __salt__["mssql.user_create"]( @@ -92,9 +90,9 @@ def present( user_created is not True ): # Non-empty strings are also evaluated to True, so we cannot use if not user_created: ret["result"] = False - ret["comment"] += "User {0} failed to be added: {1}".format(name, user_created) + ret["comment"] += "User {} failed to be added: {}".format(name, user_created) return ret - ret["comment"] += "User {0} has been added".format(name) + ret["comment"] += "User {} has been added".format(name) ret["changes"][name] = "Present" return ret @@ -109,17 +107,17 @@ def absent(name, **kwargs): ret = {"name": name, "changes": {}, "result": True, "comment": ""} if not __salt__["mssql.user_exists"](name): - ret["comment"] = "User {0} is not present".format(name) + ret["comment"] = "User {} is not present".format(name) return ret if __opts__["test"]: ret["result"] = None - ret["comment"] = "User {0} is set to be removed".format(name) + ret["comment"] = "User {} is set to be removed".format(name) return ret if __salt__["mssql.user_remove"](name, **kwargs): - ret["comment"] = "User {0} has been removed".format(name) + ret["comment"] = "User {} has been removed".format(name) ret["changes"][name] = "Absent" return ret # else: ret["result"] = False - ret["comment"] = "User {0} failed to be removed".format(name) + ret["comment"] = "User {} failed to be removed".format(name) return ret diff --git a/salt/states/msteams.py b/salt/states/msteams.py index 05736f021e8..f4db009339b 100644 --- a/salt/states/msteams.py +++ b/salt/states/msteams.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Send a message card to Microsoft Teams ====================================== @@ -22,10 +21,7 @@ The hook_url can be specified in the master or minion configuration like below: hook_url: https://outlook.office.com/webhook/837 """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals -# Import Salt libs from salt.exceptions import SaltInvocationError @@ -67,14 +63,14 @@ def post_card(name, message, hook_url=None, title=None, theme_color=None): ret = {"name": name, "changes": {}, "result": False, "comment": ""} if __opts__["test"]: - ret["comment"] = "The following message is to be sent to Teams: {0}".format( + ret["comment"] = "The following message is to be sent to Teams: {}".format( message ) ret["result"] = None return ret if not message: - ret["comment"] = "Teams message is missing: {0}".format(message) + ret["comment"] = "Teams message is missing: {}".format(message) return ret try: @@ -82,13 +78,13 @@ def post_card(name, message, hook_url=None, title=None, theme_color=None): message=message, hook_url=hook_url, title=title, theme_color=theme_color, ) except SaltInvocationError as sie: - ret["comment"] = "Failed to send message ({0}): {1}".format(sie, name) + ret["comment"] = "Failed to send message ({}): {}".format(sie, name) else: if isinstance(result, bool) and result: ret["result"] = True - ret["comment"] = "Sent message: {0}".format(name) + ret["comment"] = "Sent message: {}".format(name) else: - ret["comment"] = "Failed to send message ({0}): {1}".format( + ret["comment"] = "Failed to send message ({}): {}".format( result["message"], name ) diff --git a/salt/states/mysql_grants.py b/salt/states/mysql_grants.py index f365e878cf3..7765d4b445f 100644 --- a/salt/states/mysql_grants.py +++ b/salt/states/mysql_grants.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of MySQL grants (user permissions) ============================================= @@ -45,7 +44,6 @@ instructions. - database: somedb.sometable - user: joe """ -from __future__ import absolute_import, print_function, unicode_literals import sys @@ -191,7 +189,7 @@ def present( if __opts__["test"]: # there is probably better things to make in test mode ret["result"] = None - ret["comment"] = ("MySQL grant {0} is set to be created").format(name) + ret["comment"] = ("MySQL grant {} is set to be created").format(name) return ret if __salt__["mysql.grant_add"]( grant, database, user, host, grant_option, escape, ssl_option, **connection_args @@ -204,7 +202,7 @@ def present( ret["comment"] = ret["comment"].format(grant, database, user, host) err = _get_mysql_error() if err is not None: - ret["comment"] += " ({0})".format(err) + ret["comment"] += " ({})".format(err) ret["result"] = False return ret @@ -246,12 +244,12 @@ def absent( if __opts__["test"]: ret["result"] = None - ret["comment"] = "MySQL grant {0} is set to be " "revoked".format(name) + ret["comment"] = "MySQL grant {} is set to be " "revoked".format(name) return ret if __salt__["mysql.grant_revoke"]( grant, database, user, host, grant_option, **connection_args ): - ret["comment"] = "Grant {0} on {1} for {2}@{3} has been " "revoked".format( + ret["comment"] = "Grant {} on {} for {}@{} has been " "revoked".format( grant, database, user, host ) ret["changes"][name] = "Absent" @@ -260,8 +258,8 @@ def absent( err = _get_mysql_error() if err is not None: ret["comment"] = ( - "Unable to revoke grant {0} on {1} for " - "{2}@{3} ({4})".format(grant, database, user, host, err) + "Unable to revoke grant {} on {} for " + "{}@{} ({})".format(grant, database, user, host, err) ) ret["result"] = False return ret @@ -269,14 +267,14 @@ def absent( err = _get_mysql_error() if err is not None: ret["comment"] = ( - "Unable to determine if grant {0} on {1} for " - "{2}@{3} exists ({4})".format(grant, database, user, host, err) + "Unable to determine if grant {} on {} for " + "{}@{} exists ({})".format(grant, database, user, host, err) ) ret["result"] = False return ret # fallback ret["comment"] = ( - "Grant {0} on {1} to {2}@{3} is not present, so it" " cannot be revoked" + "Grant {} on {} to {}@{} is not present, so it" " cannot be revoked" ).format(grant, database, user, host) return ret diff --git a/salt/states/mysql_user.py b/salt/states/mysql_user.py index f4c1a30c67f..590503166db 100644 --- a/salt/states/mysql_user.py +++ b/salt/states/mysql_user.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of MySQL users ========================= @@ -40,12 +39,9 @@ This state is not able to grant permissions for the user. See :py:mod:`salt.states.mysql_grants` for further instructions. """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import sys -# Import salt libs import salt.utils.data @@ -121,7 +117,7 @@ def present( "name": name, "changes": {}, "result": True, - "comment": "User {0}@{1} is already present".format(name, host), + "comment": "User {}@{} is already present".format(name, host), } passwordless = not any((password, password_hash)) @@ -183,9 +179,7 @@ def present( # The user is present, change the password if __opts__["test"]: - ret["comment"] = "Password for user {0}@{1} is set to be ".format( - name, host - ) + ret["comment"] = "Password for user {}@{} is set to be ".format(name, host) ret["result"] = None if passwordless: ret["comment"] += "cleared" @@ -205,17 +199,17 @@ def present( unix_socket, **connection_args ): - ret["comment"] = "Password for user {0}@{1} has been " "{2}".format( + ret["comment"] = "Password for user {}@{} has been " "{}".format( name, host, "cleared" if passwordless else "changed" ) ret["changes"][name] = "Updated" else: - ret["comment"] = "Failed to {0} password for user " "{1}@{2}".format( + ret["comment"] = "Failed to {} password for user " "{}@{}".format( "clear" if passwordless else "change", name, host ) err = _get_mysql_error() if err is not None: - ret["comment"] += " ({0})".format(err) + ret["comment"] += " ({})".format(err) if passwordless and not salt.utils.data.is_true(allow_passwordless): ret["comment"] += ( ". Note: allow_passwordless must be True " @@ -232,7 +226,7 @@ def present( # The user is not present, make it! if __opts__["test"]: - ret["comment"] = "User {0}@{1} is set to be added".format(name, host) + ret["comment"] = "User {}@{} is set to be added".format(name, host) ret["result"] = None if passwordless: ret["comment"] += " with passwordless login" @@ -252,15 +246,15 @@ def present( auth_plugin=auth_plugin, **connection_args ): - ret["comment"] = "The user {0}@{1} has been added".format(name, host) + ret["comment"] = "The user {}@{} has been added".format(name, host) if passwordless: ret["comment"] += " with passwordless login" ret["changes"][name] = "Present" else: - ret["comment"] = "Failed to create user {0}@{1}".format(name, host) + ret["comment"] = "Failed to create user {}@{}".format(name, host) err = _get_mysql_error() if err is not None: - ret["comment"] += " ({0})".format(err) + ret["comment"] += " ({})".format(err) ret["result"] = False return ret @@ -279,10 +273,10 @@ def absent(name, host="localhost", **connection_args): if __salt__["mysql.user_exists"](name, host, **connection_args): if __opts__["test"]: ret["result"] = None - ret["comment"] = "User {0}@{1} is set to be removed".format(name, host) + ret["comment"] = "User {}@{} is set to be removed".format(name, host) return ret if __salt__["mysql.user_remove"](name, host, **connection_args): - ret["comment"] = "User {0}@{1} has been removed".format(name, host) + ret["comment"] = "User {}@{} has been removed".format(name, host) ret["changes"][name] = "Absent" return ret else: @@ -299,7 +293,7 @@ def absent(name, host="localhost", **connection_args): return ret # fallback - ret["comment"] = ("User {0}@{1} is not present, so it cannot be removed").format( + ret["comment"] = ("User {}@{} is not present, so it cannot be removed").format( name, host ) return ret diff --git a/salt/states/neutron_network.py b/salt/states/neutron_network.py index 86a2942753b..2da8a9b0f1e 100644 --- a/salt/states/neutron_network.py +++ b/salt/states/neutron_network.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of OpenStack Neutron Networks ========================================= @@ -29,7 +28,6 @@ Example States - project: project1 """ -from __future__ import absolute_import, print_function, unicode_literals __virtualname__ = "neutron_network" diff --git a/salt/states/neutron_secgroup.py b/salt/states/neutron_secgroup.py index 6773388701c..7f7218224d9 100644 --- a/salt/states/neutron_secgroup.py +++ b/salt/states/neutron_secgroup.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of OpenStack Neutron Security Groups =============================================== @@ -35,7 +34,6 @@ Example States - project_name: Project1 """ -from __future__ import absolute_import, print_function, unicode_literals __virtualname__ = "neutron_secgroup" diff --git a/salt/states/neutron_secgroup_rule.py b/salt/states/neutron_secgroup_rule.py index 28cf254d5e2..f401ef55e5e 100644 --- a/salt/states/neutron_secgroup_rule.py +++ b/salt/states/neutron_secgroup_rule.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of OpenStack Neutron Security Group Rules ==================================================== @@ -29,7 +28,6 @@ Example States - project_id: 1dcac318a83b4610b7a7f7ba01465548 """ -from __future__ import absolute_import, print_function, unicode_literals __virtualname__ = "neutron_secgroup_rule" diff --git a/salt/states/neutron_subnet.py b/salt/states/neutron_subnet.py index c934c71b1e9..01c795fc21c 100644 --- a/salt/states/neutron_subnet.py +++ b/salt/states/neutron_subnet.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of OpenStack Neutron Subnets ========================================= @@ -47,7 +46,6 @@ Example States - ip_version: 6 """ -from __future__ import absolute_import, print_function, unicode_literals __virtualname__ = "neutron_subnet" diff --git a/salt/states/nexus.py b/salt/states/nexus.py index 6b83b3528a2..a823b0a47d0 100644 --- a/salt/states/nexus.py +++ b/salt/states/nexus.py @@ -1,18 +1,12 @@ -# -*- coding: utf-8 -*- """ This state downloads artifacts from Nexus 3.x. .. versionadded:: 2018.3.0 """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import logging -# Import Salt libs -from salt.ext import six - log = logging.getLogger(__name__) __virtualname__ = "nexus" @@ -95,7 +89,7 @@ def downloaded(name, artifact, target_dir="/tmp", target_file=None): fetch_result = __fetch_from_nexus(artifact, target_dir, target_file) except Exception as exc: # pylint: disable=broad-except ret["result"] = False - ret["comment"] = six.text_type(exc) + ret["comment"] = str(exc) return ret log.debug("fetch_result=%s", fetch_result) diff --git a/salt/states/nfs_export.py b/salt/states/nfs_export.py index 8731bca363f..ad572739d7f 100644 --- a/salt/states/nfs_export.py +++ b/salt/states/nfs_export.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of NFS exports =============================================== @@ -57,7 +56,6 @@ To ensure an NFS export is absent: - name: '/srv/nfs' """ -from __future__ import absolute_import, print_function, unicode_literals import salt.utils.path @@ -142,14 +140,14 @@ def present(name, clients=None, hosts=None, options=None, exports="/etc/exports" if path in old: if old[path] == clients: ret["result"] = True - ret["comment"] = "Export {0} already configured".format(path) + ret["comment"] = "Export {} already configured".format(path) return ret ret["changes"]["new"] = clients ret["changes"]["old"] = old[path] if __opts__["test"]: ret["result"] = None - ret["comment"] = "Export {0} would be changed".format(path) + ret["comment"] = "Export {} would be changed".format(path) return ret __salt__["nfs3.del_export"](exports, path) @@ -159,7 +157,7 @@ def present(name, clients=None, hosts=None, options=None, exports="/etc/exports" ret["changes"]["new"] = clients if __opts__["test"]: ret["result"] = None - ret["comment"] = "Export {0} would be added".format(path) + ret["comment"] = "Export {} would be added".format(path) return ret add_export = __salt__["nfs3.add_export"] @@ -188,7 +186,7 @@ def absent(name, exports="/etc/exports"): old = __salt__["nfs3.list_exports"](exports) if path in old: if __opts__["test"]: - ret["comment"] = "Export {0} would be removed".format(path) + ret["comment"] = "Export {} would be removed".format(path) ret["changes"][path] = old[path] ret["result"] = None return ret @@ -198,12 +196,12 @@ def absent(name, exports="/etc/exports"): if not try_reload["result"]: ret["comment"] = try_reload["stderr"] else: - ret["comment"] = "Export {0} removed".format(path) + ret["comment"] = "Export {} removed".format(path) ret["result"] = try_reload["result"] ret["changes"][path] = old[path] else: - ret["comment"] = "Export {0} already absent".format(path) + ret["comment"] = "Export {} already absent".format(path) ret["result"] = True return ret diff --git a/salt/states/openstack_config.py b/salt/states/openstack_config.py index 28be0eeedb0..e9154d57a4f 100644 --- a/salt/states/openstack_config.py +++ b/salt/states/openstack_config.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage OpenStack configuration file settings. @@ -9,14 +8,9 @@ Manage OpenStack configuration file settings. """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals from salt.exceptions import CommandExecutionError -# Import Salt Libs -from salt.ext import six - def __virtual__(): """ @@ -66,13 +60,13 @@ def present(name, filename, section, value, parameter=None): if __opts__["test"]: ret["result"] = None - ret["comment"] = "Value '{0}' is set to be changed to '{1}'.".format( + ret["comment"] = "Value '{}' is set to be changed to '{}'.".format( old_value, value ) return ret except CommandExecutionError as err: - if not six.text_type(err).lower().startswith("parameter not found:"): + if not str(err).lower().startswith("parameter not found:"): raise __salt__["openstack_config.set"]( @@ -111,7 +105,7 @@ def absent(name, filename, section, parameter=None): filename=filename, section=section, parameter=parameter ) except CommandExecutionError as err: - if six.text_type(err).lower().startswith("parameter not found:"): + if str(err).lower().startswith("parameter not found:"): ret["result"] = True ret["comment"] = "The value is already absent" return ret @@ -119,7 +113,7 @@ def absent(name, filename, section, parameter=None): if __opts__["test"]: ret["result"] = None - ret["comment"] = "Value '{0}' is set to be deleted.".format(old_value) + ret["comment"] = "Value '{}' is set to be deleted.".format(old_value) return ret __salt__["openstack_config.delete"]( diff --git a/salt/states/openvswitch_bridge.py b/salt/states/openvswitch_bridge.py index ae7ca522b0a..654a1cbc1c6 100644 --- a/salt/states/openvswitch_bridge.py +++ b/salt/states/openvswitch_bridge.py @@ -1,11 +1,7 @@ -# -*- coding: utf-8 -*- """ Management of Open vSwitch bridges. """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - def __virtual__(): """ @@ -27,13 +23,13 @@ def present(name): ret = {"name": name, "changes": {}, "result": False, "comment": ""} # Comment and change messages - comment_bridge_created = "Bridge {0} created.".format(name) - comment_bridge_notcreated = "Unable to create bridge: {0}.".format(name) - comment_bridge_exists = "Bridge {0} already exists.".format(name) + comment_bridge_created = "Bridge {} created.".format(name) + comment_bridge_notcreated = "Unable to create bridge: {}.".format(name) + comment_bridge_exists = "Bridge {} already exists.".format(name) changes_bridge_created = { name: { - "old": "Bridge {0} does not exist.".format(name), - "new": "Bridge {0} created".format(name), + "old": "Bridge {} does not exist.".format(name), + "new": "Bridge {} created".format(name), } } @@ -78,13 +74,13 @@ def absent(name): ret = {"name": name, "changes": {}, "result": False, "comment": ""} # Comment and change messages - comment_bridge_deleted = "Bridge {0} deleted.".format(name) - comment_bridge_notdeleted = "Unable to delete bridge: {0}.".format(name) - comment_bridge_notexists = "Bridge {0} does not exist.".format(name) + comment_bridge_deleted = "Bridge {} deleted.".format(name) + comment_bridge_notdeleted = "Unable to delete bridge: {}.".format(name) + comment_bridge_notexists = "Bridge {} does not exist.".format(name) changes_bridge_deleted = { name: { - "old": "Bridge {0} exists.".format(name), - "new": "Bridge {0} deleted.".format(name), + "old": "Bridge {} exists.".format(name), + "new": "Bridge {} deleted.".format(name), } } diff --git a/salt/states/openvswitch_port.py b/salt/states/openvswitch_port.py index f5872fbfeb4..f5c5205ea80 100644 --- a/salt/states/openvswitch_port.py +++ b/salt/states/openvswitch_port.py @@ -1,14 +1,7 @@ -# -*- coding: utf-8 -*- """ Management of Open vSwitch ports. """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - -# Import Salt libs -from salt.ext import six - def __virtual__(): """ @@ -40,8 +33,8 @@ def present( if tunnel_type and tunnel_type not in tunnel_types: raise TypeError( - "The optional type argument must be one of these values: {0}.".format( - six.text_type(tunnel_types) + "The optional type argument must be one of these values: {}.".format( + str(tunnel_types) ) ) @@ -54,29 +47,29 @@ def present( comments = {} - comments["comment_bridge_notexists"] = "Bridge {0} does not exist.".format(bridge) - comments["comment_port_exists"] = "Port {0} already exists.".format(name) - comments["comment_port_created"] = "Port {0} created on bridge {1}.".format( + comments["comment_bridge_notexists"] = "Bridge {} does not exist.".format(bridge) + comments["comment_port_exists"] = "Port {} already exists.".format(name) + comments["comment_port_created"] = "Port {} created on bridge {}.".format( name, bridge ) comments[ "comment_port_notcreated" - ] = "Unable to create port {0} on bridge {1}.".format(name, bridge) + ] = "Unable to create port {} on bridge {}.".format(name, bridge) comments["changes_port_created"] = { name: { - "old": "No port named {0} present.".format(name), + "old": "No port named {} present.".format(name), "new": "Created port {1} on bridge {0}.".format(bridge, name), } } comments[ "comment_port_internal" - ] = "Port {0} already exists, but interface type has been changed to internal.".format( + ] = "Port {} already exists, but interface type has been changed to internal.".format( name ) comments["changes_port_internal"] = {"internal": {"old": False, "new": True}} comments[ "comment_port_internal_not_changed" - ] = "Port {0} already exists, but the interface type could not be changed to internal.".format( + ] = "Port {} already exists, but the interface type could not be changed to internal.".format( name ) @@ -86,25 +79,25 @@ def present( comments["comment_vlan_invalid_id"] = "VLANs id must be between 0 and 4095." comments[ "comment_vlan_invalid_name" - ] = "Could not find network interface {0}.".format(name) + ] = "Could not find network interface {}.".format(name) comments[ "comment_vlan_port_exists" - ] = "Port {0} with access to VLAN {1} already exists on bridge {2}.".format( + ] = "Port {} with access to VLAN {} already exists on bridge {}.".format( name, id, bridge ) comments[ "comment_vlan_created" - ] = "Created port {0} with access to VLAN {1} on bridge {2}.".format( + ] = "Created port {} with access to VLAN {} on bridge {}.".format( name, id, bridge ) comments["comment_vlan_notcreated"] = ( - "Unable to create port {0} with access to VLAN {1} on " - "bridge {2}.".format(name, id, bridge) + "Unable to create port {} with access to VLAN {} on " + "bridge {}.".format(name, id, bridge) ) comments["changes_vlan_created"] = { name: { - "old": "No port named {0} with access to VLAN {1} present on " - "bridge {2} present.".format(name, id, bridge), + "old": "No port named {} with access to VLAN {} present on " + "bridge {} present.".format(name, id, bridge), "new": "Created port {1} with access to VLAN {2} on " "bridge {0}.".format(bridge, name, id), } @@ -115,60 +108,58 @@ def present( "comment_gre_invalid_id" ] = "Id of GRE tunnel must be an unsigned 32-bit integer." comments["comment_gre_interface_exists"] = ( - "GRE tunnel interface {0} with rempte ip {1} and key {2} " - "already exists on bridge {3}.".format(name, remote, id, bridge) + "GRE tunnel interface {} with rempte ip {} and key {} " + "already exists on bridge {}.".format(name, remote, id, bridge) ) comments["comment_gre_created"] = ( - "Created GRE tunnel interface {0} with remote ip {1} and key {2} " - "on bridge {3}.".format(name, remote, id, bridge) + "Created GRE tunnel interface {} with remote ip {} and key {} " + "on bridge {}.".format(name, remote, id, bridge) ) comments["comment_gre_notcreated"] = ( - "Unable to create GRE tunnel interface {0} with remote ip {1} and key {2} " - "on bridge {3}.".format(name, remote, id, bridge) + "Unable to create GRE tunnel interface {} with remote ip {} and key {} " + "on bridge {}.".format(name, remote, id, bridge) ) comments["changes_gre_created"] = { name: { - "old": "No GRE tunnel interface {0} with remote ip {1} and key {2} " - "on bridge {3} present.".format(name, remote, id, bridge), - "new": "Created GRE tunnel interface {0} with remote ip {1} and key {2} " - "on bridge {3}.".format(name, remote, id, bridge), + "old": "No GRE tunnel interface {} with remote ip {} and key {} " + "on bridge {} present.".format(name, remote, id, bridge), + "new": "Created GRE tunnel interface {} with remote ip {} and key {} " + "on bridge {}.".format(name, remote, id, bridge), } } elif tunnel_type == "vxlan": comments["comment_dstport"] = ( - " (dst_port" + six.text_type(dst_port) + ")" - if 0 < dst_port <= 65535 - else "" + " (dst_port" + str(dst_port) + ")" if 0 < dst_port <= 65535 else "" ) comments[ "comment_vxlan_invalid_id" ] = "Id of VXLAN tunnel must be an unsigned 64-bit integer." comments["comment_vxlan_interface_exists"] = ( - "VXLAN tunnel interface {0} with rempte ip {1} and key {2} " - "already exists on bridge {3}{4}.".format( + "VXLAN tunnel interface {} with rempte ip {} and key {} " + "already exists on bridge {}{}.".format( name, remote, id, bridge, comments["comment_dstport"] ) ) comments["comment_vxlan_created"] = ( - "Created VXLAN tunnel interface {0} with remote ip {1} and key {2} " - "on bridge {3}{4}.".format( + "Created VXLAN tunnel interface {} with remote ip {} and key {} " + "on bridge {}{}.".format( name, remote, id, bridge, comments["comment_dstport"] ) ) comments["comment_vxlan_notcreated"] = ( - "Unable to create VXLAN tunnel interface {0} with remote ip {1} and key {2} " - "on bridge {3}{4}.".format( + "Unable to create VXLAN tunnel interface {} with remote ip {} and key {} " + "on bridge {}{}.".format( name, remote, id, bridge, comments["comment_dstport"] ) ) comments["changes_vxlan_created"] = { name: { - "old": "No VXLAN tunnel interface {0} with remote ip {1} and key {2} " - "on bridge {3}{4} present.".format( + "old": "No VXLAN tunnel interface {} with remote ip {} and key {} " + "on bridge {}{} present.".format( name, remote, id, bridge, comments["comment_dstport"] ), - "new": "Created VXLAN tunnel interface {0} with remote ip {1} and key {2} " - "on bridge {3}{4}.".format( + "new": "Created VXLAN tunnel interface {} with remote ip {} and key {} " + "on bridge {}{}.".format( name, remote, id, bridge, comments["comment_dstport"] ), } @@ -204,11 +195,7 @@ def present( ret["comment"] = comments["comment_invalid_ip"] elif interface_options and interface_type and name in port_list: interface_attroptions = ( - '{key="' - + six.text_type(id) - + '", remote_ip="' - + six.text_type(remote) - + '"}' + '{key="' + str(id) + '", remote_ip="' + str(remote) + '"}' ) try: if ( @@ -232,15 +219,13 @@ def present( ret["comment"] = comments["comment_invalid_ip"] elif interface_options and interface_type and name in port_list: opt_port = ( - 'dst_port="' + six.text_type(dst_port) + '", ' - if 0 < dst_port <= 65535 - else "" + 'dst_port="' + str(dst_port) + '", ' if 0 < dst_port <= 65535 else "" ) interface_attroptions = ( '{{{0}key="'.format(opt_port) - + six.text_type(id) + + str(id) + '", remote_ip="' - + six.text_type(remote) + + str(remote) + '"}' ) try: @@ -391,16 +376,16 @@ def absent(name, bridge=None): # Comment and change messages comments = {} - comments["comment_bridge_notexists"] = "Bridge {0} does not exist.".format(bridge) - comments[ - "comment_port_notexists" - ] = "Port {0} does not exist on bridge {1}.".format(name, bridge) - comments["comment_port_deleted"] = "Port {0} deleted.".format(name) - comments["comment_port_notdeleted"] = "Unable to delete port {0}.".format(name) + comments["comment_bridge_notexists"] = "Bridge {} does not exist.".format(bridge) + comments["comment_port_notexists"] = "Port {} does not exist on bridge {}.".format( + name, bridge + ) + comments["comment_port_deleted"] = "Port {} deleted.".format(name) + comments["comment_port_notdeleted"] = "Unable to delete port {}.".format(name) comments["changes_port_deleted"] = { name: { - "old": "Port named {0} may exist.".format(name), - "new": "Deleted port {0}.".format(name), + "old": "Port named {} may exist.".format(name), + "new": "Deleted port {}.".format(name), } } diff --git a/salt/states/opsgenie.py b/salt/states/opsgenie.py index 1bc9fd008d4..c0e9790f43d 100644 --- a/salt/states/opsgenie.py +++ b/salt/states/opsgenie.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Create/Close an alert in OpsGenie ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -32,13 +31,10 @@ during state runs. - disk: used_space """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import inspect import logging -# Import Salt libs import salt.exceptions log = logging.getLogger(__name__) @@ -80,8 +76,8 @@ def create_alert(name=None, api_key=None, reason=None, action_type="Create"): if __opts__["test"] is True: ret["comment"] = ( - "Test: {0} alert request will be processed " - 'using the API Key="{1}".'.format(action_type, api_key) + "Test: {} alert request will be processed " + 'using the API Key="{}".'.format(action_type, api_key) ) # Return ``None`` when running with ``test=true``. @@ -100,8 +96,8 @@ def create_alert(name=None, api_key=None, reason=None, action_type="Create"): response_status_code, ) ret["comment"] = ( - "Test: {0} alert request will be processed" - ' using the API Key="{1}".'.format(action_type, api_key) + "Test: {} alert request will be processed" + ' using the API Key="{}".'.format(action_type, api_key) ) ret["result"] = True else: diff --git a/salt/states/pagerduty.py b/salt/states/pagerduty.py index 3dc8f25715a..e4eace4524f 100644 --- a/salt/states/pagerduty.py +++ b/salt/states/pagerduty.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Create an Event in PagerDuty ============================ @@ -18,9 +17,6 @@ runs. - profile: my-pagerduty-account """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - def __virtual__(): """ @@ -61,11 +57,11 @@ def create_event(name, details, service_key, profile): """ ret = {"name": name, "changes": {}, "result": None, "comment": ""} if __opts__["test"]: - ret["comment"] = "Need to create event: {0}".format(name) + ret["comment"] = "Need to create event: {}".format(name) return ret __salt__["pagerduty.create_event"]( description=name, details=details, service_key=service_key, profile=profile, ) ret["result"] = True - ret["comment"] = "Created event: {0}".format(name) + ret["comment"] = "Created event: {}".format(name) return ret diff --git a/salt/states/pagerduty_escalation_policy.py b/salt/states/pagerduty_escalation_policy.py index ae18c07ed5d..44e663e4ea3 100644 --- a/salt/states/pagerduty_escalation_policy.py +++ b/salt/states/pagerduty_escalation_policy.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage PagerDuty escalation policies. @@ -35,9 +34,6 @@ For example: escalation_delay_in_minutes: 15 """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - def __virtual__(): """ @@ -100,7 +96,7 @@ def present(profile="pagerduty", subdomain=None, api_key=None, **kwargs): if schedule: target_id = schedule["schedule"]["id"] if target_id is None: - raise Exception("unidentified target: {0}".format(target)) + raise Exception("unidentified target: {}".format(target)) target["id"] = target_id r = __salt__["pagerduty_util.resource_present"]( @@ -147,7 +143,7 @@ def _diff(state_data, resource_object): else: resource_value = resource_object[k] if v != resource_value: - objects_differ = "{0} {1} {2}".format(k, v, resource_value) + objects_differ = "{} {} {}".format(k, v, resource_value) break if objects_differ: @@ -160,9 +156,9 @@ def _escalation_rules_to_string(escalation_rules): "convert escalation_rules dict to a string for comparison" result = "" for rule in escalation_rules: - result += "escalation_delay_in_minutes: {0} ".format( + result += "escalation_delay_in_minutes: {} ".format( rule["escalation_delay_in_minutes"] ) for target in rule["targets"]: - result += "{0}:{1} ".format(target["type"], target["id"]) + result += "{}:{} ".format(target["type"], target["id"]) return result diff --git a/salt/states/pagerduty_schedule.py b/salt/states/pagerduty_schedule.py index 21b2daa36a0..75f705f6086 100644 --- a/salt/states/pagerduty_schedule.py +++ b/salt/states/pagerduty_schedule.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage PagerDuty schedules. @@ -34,9 +33,6 @@ Example: """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - def __virtual__(): """ @@ -69,7 +65,7 @@ def present(profile="pagerduty", subdomain=None, api_key=None, **kwargs): api_key=api_key, ) if u is None: - raise Exception("unknown user: {0}".format(user)) + raise Exception("unknown user: {}".format(user)) user["user"]["id"] = u["id"] r = __salt__["pagerduty_util.resource_present"]( "schedules", ["name", "id"], _diff, profile, subdomain, api_key, **kwargs @@ -103,7 +99,7 @@ def _diff(state_data, resource_object): if k == "schedule_layers": continue if v != resource_object["schedule"][k]: - objects_differ = "{0} {1} {2}".format(k, v, resource_object["schedule"][k]) + objects_differ = "{} {} {}".format(k, v, resource_object["schedule"][k]) break # check schedule_layers @@ -117,7 +113,7 @@ def _diff(state_data, resource_object): found = True break if not found: - objects_differ = "layer {0} missing".format(layer["name"]) + objects_differ = "layer {} missing".format(layer["name"]) break # set the id, so that we will update this layer instead of creating a new one layer["id"] = resource_layer["id"] @@ -128,7 +124,7 @@ def _diff(state_data, resource_object): if k == "start": continue if v != resource_layer[k]: - objects_differ = "layer {0} key {1} {2} != {3}".format( + objects_differ = "layer {} key {} {} != {}".format( layer["name"], k, v, resource_layer[k] ) break @@ -136,7 +132,7 @@ def _diff(state_data, resource_object): break # compare layer['users'] if len(layer["users"]) != len(resource_layer["users"]): - objects_differ = "num users in layer {0} {1} != {2}".format( + objects_differ = "num users in layer {} {} != {}".format( layer["name"], len(layer["users"]), len(resource_layer["users"]) ) break @@ -150,12 +146,12 @@ def _diff(state_data, resource_object): found = True break if not found: - objects_differ = "layer {0} no one with member_order {1}".format( + objects_differ = "layer {} no one with member_order {}".format( layer["name"], user1["member_order"] ) break if user1["user"]["id"] != user2["user"]["id"]: - objects_differ = "layer {0} user at member_order {1} {2} != {3}".format( + objects_differ = "layer {} user at member_order {} {} != {}".format( layer["name"], user1["member_order"], user1["user"]["id"], diff --git a/salt/states/pagerduty_service.py b/salt/states/pagerduty_service.py index 99b5aee7f9a..f615aff7a7b 100644 --- a/salt/states/pagerduty_service.py +++ b/salt/states/pagerduty_service.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage PagerDuty services @@ -16,9 +15,6 @@ For example: """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - def __virtual__(): """ @@ -114,7 +110,7 @@ def _diff(state_data, resource_object): else: resource_value = resource_object[k] if v != resource_value: - objects_differ = "{0} {1} {2}".format(k, v, resource_value) + objects_differ = "{} {} {}".format(k, v, resource_value) break if objects_differ: diff --git a/salt/states/pagerduty_user.py b/salt/states/pagerduty_user.py index a85d2615b1f..dc8e74b3168 100644 --- a/salt/states/pagerduty_user.py +++ b/salt/states/pagerduty_user.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage PagerDuty users. @@ -14,9 +13,6 @@ Example: """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - def __virtual__(): """ diff --git a/salt/states/pbm.py b/salt/states/pbm.py index c2c8b6d4a88..a00f0ef7b1a 100644 --- a/salt/states/pbm.py +++ b/salt/states/pbm.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manages VMware storage policies (called pbm because the vCenter endpoint is /pbm) @@ -91,14 +90,11 @@ PyVmomi can be installed via pip: information. """ -# Import Python Libs -from __future__ import absolute_import import copy import logging import sys -# Import Salt Libs from salt.exceptions import ArgumentValueError, CommandExecutionError from salt.utils.dictdiffer import recursive_diff from salt.utils.listdiffer import list_diff @@ -155,13 +151,13 @@ def default_vsan_policy_configured(name, policy): # It's going to make the whole thing much easier policy_copy = copy.deepcopy(policy) proxy_type = __salt__["vsphere.get_proxy_type"]() - log.trace("proxy_type = {0}".format(proxy_type)) + log.trace("proxy_type = {}".format(proxy_type)) # All allowed proxies have a shim execution module with the same # name which implementes a get_details function # All allowed proxies have a vcenter detail - vcenter = __salt__["{0}.get_details".format(proxy_type)]()["vcenter"] - log.info("Running {0} on vCenter " "'{1}'".format(name, vcenter)) - log.trace("policy = {0}".format(policy)) + vcenter = __salt__["{}.get_details".format(proxy_type)]()["vcenter"] + log.info("Running {} on vCenter " "'{}'".format(name, vcenter)) + log.trace("policy = {}".format(policy)) changes_required = False ret = {"name": name, "changes": {}, "result": None, "comment": None} comments = [] @@ -173,7 +169,7 @@ def default_vsan_policy_configured(name, policy): # TODO policy schema validation si = __salt__["vsphere.get_service_instance_via_proxy"]() current_policy = __salt__["vsphere.list_default_vsan_policy"](si) - log.trace("current_policy = {0}".format(current_policy)) + log.trace("current_policy = {}".format(current_policy)) # Building all diffs between the current and expected policy # XXX We simplify the comparison by assuming we have at most 1 # sub_profile @@ -222,7 +218,7 @@ def default_vsan_policy_configured(name, policy): if subprofile_differ.diffs: str_changes.extend( [ - " {0}".format(change) + " {}".format(change) for change in subprofile_differ.changes_str.split("\n") ] ) @@ -230,15 +226,15 @@ def default_vsan_policy_configured(name, policy): str_changes.append(" capabilities:") str_changes.extend( [ - " {0}".format(change) + " {}".format(change) for change in capabilities_differ.changes_str2.split( "\n" ) ] ) comments.append( - "State {0} will update the default VSAN policy on " - "vCenter '{1}':\n{2}" + "State {} will update the default VSAN policy on " + "vCenter '{}':\n{}" "".format(name, vcenter, "\n".join(str_changes)) ) else: @@ -248,8 +244,7 @@ def default_vsan_policy_configured(name, policy): service_instance=si, ) comments.append( - "Updated the default VSAN policy in vCenter " - "'{0}'".format(vcenter) + "Updated the default VSAN policy in vCenter " "'{}'".format(vcenter) ) log.info(comments[-1]) @@ -292,7 +287,7 @@ def default_vsan_policy_configured(name, policy): { "comment": ( "Default VSAN policy in vCenter " - "'{0}' is correctly configured. " + "'{}' is correctly configured. " "Nothing to be done.".format(vcenter) ), "result": True, @@ -320,21 +315,21 @@ def storage_policies_configured(name, policies): changes = [] changes_required = False ret = {"name": name, "changes": {}, "result": None, "comment": None} - log.trace("policies = {0}".format(policies)) + log.trace("policies = {}".format(policies)) si = None try: proxy_type = __salt__["vsphere.get_proxy_type"]() - log.trace("proxy_type = {0}".format(proxy_type)) + log.trace("proxy_type = {}".format(proxy_type)) # All allowed proxies have a shim execution module with the same # name which implementes a get_details function # All allowed proxies have a vcenter detail - vcenter = __salt__["{0}.get_details".format(proxy_type)]()["vcenter"] - log.info("Running state '{0}' on vCenter " "'{1}'".format(name, vcenter)) + vcenter = __salt__["{}.get_details".format(proxy_type)]()["vcenter"] + log.info("Running state '{}' on vCenter " "'{}'".format(name, vcenter)) si = __salt__["vsphere.get_service_instance_via_proxy"]() current_policies = __salt__["vsphere.list_storage_policies"]( policy_names=[policy["name"] for policy in policies], service_instance=si ) - log.trace("current_policies = {0}".format(current_policies)) + log.trace("current_policies = {}".format(current_policies)) # TODO Refactor when recurse_differ supports list_differ # It's going to make the whole thing much easier for policy in policies: @@ -348,8 +343,8 @@ def storage_policies_configured(name, policies): changes_required = True if __opts__["test"]: comments.append( - "State {0} will create the storage policy " - "'{1}' on vCenter '{2}'" + "State {} will create the storage policy " + "'{}' on vCenter '{}'" "".format(name, policy["name"], vcenter) ) else: @@ -357,8 +352,8 @@ def storage_policies_configured(name, policies): policy["name"], policy, service_instance=si ) comments.append( - "Created storage policy '{0}' on " - "vCenter '{1}'".format(policy["name"], vcenter) + "Created storage policy '{}' on " + "vCenter '{}'".format(policy["name"], vcenter) ) changes.append({"new": policy, "old": None}) log.trace(comments[-1]) @@ -409,7 +404,7 @@ def storage_policies_configured(name, policies): if subprofile_differ.diffs: str_changes.extend( [ - " {0}".format(change) + " {}".format(change) for change in subprofile_differ.changes_str.split( "\n" ) @@ -419,15 +414,15 @@ def storage_policies_configured(name, policies): str_changes.append(" capabilities:") str_changes.extend( [ - " {0}".format(change) + " {}".format(change) for change in capabilities_differ.changes_str2.split( "\n" ) ] ) comments.append( - "State {0} will update the storage policy '{1}'" - " on vCenter '{2}':\n{3}" + "State {} will update the storage policy '{}'" + " on vCenter '{}':\n{}" "".format(name, policy["name"], vcenter, "\n".join(str_changes)) ) else: @@ -437,8 +432,8 @@ def storage_policies_configured(name, policies): service_instance=si, ) comments.append( - "Updated the storage policy '{0}'" - "in vCenter '{1}'" + "Updated the storage policy '{}'" + "in vCenter '{}'" "".format(policy["name"], vcenter) ) log.info(comments[-1]) @@ -466,12 +461,12 @@ def storage_policies_configured(name, policies): else: # No diffs found - no updates required comments.append( - "Storage policy '{0}' is up to date. " + "Storage policy '{}' is up to date. " "Nothing to be done.".format(policy["name"]) ) __salt__["vsphere.disconnect"](si) except CommandExecutionError as exc: - log.error("Error: {0}".format(exc)) + log.error("Error: {}".format(exc)) if si: __salt__["vsphere.disconnect"](si) if not __opts__["test"]: @@ -486,7 +481,7 @@ def storage_policies_configured(name, policies): { "comment": ( "All storage policy in vCenter " - "'{0}' is correctly configured. " + "'{}' is correctly configured. " "Nothing to be done.".format(vcenter) ), "result": True, @@ -514,7 +509,7 @@ def default_storage_policy_assigned(name, policy, datastore): Name of datastore """ log.info( - "Running state {0} for policy '{1}', datastore '{2}'." + "Running state {} for policy '{}', datastore '{}'." "".format(name, policy, datastore) ) changes = {} @@ -528,8 +523,8 @@ def default_storage_policy_assigned(name, policy, datastore): ) if existing_policy["name"] == policy: comment = ( - "Storage policy '{0}' is already assigned to " - "datastore '{1}'. Nothing to be done." + "Storage policy '{}' is already assigned to " + "datastore '{}'. Nothing to be done." "".format(policy, datastore) ) else: @@ -542,14 +537,14 @@ def default_storage_policy_assigned(name, policy, datastore): } if __opts__["test"]: comment = ( - "State {0} will assign storage policy '{1}' to " "datastore '{2}'." + "State {} will assign storage policy '{}' to " "datastore '{}'." ).format(name, policy, datastore) else: __salt__["vsphere.assign_default_storage_policy_to_datastore"]( policy=policy, datastore=datastore, service_instance=si ) comment = ( - "Storage policy '{0} was assigned to datastore " "'{1}'." + "Storage policy '{} was assigned to datastore " "'{}'." ).format(policy, name) log.info(comment) except CommandExecutionError as exc: diff --git a/salt/states/pcs.py b/salt/states/pcs.py index 18a59e44fb6..c28e1ec554f 100644 --- a/salt/states/pcs.py +++ b/salt/states/pcs.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of Pacemaker/Corosync clusters with PCS ================================================== @@ -162,20 +161,14 @@ Create a cluster from scratch: .. versionadded:: 2016.3.0 """ -from __future__ import absolute_import, print_function, unicode_literals -# Import Python libs import logging import os -# Import Salt libs import salt.utils.files import salt.utils.path import salt.utils.stringutils -# Import 3rd-party libs -from salt.ext import six - log = logging.getLogger(__name__) @@ -222,7 +215,7 @@ def _get_cibfile(cibname): """ Get the full path of a cached CIB-file with the name of the CIB """ - cibfile = os.path.join(_get_cibpath(), "{0}.{1}".format(cibname, "cib")) + cibfile = os.path.join(_get_cibpath(), "{}.{}".format(cibname, "cib")) log.trace("cibfile: %s", cibfile) return cibfile @@ -231,7 +224,7 @@ def _get_cibfile_tmp(cibname): """ Get the full path of a temporary CIB-file with the name of the CIB """ - cibfile_tmp = "{0}.tmp".format(_get_cibfile(cibname)) + cibfile_tmp = "{}.tmp".format(_get_cibfile(cibname)) log.trace("cibfile_tmp: %s", cibfile_tmp) return cibfile_tmp @@ -240,7 +233,7 @@ def _get_cibfile_cksum(cibname): """ Get the full path of the file containing a checksum of a CIB-file with the name of the CIB """ - cibfile_cksum = "{0}.cksum".format(_get_cibfile(cibname)) + cibfile_cksum = "{}.cksum".format(_get_cibfile(cibname)) log.trace("cibfile_cksum: %s", cibfile_cksum) return cibfile_cksum @@ -279,7 +272,7 @@ def _item_present( item_create_required = True cibfile = None - if isinstance(cibname, six.string_types): + if isinstance(cibname, str): cibfile = _get_cibfile(cibname) if not isinstance(extra_args, (list, tuple)): @@ -324,7 +317,7 @@ def _item_present( # constraints match on '(id:)' elif item in ["constraint"]: for line in is_existing["stdout"].splitlines(): - if "(id:{0})".format(item_id) in line: + if "(id:{})".format(item_id) in line: item_create_required = False # item_id was provided, @@ -334,15 +327,15 @@ def _item_present( item_create_required = False if not item_create_required: - ret["comment"] += "{0} {1} ({2}) is already existing\n".format( - six.text_type(item), six.text_type(item_id), six.text_type(item_type) + ret["comment"] += "{} {} ({}) is already existing\n".format( + str(item), str(item_id), str(item_type) ) return ret if __opts__["test"]: ret["result"] = None - ret["comment"] += "{0} {1} ({2}) is set to be created\n".format( - six.text_type(item), six.text_type(item_id), six.text_type(item_type) + ret["comment"] += "{} {} ({}) is set to be created\n".format( + str(item), str(item_id), str(item_type) ) return ret @@ -358,11 +351,11 @@ def _item_present( log.trace("Output of pcs.item_create: %s", item_create) if item_create["retcode"] in [0]: - ret["comment"] += "Created {0} {1} ({2})\n".format(item, item_id, item_type) - ret["changes"].update({item_id: {"old": "", "new": six.text_type(item_id)}}) + ret["comment"] += "Created {} {} ({})\n".format(item, item_id, item_type) + ret["changes"].update({item_id: {"old": "", "new": str(item_id)}}) else: ret["result"] = False - ret["comment"] += "Failed to create {0} {1} ({2})\n".format( + ret["comment"] += "Failed to create {} {} ({})\n".format( item, item_id, item_type ) @@ -416,11 +409,11 @@ def auth(name, nodes, pcsuser="hacluster", pcspasswd="hacluster", extra_args=Non for node in nodes: if node in authorized_dict and authorized_dict[node] == "Already authorized": - ret["comment"] += "Node {0} is already authorized\n".format(node) + ret["comment"] += "Node {} is already authorized\n".format(node) else: auth_required = True if __opts__["test"]: - ret["comment"] += "Node is set to authorize: {0}\n".format(node) + ret["comment"] += "Node is set to authorize: {}\n".format(node) if not auth_required: return ret @@ -448,18 +441,18 @@ def auth(name, nodes, pcsuser="hacluster", pcspasswd="hacluster", extra_args=Non for node in nodes: if node in authorize_dict and authorize_dict[node] == "Authorized": - ret["comment"] += "Authorized {0}\n".format(node) + ret["comment"] += "Authorized {}\n".format(node) ret["changes"].update({node: {"old": "", "new": "Authorized"}}) else: ret["result"] = False if node in authorized_dict: ret[ "comment" - ] += "Authorization check for node {0} returned: {1}\n".format( + ] += "Authorization check for node {} returned: {}\n".format( node, authorized_dict[node] ) if node in authorize_dict: - ret["comment"] += "Failed to authorize {0} with error {1}\n".format( + ret["comment"] += "Failed to authorize {} with error {}\n".format( node, authorize_dict[node] ) @@ -508,13 +501,13 @@ def cluster_setup(name, nodes, pcsclustername="pcscluster", extra_args=None): value = line.split(":")[1].strip() if key in ["Cluster Name"]: if value in [pcsclustername]: - ret["comment"] += "Cluster {0} is already set up\n".format( + ret["comment"] += "Cluster {} is already set up\n".format( pcsclustername ) else: setup_required = True if __opts__["test"]: - ret["comment"] += "Cluster {0} is set to set up\n".format( + ret["comment"] += "Cluster {} is set to set up\n".format( pcsclustername ) @@ -547,16 +540,14 @@ def cluster_setup(name, nodes, pcsclustername="pcscluster", extra_args=None): for node in nodes: if node in setup_dict and setup_dict[node] in ["Succeeded", "Success"]: - ret["comment"] += "Set up {0}\n".format(node) + ret["comment"] += "Set up {}\n".format(node) ret["changes"].update({node: {"old": "", "new": "Setup"}}) else: ret["result"] = False - ret["comment"] += "Failed to setup {0}\n".format(node) + ret["comment"] += "Failed to setup {}\n".format(node) if node in setup_dict: - ret["comment"] += "{0}: setup_dict: {1}\n".format( - node, setup_dict[node] - ) - ret["comment"] += six.text_type(setup) + ret["comment"] += "{}: setup_dict: {}\n".format(node, setup_dict[node]) + ret["comment"] += str(setup) log.trace("ret: %s", ret) @@ -609,7 +600,7 @@ def cluster_node_present(name, node, extra_args=None): node_add_required = False ret[ "comment" - ] += "Node {0} is already member of the cluster\n".format(node) + ] += "Node {} is already member of the cluster\n".format(node) else: current_nodes += value.split() @@ -618,7 +609,7 @@ def cluster_node_present(name, node, extra_args=None): if __opts__["test"]: ret["result"] = None - ret["comment"] += "Node {0} is set to be added to the cluster\n".format(node) + ret["comment"] += "Node {} is set to be added to the cluster\n".format(node) return ret if not isinstance(extra_args, (list, tuple)): @@ -642,29 +633,29 @@ def cluster_node_present(name, node, extra_args=None): if current_node in node_add_dict: if node_add_dict[current_node] not in ["Corosync updated"]: ret["result"] = False - ret["comment"] += "Failed to update corosync.conf on node {0}\n".format( + ret["comment"] += "Failed to update corosync.conf on node {}\n".format( current_node ) - ret["comment"] += "{0}: node_add_dict: {1}\n".format( + ret["comment"] += "{}: node_add_dict: {}\n".format( current_node, node_add_dict[current_node] ) else: ret["result"] = False - ret["comment"] += "Failed to update corosync.conf on node {0}\n".format( + ret["comment"] += "Failed to update corosync.conf on node {}\n".format( current_node ) if node in node_add_dict and node_add_dict[node] in ["Succeeded", "Success"]: - ret["comment"] += "Added node {0}\n".format(node) + ret["comment"] += "Added node {}\n".format(node) ret["changes"].update({node: {"old": "", "new": "Added"}}) else: ret["result"] = False - ret["comment"] += "Failed to add node{0}\n".format(node) + ret["comment"] += "Failed to add node{}\n".format(node) if node in node_add_dict: - ret["comment"] += "{0}: node_add_dict: {1}\n".format( + ret["comment"] += "{}: node_add_dict: {}\n".format( node, node_add_dict[node] ) - ret["comment"] += six.text_type(node_add) + ret["comment"] += str(node_add) log.trace("ret: %s", ret) @@ -729,7 +720,7 @@ def cib_present(name, cibname, scope=None, extra_args=None): ret["comment"] += "Failed to get live CIB\n" return ret - cib_hash_live = "{0}:{1}".format( + cib_hash_live = "{}:{}".format( cib_hash_form, __salt__["file.get_hash"](path=cibfile_tmp, form=cib_hash_form) ) log.trace("cib_hash_live: %s", cib_hash_live) @@ -751,10 +742,10 @@ def cib_present(name, cibname, scope=None, extra_args=None): if not cib_create_required: __salt__["file.remove"](cibfile_tmp) - ret["comment"] += "CIB {0} is already equal to the live CIB\n".format(cibname) + ret["comment"] += "CIB {} is already equal to the live CIB\n".format(cibname) if not cib_cksum_required: - ret["comment"] += "CIB {0} checksum is correct\n".format(cibname) + ret["comment"] += "CIB {} checksum is correct\n".format(cibname) if not cib_required: return ret @@ -763,9 +754,9 @@ def cib_present(name, cibname, scope=None, extra_args=None): __salt__["file.remove"](cibfile_tmp) ret["result"] = None if cib_create_required: - ret["comment"] += "CIB {0} is set to be created/updated\n".format(cibname) + ret["comment"] += "CIB {} is set to be created/updated\n".format(cibname) if cib_cksum_required: - ret["comment"] += "CIB {0} checksum is set to be created/updated\n".format( + ret["comment"] += "CIB {} checksum is set to be created/updated\n".format( cibname ) return ret @@ -774,23 +765,23 @@ def cib_present(name, cibname, scope=None, extra_args=None): __salt__["file.move"](cibfile_tmp, cibfile) if __salt__["file.check_hash"](path=cibfile, file_hash=cib_hash_live): - ret["comment"] += "Created/updated CIB {0}\n".format(cibname) + ret["comment"] += "Created/updated CIB {}\n".format(cibname) ret["changes"].update({"cibfile": cibfile}) else: ret["result"] = False - ret["comment"] += "Failed to create/update CIB {0}\n".format(cibname) + ret["comment"] += "Failed to create/update CIB {}\n".format(cibname) if cib_cksum_required: _file_write(cibfile_cksum, cib_hash_live) if _file_read(cibfile_cksum) in [cib_hash_live]: - ret["comment"] += "Created/updated checksum {0} of CIB {1}\n".format( + ret["comment"] += "Created/updated checksum {} of CIB {}\n".format( cib_hash_live, cibname ) ret["changes"].update({"cibcksum": cib_hash_live}) else: ret["result"] = False - ret["comment"] += "Failed to create/update checksum {0} CIB {1}\n".format( + ret["comment"] += "Failed to create/update checksum {} CIB {}\n".format( cib_hash_live, cibname ) @@ -839,10 +830,10 @@ def cib_pushed(name, cibname, scope=None, extra_args=None): if not os.path.exists(cibfile): ret["result"] = False - ret["comment"] += "CIB-file {0} does not exist\n".format(cibfile) + ret["comment"] += "CIB-file {} does not exist\n".format(cibfile) return ret - cib_hash_cibfile = "{0}:{1}".format( + cib_hash_cibfile = "{}:{}".format( cib_hash_form, __salt__["file.get_hash"](path=cibfile, form=cib_hash_form) ) log.trace("cib_hash_cibfile: %s", cib_hash_cibfile) @@ -853,14 +844,14 @@ def cib_pushed(name, cibname, scope=None, extra_args=None): if not cib_push_required: ret[ "comment" - ] += "CIB {0} is not changed since creation through pcs.cib_present\n".format( + ] += "CIB {} is not changed since creation through pcs.cib_present\n".format( cibname ) return ret if __opts__["test"]: ret["result"] = None - ret["comment"] += "CIB {0} is set to be pushed as the new live CIB\n".format( + ret["comment"] += "CIB {} is set to be pushed as the new live CIB\n".format( cibname ) return ret @@ -871,11 +862,11 @@ def cib_pushed(name, cibname, scope=None, extra_args=None): log.trace("Output of pcs.cib_push: %s", cib_push) if cib_push["retcode"] in [0]: - ret["comment"] += "Pushed CIB {0}\n".format(cibname) + ret["comment"] += "Pushed CIB {}\n".format(cibname) ret["changes"].update({"cibfile_pushed": cibfile}) else: ret["result"] = False - ret["comment"] += "Failed to push CIB {0}\n".format(cibname) + ret["comment"] += "Failed to push CIB {}\n".format(cibname) log.trace("ret: %s", ret) @@ -913,7 +904,7 @@ def prop_has_value(name, prop, value, extra_args=None, cibname=None): return _item_present( name=name, item="property", - item_id="{0}={1}".format(prop, value), + item_id="{}={}".format(prop, value), item_type=None, create="set", extra_args=extra_args, @@ -953,7 +944,7 @@ def resource_defaults_to(name, default, value, extra_args=None, cibname=None): return _item_present( name=name, item="resource", - item_id="{0}={1}".format(default, value), + item_id="{}={}".format(default, value), item_type=None, show="defaults", create="defaults", @@ -994,7 +985,7 @@ def resource_op_defaults_to(name, op_default, value, extra_args=None, cibname=No return _item_present( name=name, item="resource", - item_id="{0}={1}".format(op_default, value), + item_id="{}={}".format(op_default, value), item_type=None, show=["op", "defaults"], create=["op", "defaults"], diff --git a/salt/states/pdbedit.py b/salt/states/pdbedit.py index 00833cb1fea..a01e5ef3775 100644 --- a/salt/states/pdbedit.py +++ b/salt/states/pdbedit.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage accounts in Samba's passdb using pdbedit @@ -21,12 +20,9 @@ Manage accounts in Samba's passdb using pdbedit - drive: 'X:' - homedir: '\\\\serenity\\mechanic\\profile' """ -from __future__ import absolute_import, print_function, unicode_literals -# Import Python libs import logging -# Import Salt libs import salt.utils.data log = logging.getLogger(__name__) @@ -44,7 +40,7 @@ def __virtual__(): else: return ( False, - "{0} state module can only be loaded when the pdbedit module is available".format( + "{} state module can only be loaded when the pdbedit module is available".format( __virtualname__ ), ) diff --git a/salt/states/pecl.py b/salt/states/pecl.py index e224f016a80..a69a2ca1cb1 100644 --- a/salt/states/pecl.py +++ b/salt/states/pecl.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Installation of PHP Extensions Using pecl ========================================= @@ -18,10 +17,6 @@ requisite to a pkg.installed state for the package which provides pecl - require: - pkg: php-pear """ -from __future__ import absolute_import, print_function, unicode_literals - -# Import salt libs -from salt.ext import six def __virtual__(): @@ -60,8 +55,8 @@ def installed( The pecl extension state to install """ # Check to see if we have a designated version - if not isinstance(version, six.string_types) and version is not None: - version = six.text_type(version) + if not isinstance(version, str) and version is not None: + version = str(version) ret = {"name": name, "result": None, "comment": "", "changes": {}} @@ -78,25 +73,25 @@ def installed( version is None or version in installed_pecls[package] ) and preferred_state in installed_pecls[package]: ret["result"] = True - ret["comment"] = "Pecl extension {0} is already installed.".format(name) + ret["comment"] = "Pecl extension {} is already installed.".format(name) return ret if version is not None: # Modify the name to include the version and proceed. - name = "{0}-{1}".format(name, version) + name = "{}-{}".format(name, version) if __opts__["test"]: - ret["comment"] = "Pecl extension {0} would have been installed".format(name) + ret["comment"] = "Pecl extension {} would have been installed".format(name) return ret if __salt__["pecl.install"]( name, defaults=defaults, force=force, preferred_state=preferred_state ): ret["result"] = True ret["changes"][name] = "Installed" - ret["comment"] = "Pecl extension {0} was successfully installed".format(name) + ret["comment"] = "Pecl extension {} was successfully installed".format(name) else: ret["result"] = False - ret["comment"] = "Could not install pecl extension {0}.".format(name) + ret["comment"] = "Could not install pecl extension {}.".format(name) return ret @@ -111,17 +106,17 @@ def removed(name): ret = {"name": name, "result": None, "comment": "", "changes": {}} if name not in __salt__["pecl.list"](): ret["result"] = True - ret["comment"] = "Pecl extension {0} is not installed.".format(name) + ret["comment"] = "Pecl extension {} is not installed.".format(name) return ret if __opts__["test"]: - ret["comment"] = "Pecl extension {0} would have been removed".format(name) + ret["comment"] = "Pecl extension {} would have been removed".format(name) return ret if __salt__["pecl.uninstall"](name): ret["result"] = True ret["changes"][name] = "Removed" - ret["comment"] = "Pecl extension {0} was successfully removed.".format(name) + ret["comment"] = "Pecl extension {} was successfully removed.".format(name) else: ret["result"] = False - ret["comment"] = "Could not remove pecl extension {0}.".format(name) + ret["comment"] = "Could not remove pecl extension {}.".format(name) return ret diff --git a/salt/states/portage_config.py b/salt/states/portage_config.py index c0c70cd4d30..75e1b884dcb 100644 --- a/salt/states/portage_config.py +++ b/salt/states/portage_config.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of Portage package configuration on Gentoo ===================================================== @@ -12,7 +11,6 @@ A state module to manage Portage configuration on Gentoo - use: - openssl """ -from __future__ import absolute_import, print_function, unicode_literals def __virtual__(): diff --git a/salt/states/ports.py b/salt/states/ports.py index 6954777d49d..f600bdba855 100644 --- a/salt/states/ports.py +++ b/salt/states/ports.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage software from FreeBSD ports @@ -14,9 +13,7 @@ Manage software from FreeBSD ports salt -t 1200 '*' state.highstate """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import copy import logging @@ -24,10 +21,8 @@ import logging import os # pylint: disable=W0611 import sys -# Import salt libs import salt.utils.data from salt.exceptions import CommandExecutionError, SaltInvocationError -from salt.ext import six from salt.modules.freebsdports import _normalize, _options_file_exists log = logging.getLogger(__name__) @@ -43,12 +38,10 @@ def _repack_options(options): """ Repack the options data """ - return dict( - [ - (six.text_type(x), _normalize(y)) - for x, y in six.iteritems(salt.utils.data.repack_dictlist(options)) - ] - ) + return { + str(x): _normalize(y) + for x, y in salt.utils.data.repack_dictlist(options).items() + } def _get_option_list(options): @@ -56,7 +49,7 @@ def _get_option_list(options): Returns the key/value pairs in the passed dict in a commaspace-delimited list in the format "key=value". """ - return ", ".join(["{0}={1}".format(x, y) for x, y in six.iteritems(options)]) + return ", ".join(["{}={}".format(x, y) for x, y in options.items()]) def _build_option_string(options): @@ -64,7 +57,7 @@ def _build_option_string(options): Common function to get a string to append to the end of the state comment """ if options: - return "with the following build options: {0}".format(_get_option_list(options)) + return "with the following build options: {}".format(_get_option_list(options)) else: return "with the default build options" @@ -96,7 +89,7 @@ def installed(name, options=None): "name": name, "changes": {}, "result": True, - "comment": "{0} is already installed".format(name), + "comment": "{} is already installed".format(name), } try: current_options = __salt__["ports.showconfig"]( @@ -113,9 +106,9 @@ def installed(name, options=None): except (SaltInvocationError, CommandExecutionError) as exc: ret["result"] = False ret["comment"] = ( - "Unable to get configuration for {0}. Port name may " + "Unable to get configuration for {}. Port name may " "be invalid, or ports tree may need to be updated. " - "Error message: {1}".format(name, exc) + "Error message: {}".format(name, exc) ) return ret @@ -123,7 +116,7 @@ def installed(name, options=None): desired_options = copy.deepcopy(default_options) desired_options.update(options) ports_pre = [ - x["origin"] for x in six.itervalues(__salt__["pkg.list_pkgs"](with_origin=True)) + x["origin"] for x in __salt__["pkg.list_pkgs"](with_origin=True).values() ] if current_options == desired_options and name in ports_pre: @@ -136,14 +129,14 @@ def installed(name, options=None): if options: ret["result"] = False ret["comment"] = ( - "{0} does not have any build options, yet " + "{} does not have any build options, yet " "options were specified".format(name) ) return ret else: if __opts__["test"]: ret["result"] = None - ret["comment"] = "{0} will be installed".format(name) + ret["comment"] = "{} will be installed".format(name) return ret else: bad_opts = [x for x in options if x not in default_options] @@ -151,31 +144,31 @@ def installed(name, options=None): ret["result"] = False ret["comment"] = ( "The following options are not available for " - "{0}: {1}".format(name, ", ".join(bad_opts)) + "{}: {}".format(name, ", ".join(bad_opts)) ) return ret if __opts__["test"]: ret["result"] = None - ret["comment"] = "{0} will be installed ".format(name) + ret["comment"] = "{} will be installed ".format(name) ret["comment"] += _build_option_string(options) return ret if options: if not __salt__["ports.config"](name, reset=True, **options): ret["result"] = False - ret["comment"] = "Unable to set options for {0}".format(name) + ret["comment"] = "Unable to set options for {}".format(name) return ret else: __salt__["ports.rmconfig"](name) if _options_file_exists(name): ret["result"] = False - ret["comment"] = "Unable to clear options for {0}".format(name) + ret["comment"] = "Unable to clear options for {}".format(name) return ret ret["changes"] = __salt__["ports.install"](name) ports_post = [ - x["origin"] for x in six.itervalues(__salt__["pkg.list_pkgs"](with_origin=True)) + x["origin"] for x in __salt__["pkg.list_pkgs"](with_origin=True).values() ] err = sys.modules[__salt__["test.ping"].__module__].__context__.pop( "ports.install_error", None @@ -183,11 +176,11 @@ def installed(name, options=None): if err or name not in ports_post: ret["result"] = False if ret["result"]: - ret["comment"] = "Successfully installed {0}".format(name) + ret["comment"] = "Successfully installed {}".format(name) if default_options: ret["comment"] += " " + _build_option_string(options) else: - ret["comment"] = "Failed to install {0}".format(name) + ret["comment"] = "Failed to install {}".format(name) if err: - ret["comment"] += ". Error message:\n{0}".format(err) + ret["comment"] += ". Error message:\n{}".format(err) return ret diff --git a/salt/states/powerpath.py b/salt/states/powerpath.py index 3654fdccaaa..829a6359e5c 100644 --- a/salt/states/powerpath.py +++ b/salt/states/powerpath.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Powerpath configuration support =============================== @@ -12,9 +11,6 @@ only addition/deletion of licenses is supported. powerpath.license_present: [] """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - def license_present(name): """ @@ -35,12 +31,12 @@ def license_present(name): if name in licenses: ret["result"] = True - ret["comment"] = "License key {0} already present".format(name) + ret["comment"] = "License key {} already present".format(name) return ret if __opts__["test"]: ret["result"] = None - ret["comment"] = "License key {0} is set to be added".format(name) + ret["comment"] = "License key {} is set to be added".format(name) return ret data = __salt__["powerpath.add_license"](name) @@ -74,12 +70,12 @@ def license_absent(name): if name not in licenses: ret["result"] = True - ret["comment"] = "License key {0} not present".format(name) + ret["comment"] = "License key {} not present".format(name) return ret if __opts__["test"]: ret["result"] = None - ret["comment"] = "License key {0} is set to be removed".format(name) + ret["comment"] = "License key {} is set to be removed".format(name) return ret data = __salt__["powerpath.remove_license"](name) diff --git a/salt/states/process.py b/salt/states/process.py index 8251c1b0351..6b927b482ff 100644 --- a/salt/states/process.py +++ b/salt/states/process.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Process Management ================== @@ -11,7 +10,6 @@ Ensure a process matching a given pattern is absent. process.absent: - name: apache2 """ -from __future__ import absolute_import, print_function, unicode_literals def __virtual__(): @@ -39,7 +37,7 @@ def absent(name, user=None, signal=None): running = __salt__["ps.pgrep"](name, user=user) ret["result"] = None if running: - ret["comment"] = ("{0} processes will " "be killed").format(len(running)) + ret["comment"] = ("{} processes will " "be killed").format(len(running)) else: ret["comment"] = "No matching processes running" return ret @@ -51,7 +49,7 @@ def absent(name, user=None, signal=None): ret["result"] = True if status: - ret["comment"] = "Killed {0} processes".format(len(status["killed"])) + ret["comment"] = "Killed {} processes".format(len(status["killed"])) ret["changes"] = status else: ret["comment"] = "No matching processes running" diff --git a/salt/states/pushover.py b/salt/states/pushover.py index 1ea968902b7..cda8117a281 100644 --- a/salt/states/pushover.py +++ b/salt/states/pushover.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Send a message to PushOver ========================== @@ -28,9 +27,6 @@ The api key can be specified in the master or minion configuration like below: """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - def __virtual__(): """ @@ -106,18 +102,18 @@ def post_message( ret = {"name": name, "changes": {}, "result": False, "comment": ""} if __opts__["test"]: - ret["comment"] = "The following message is to be sent to PushOver: {0}".format( + ret["comment"] = "The following message is to be sent to PushOver: {}".format( message ) ret["result"] = None return ret if not user: - ret["comment"] = "PushOver user is missing: {0}".format(user) + ret["comment"] = "PushOver user is missing: {}".format(user) return ret if not message: - ret["comment"] = "PushOver message is missing: {0}".format(message) + ret["comment"] = "PushOver message is missing: {}".format(message) return ret result = __salt__["pushover.post_message"]( @@ -133,8 +129,8 @@ def post_message( if result: ret["result"] = True - ret["comment"] = "Sent message: {0}".format(name) + ret["comment"] = "Sent message: {}".format(name) else: - ret["comment"] = "Failed to send message: {0}".format(name) + ret["comment"] = "Failed to send message: {}".format(name) return ret diff --git a/salt/states/pyrax_queues.py b/salt/states/pyrax_queues.py index 4ad63137199..f1c951a510c 100644 --- a/salt/states/pyrax_queues.py +++ b/salt/states/pyrax_queues.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage Rackspace Queues ======================= @@ -21,7 +20,6 @@ This module is greatly inspired by boto_* modules from SaltStack code source. pyrax_queues.absent: - provider: my-pyrax """ -from __future__ import absolute_import, print_function, unicode_literals import salt.utils.openstack.pyrax as suop @@ -55,7 +53,7 @@ def present(name, provider): if not is_present: if __opts__["test"]: - msg = "Rackspace queue {0} is set to be created.".format(name) + msg = "Rackspace queue {} is set to be created.".format(name) ret["comment"] = msg ret["result"] = None return ret @@ -70,10 +68,10 @@ def present(name, provider): ret["changes"]["new"] = {"queue": queue} else: ret["result"] = False - ret["comment"] = "Failed to create {0} Rackspace queue.".format(name) + ret["comment"] = "Failed to create {} Rackspace queue.".format(name) return ret else: - ret["comment"] = "{0} present.".format(name) + ret["comment"] = "{} present.".format(name) return ret @@ -100,7 +98,7 @@ def absent(name, provider): if is_present: if __opts__["test"]: - ret["comment"] = "Rackspace queue {0} is set to be removed.".format(name) + ret["comment"] = "Rackspace queue {} is set to be removed.".format(name) ret["result"] = None return ret queue = __salt__["cloud.action"]("queues_show", provider=provider, name=name) @@ -112,8 +110,8 @@ def absent(name, provider): ret["changes"]["new"] = {} else: ret["result"] = False - ret["comment"] = "Failed to delete {0} Rackspace queue.".format(name) + ret["comment"] = "Failed to delete {} Rackspace queue.".format(name) else: - ret["comment"] = "{0} does not exist.".format(name) + ret["comment"] = "{} does not exist.".format(name) return ret diff --git a/salt/states/rbac_solaris.py b/salt/states/rbac_solaris.py index f6e1ff337ae..551e5b9df83 100644 --- a/salt/states/rbac_solaris.py +++ b/salt/states/rbac_solaris.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of Solaris RBAC @@ -20,9 +19,7 @@ Management of Solaris RBAC - authorizations: - solaris.audit.* """ -from __future__ import absolute_import, print_function, unicode_literals -# Import Python libs import logging log = logging.getLogger(__name__) @@ -44,7 +41,7 @@ def __virtual__(): else: return ( False, - "{0} state module can only be loaded on Solaris".format(__virtualname__), + "{} state module can only be loaded on Solaris".format(__virtualname__), ) @@ -73,7 +70,7 @@ def managed(name, roles=None, profiles=None, authorizations=None): ## check properties if name not in __salt__["user.list_users"](): ret["result"] = False - ret["comment"] = "User {0} does not exist!".format(name) + ret["comment"] = "User {} does not exist!".format(name) return ret if roles and not isinstance(roles, (list)): ret["result"] = False diff --git a/salt/states/rbenv.py b/salt/states/rbenv.py index c45b91c9fc7..c9c721f7104 100644 --- a/salt/states/rbenv.py +++ b/salt/states/rbenv.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Managing Ruby installations with rbenv ====================================== @@ -52,11 +51,8 @@ and 2.x using rbenv on Ubuntu/Debian: - require: - pkg: rbenv-deps """ -from __future__ import absolute_import, print_function, unicode_literals import copy - -# Import python libs import re @@ -134,9 +130,9 @@ def installed(name, default=False, user=None): if __opts__["test"]: ret = _ruby_installed(ret, name, user=user) if not ret["result"]: - ret["comment"] = "Ruby {0} is set to be installed".format(name) + ret["comment"] = "Ruby {} is set to be installed".format(name) else: - ret["comment"] = "Ruby {0} is already installed".format(name) + ret["comment"] = "Ruby {} is already installed".format(name) return ret rbenv_installed_ret = _check_and_install_rbenv(rbenv_installed_ret, user) @@ -168,7 +164,7 @@ def _check_and_uninstall_ruby(ret, ruby, user=None): return ret else: ret["result"] = True - ret["comment"] = "Ruby {0} is already absent".format(ruby) + ret["comment"] = "Ruby {} is already absent".format(ruby) return ret @@ -196,17 +192,17 @@ def absent(name, user=None): ret = _check_rbenv(ret, user) if ret["result"] is False: ret["result"] = True - ret["comment"] = "Rbenv not installed, {0} not either".format(name) + ret["comment"] = "Rbenv not installed, {} not either".format(name) return ret else: if __opts__["test"]: ret = _ruby_installed(ret, name, user=user) if ret["result"]: ret["result"] = None - ret["comment"] = "Ruby {0} is set to be uninstalled".format(name) + ret["comment"] = "Ruby {} is set to be uninstalled".format(name) else: ret["result"] = True - ret["comment"] = "Ruby {0} is already uninstalled".format(name) + ret["comment"] = "Ruby {} is already uninstalled".format(name) return ret return _check_and_uninstall_ruby(ret, name, user=user) diff --git a/salt/states/rdp.py b/salt/states/rdp.py index 10e8bcfc693..48224a65c9d 100644 --- a/salt/states/rdp.py +++ b/salt/states/rdp.py @@ -1,8 +1,6 @@ -# -*- coding: utf-8 -*- """ Manage RDP Service on Windows servers """ -from __future__ import absolute_import, print_function, unicode_literals def __virtual__(): diff --git a/salt/states/rsync.py b/salt/states/rsync.py index 5683fb0b7b3..79be3def583 100644 --- a/salt/states/rsync.py +++ b/salt/states/rsync.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright 2015 SUSE LLC # @@ -27,7 +26,6 @@ State to synchronize files and directories with rsync. """ -from __future__ import absolute_import, print_function, unicode_literals import logging import os diff --git a/salt/states/rvm.py b/salt/states/rvm.py index 60f469833c3..5b7c4fa8e22 100644 --- a/salt/states/rvm.py +++ b/salt/states/rvm.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Managing Ruby installations and gemsets with Ruby Version Manager (RVM) ======================================================================= @@ -100,9 +99,7 @@ configuration could look like: - require: - rvm: ruby-1.9.2 """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import re @@ -191,7 +188,7 @@ def installed(name, default=False, user=None, opts=None, env=None): ret = {"name": name, "result": None, "comment": "", "changes": {}} if __opts__["test"]: - ret["comment"] = "Ruby {0} is set to be installed".format(name) + ret["comment"] = "Ruby {} is set to be installed".format(name) return ret ret = _check_rvm(ret, user) @@ -244,7 +241,7 @@ def gemset_present(name, ruby="default", user=None): else: if __opts__["test"]: ret["result"] = None - ret["comment"] = "Set to install gemset {0}".format(name) + ret["comment"] = "Set to install gemset {}".format(name) return ret if __salt__["rvm.gemset_create"](ruby, name, runas=user): ret["result"] = True diff --git a/salt/states/serverdensity_device.py b/salt/states/serverdensity_device.py index 2009797b1d0..6e486cd2454 100644 --- a/salt/states/serverdensity_device.py +++ b/salt/states/serverdensity_device.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Monitor Server with Server Density ================================== @@ -47,17 +46,11 @@ Example: serverdensity_device.monitored """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import logging -# Import Salt libs import salt.utils.json -# Import 3rd-party libs -from salt.ext import six - # TODO: # # Add a plugin support @@ -86,10 +79,10 @@ def _get_salt_params(): sd_os = {"code": all_grains["kernel"].lower(), "name": all_grains["kernel"]} params["os"] = salt.utils.json.dumps(sd_os) params["cpuCores"] = all_stats["cpuinfo"]["cpu cores"] - params["installedRAM"] = six.text_type( + params["installedRAM"] = str( int(all_stats["meminfo"]["MemTotal"]["value"]) / 1024 ) - params["swapSpace"] = six.text_type( + params["swapSpace"] = str( int(all_stats["meminfo"]["SwapTotal"]["value"]) / 1024 ) params["privateIPs"] = salt.utils.json.dumps(all_grains["fqdn_ip4"]) @@ -173,7 +166,7 @@ def monitored( # override salt_params with given params if salt_params: - for key, value in six.iteritems(params): + for key, value in params.items(): params_from_salt[key] = value params_to_use = params_from_salt else: diff --git a/salt/states/smartos.py b/salt/states/smartos.py index cdfd89327f6..8fd8899a35f 100644 --- a/salt/states/smartos.py +++ b/salt/states/smartos.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of SmartOS Standalone Compute Nodes @@ -118,22 +117,15 @@ Management of SmartOS Standalone Compute Nodes this disk should NOT have a size specified. (See man vmadm) """ -from __future__ import absolute_import, print_function, unicode_literals import json - -# Import Python libs import logging import os -# Import Salt libs import salt.utils.atomicfile import salt.utils.data import salt.utils.files -# Import 3rd party libs -from salt.ext import six - log = logging.getLogger(__name__) # Define the state's virtual name @@ -149,7 +141,7 @@ def __virtual__(): else: return ( False, - "{0} state module can only be loaded on SmartOS compute nodes".format( + "{} state module can only be loaded on SmartOS compute nodes".format( __virtualname__ ), ) @@ -174,7 +166,7 @@ def _is_uuid(uuid): Example: e69a0918-055d-11e5-8912-e3ceb6df4cf8 """ - if uuid and list((len(x) for x in uuid.split("-"))) == [8, 4, 4, 4, 12]: + if uuid and list(len(x) for x in uuid.split("-")) == [8, 4, 4, 4, 12]: return True return False @@ -217,18 +209,16 @@ def _write_config(config): with salt.utils.atomicfile.atomic_open("/usbkey/config", "w") as config_file: config_file.write("#\n# This file was generated by salt\n#\n") for prop in salt.utils.odict.OrderedDict(sorted(config.items())): - if " " in six.text_type(config[prop]): + if " " in str(config[prop]): if not config[prop].startswith('"') or not config[prop].endswith( '"' ): - config[prop] = '"{0}"'.format(config[prop]) + config[prop] = '"{}"'.format(config[prop]) config_file.write( - salt.utils.stringutils.to_str( - "{0}={1}\n".format(prop, config[prop]) - ) + salt.utils.stringutils.to_str("{}={}\n".format(prop, config[prop])) ) log.debug("smartos.config - wrote /usbkey/config: %s", config) - except IOError: + except OSError: return False return True @@ -257,7 +247,7 @@ def _parse_vmconfig(config, instances): instance_config["mac"] = instance_config["mac"].lower() ## calculate mac from vrrp_vrid if "vrrp_vrid" in instance_config: - instance_config["mac"] = "00:00:5e:00:01:{0}".format( + instance_config["mac"] = "00:00:5e:00:01:{}".format( hex(int(instance_config["vrrp_vrid"])) .split("x")[-1] .zfill(2), @@ -309,7 +299,7 @@ def _copy_lx_vars(vmconfig): for var in imgtags.get("docker:config", {}): val = imgtags["docker:config"][var] - var = "docker:{0}".format(var.lower()) + var = "docker:{}".format(var.lower()) # NOTE: skip empty values if not val: @@ -331,7 +321,7 @@ def _copy_lx_vars(vmconfig): ): config_env_var = config_env_var.split("=") for img_env_var in val: - if img_env_var.startswith("{0}=".format(config_env_var[0])): + if img_env_var.startswith("{}=".format(config_env_var[0])): val.remove(img_env_var) val.append("=".join(config_env_var)) elif var in vmconfig["internal_metadata"]: @@ -369,20 +359,20 @@ def config_present(name, value): value = "" if name in config: - if six.text_type(config[name]) == six.text_type(value): + if str(config[name]) == str(value): # we're good ret["result"] = True - ret["comment"] = 'property {0} already has value "{1}"'.format(name, value) + ret["comment"] = 'property {} already has value "{}"'.format(name, value) else: # update property ret["result"] = True - ret["comment"] = 'updated property {0} with value "{1}"'.format(name, value) + ret["comment"] = 'updated property {} with value "{}"'.format(name, value) ret["changes"][name] = value config[name] = value else: # add property ret["result"] = True - ret["comment"] = 'added property {0} with value "{1}"'.format(name, value) + ret["comment"] = 'added property {} with value "{}"'.format(name, value) ret["changes"][name] = value config[name] = value @@ -393,7 +383,7 @@ def config_present(name, value): if not ret["result"]: ret[ "comment" - ] = 'Could not add property {0} with value "{1}" to config'.format( + ] = 'Could not add property {} with value "{}" to config'.format( name, value ) @@ -417,13 +407,13 @@ def config_absent(name): if name in config: # delete property ret["result"] = True - ret["comment"] = "property {0} deleted".format(name) + ret["comment"] = "property {} deleted".format(name) ret["changes"][name] = None del config[name] else: # we're good ret["result"] = True - ret["comment"] = "property {0} is absent".format(name) + ret["comment"] = "property {} is absent".format(name) # apply change if needed if not __opts__["test"] and ret["changes"]: @@ -446,7 +436,7 @@ def source_present(name, source_type="imgapi"): if name in __salt__["imgadm.sources"](): # source is present ret["result"] = True - ret["comment"] = "image source {0} is present".format(name) + ret["comment"] = "image source {} is present".format(name) else: # add new source if __opts__["test"]: @@ -457,12 +447,12 @@ def source_present(name, source_type="imgapi"): ret["result"] = name in res if ret["result"]: - ret["comment"] = "image source {0} added".format(name) + ret["comment"] = "image source {} added".format(name) ret["changes"][name] = "added" else: - ret["comment"] = "image source {0} not added".format(name) + ret["comment"] = "image source {} not added".format(name) if "Error" in res: - ret["comment"] = "{0}: {1}".format(ret["comment"], res["Error"]) + ret["comment"] = "{}: {}".format(ret["comment"], res["Error"]) return ret @@ -479,7 +469,7 @@ def source_absent(name): if name not in __salt__["imgadm.sources"](): # source is absent ret["result"] = True - ret["comment"] = "image source {0} is absent".format(name) + ret["comment"] = "image source {} is absent".format(name) else: # remove source if __opts__["test"]: @@ -490,12 +480,12 @@ def source_absent(name): ret["result"] = name not in res if ret["result"]: - ret["comment"] = "image source {0} deleted".format(name) + ret["comment"] = "image source {} deleted".format(name) ret["changes"][name] = "deleted" else: - ret["comment"] = "image source {0} not deleted".format(name) + ret["comment"] = "image source {} not deleted".format(name) if "Error" in res: - ret["comment"] = "{0}: {1}".format(ret["comment"], res["Error"]) + ret["comment"] = "{}: {}".format(ret["comment"], res["Error"]) return ret @@ -512,13 +502,13 @@ def image_present(name): if _is_docker_uuid(name) and __salt__["imgadm.docker_to_uuid"](name): # docker image was imported ret["result"] = True - ret["comment"] = "image {0} ({1}) is present".format( + ret["comment"] = "image {} ({}) is present".format( name, __salt__["imgadm.docker_to_uuid"](name), ) elif name in __salt__["imgadm.list"](): # image was already imported ret["result"] = True - ret["comment"] = "image {0} is present".format(name) + ret["comment"] = "image {} is present".format(name) else: # add image if _is_docker_uuid(name): @@ -542,13 +532,13 @@ def image_present(name): elif _is_docker_uuid(name): ret["result"] = __salt__["imgadm.docker_to_uuid"](name) is not None if ret["result"]: - ret["comment"] = "image {0} imported".format(name) + ret["comment"] = "image {} imported".format(name) ret["changes"] = res else: - ret["comment"] = "image {0} was unable to be imported".format(name) + ret["comment"] = "image {} was unable to be imported".format(name) else: ret["result"] = False - ret["comment"] = "image {0} does not exists".format(name) + ret["comment"] = "image {} does not exists".format(name) return ret @@ -576,12 +566,12 @@ def image_absent(name): if not uuid or uuid not in __salt__["imgadm.list"](): # image not imported ret["result"] = True - ret["comment"] = "image {0} is absent".format(name) + ret["comment"] = "image {} is absent".format(name) else: # check if image in use by vm if uuid in __salt__["vmadm.list"](order="image_uuid"): ret["result"] = False - ret["comment"] = "image {0} currently in use by a vm".format(name) + ret["comment"] = "image {} currently in use by a vm".format(name) else: # delete image if __opts__["test"]: @@ -604,11 +594,11 @@ def image_absent(name): ret["result"] = uuid not in __salt__["imgadm.list"]() if image_count: - ret["comment"] = "image {0} and {1} children deleted".format( + ret["comment"] = "image {} and {} children deleted".format( name, image_count ) else: - ret["comment"] = "image {0} deleted".format(name) + ret["comment"] = "image {} deleted".format(name) ret["changes"][name] = None return ret @@ -804,14 +794,12 @@ def vm_present(name, vmconfig, config=None): ) if vmconfig["image_uuid"] not in res: ret["result"] = False - ret["comment"] = "failed to import image {0}".format( + ret["comment"] = "failed to import image {}".format( vmconfig["image_uuid"] ) else: ret["result"] = False - ret["comment"] = "image {0} not installed".format( - vmconfig["image_uuid"] - ) + ret["comment"] = "image {} not installed".format(vmconfig["image_uuid"]) # prepare disk.*.image_uuid for disk in vmconfig["disks"] if "disks" in vmconfig else []: @@ -821,12 +809,12 @@ def vm_present(name, vmconfig, config=None): res = __salt__["imgadm.import"](disk["image_uuid"]) if disk["image_uuid"] not in res: ret["result"] = False - ret["comment"] = "failed to import image {0}".format( + ret["comment"] = "failed to import image {}".format( disk["image_uuid"] ) else: ret["result"] = False - ret["comment"] = "image {0} not installed".format(disk["image_uuid"]) + ret["comment"] = "image {} not installed".format(disk["image_uuid"]) # docker json-array handling if "internal_metadata" in vmconfig: @@ -901,7 +889,7 @@ def vm_present(name, vmconfig, config=None): if vmconfig["current"][prop] == vmconfig["state"][prop]: continue else: - if "{0}".format(vmconfig["current"][prop]) == "{0}".format( + if "{}".format(vmconfig["current"][prop]) == "{}".format( vmconfig["state"][prop] ): continue @@ -916,7 +904,7 @@ def vm_present(name, vmconfig, config=None): continue # enforcement - enforce = config["enforce_{0}".format(collection)] + enforce = config["enforce_{}".format(collection)] log.debug("smartos.vm_present::enforce_%s = %s", collection, enforce) # dockerinit handling @@ -951,11 +939,11 @@ def vm_present(name, vmconfig, config=None): continue # create set_ dict - if "set_{0}".format(collection) not in vmconfig["changed"]: - vmconfig["changed"]["set_{0}".format(collection)] = {} + if "set_{}".format(collection) not in vmconfig["changed"]: + vmconfig["changed"]["set_{}".format(collection)] = {} # add property to changeset - vmconfig["changed"]["set_{0}".format(collection)][prop] = vmconfig[ + vmconfig["changed"]["set_{}".format(collection)][prop] = vmconfig[ "state" ][collection][prop] @@ -975,11 +963,11 @@ def vm_present(name, vmconfig, config=None): continue # create remove_ array - if "remove_{0}".format(collection) not in vmconfig["changed"]: - vmconfig["changed"]["remove_{0}".format(collection)] = [] + if "remove_{}".format(collection) not in vmconfig["changed"]: + vmconfig["changed"]["remove_{}".format(collection)] = [] # remove property - vmconfig["changed"]["remove_{0}".format(collection)].append(prop) + vmconfig["changed"]["remove_{}".format(collection)].append(prop) # process instances for instance in vmconfig_type["instance"]: @@ -1030,29 +1018,27 @@ def vm_present(name, vmconfig, config=None): if update_cfg: # create update_ array if ( - "update_{0}".format(instance) + "update_{}".format(instance) not in vmconfig["changed"] ): vmconfig["changed"][ - "update_{0}".format(instance) + "update_{}".format(instance) ] = [] update_cfg[ vmconfig_type["instance"][instance] ] = state_cfg[vmconfig_type["instance"][instance]] vmconfig["changed"][ - "update_{0}".format(instance) + "update_{}".format(instance) ].append(update_cfg) if add_instance: # create add_ array - if "add_{0}".format(instance) not in vmconfig["changed"]: - vmconfig["changed"]["add_{0}".format(instance)] = [] + if "add_{}".format(instance) not in vmconfig["changed"]: + vmconfig["changed"]["add_{}".format(instance)] = [] # add instance - vmconfig["changed"]["add_{0}".format(instance)].append( - state_cfg - ) + vmconfig["changed"]["add_{}".format(instance)].append(state_cfg) # remove instances if ( @@ -1080,11 +1066,11 @@ def vm_present(name, vmconfig, config=None): if remove_instance: # create remove_ array - if "remove_{0}".format(instance) not in vmconfig["changed"]: - vmconfig["changed"]["remove_{0}".format(instance)] = [] + if "remove_{}".format(instance) not in vmconfig["changed"]: + vmconfig["changed"]["remove_{}".format(instance)] = [] # remove instance - vmconfig["changed"]["remove_{0}".format(instance)].append( + vmconfig["changed"]["remove_{}".format(instance)].append( current_cfg[vmconfig_type["instance"][instance]] ) @@ -1112,7 +1098,7 @@ def vm_present(name, vmconfig, config=None): ) if not isinstance(rret, (bool)) and "Error" in rret: ret["result"] = False - ret["comment"] = "{0}".format(rret["Error"]) + ret["comment"] = "{}".format(rret["Error"]) else: ret["result"] = True ret["changes"][vmconfig["state"]["hostname"]] = vmconfig["changed"] @@ -1125,7 +1111,7 @@ def vm_present(name, vmconfig, config=None): vmconfig["state"]["hostname"] in ret["changes"] and ret["changes"][vmconfig["state"]["hostname"]] ): - ret["comment"] = "vm {0} updated".format(vmconfig["state"]["hostname"]) + ret["comment"] = "vm {} updated".format(vmconfig["state"]["hostname"]) if ( config["kvm_reboot"] and vmconfig["current"]["brand"] == "kvm" @@ -1143,7 +1129,7 @@ def vm_present(name, vmconfig, config=None): ) else: ret["changes"] = {} - ret["comment"] = "vm {0} is up to date".format( + ret["comment"] = "vm {} is up to date".format( vmconfig["state"]["hostname"] ) @@ -1160,11 +1146,11 @@ def vm_present(name, vmconfig, config=None): ) if not isinstance(rret, (bool)) and "Error" in rret: ret["result"] = False - ret["comment"] = "vm {0} updated, reprovision failed".format( + ret["comment"] = "vm {} updated, reprovision failed".format( vmconfig["state"]["hostname"] ) else: - ret["comment"] = "vm {0} updated and reprovisioned".format( + ret["comment"] = "vm {} updated and reprovisioned".format( vmconfig["state"]["hostname"] ) if vmconfig["state"]["hostname"] not in ret["changes"]: @@ -1180,11 +1166,11 @@ def vm_present(name, vmconfig, config=None): name, ) else: - ret["comment"] = "vm {0} failed to be updated".format( + ret["comment"] = "vm {} failed to be updated".format( vmconfig["state"]["hostname"] ) if not isinstance(rret, (bool)) and "Error" in rret: - ret["comment"] = "{0}".format(rret["Error"]) + ret["comment"] = "{}".format(rret["Error"]) else: # check required image installed ret["result"] = True @@ -1205,11 +1191,11 @@ def vm_present(name, vmconfig, config=None): ) if not isinstance(uuid, (bool)) and "Error" in uuid: ret["result"] = False - ret["comment"] = "{0}".format(uuid["Error"]) + ret["comment"] = "{}".format(uuid["Error"]) else: ret["result"] = True ret["changes"][vmconfig["hostname"]] = vmconfig - ret["comment"] = "vm {0} created".format(vmconfig["hostname"]) + ret["comment"] = "vm {} created".format(vmconfig["hostname"]) return ret @@ -1234,7 +1220,7 @@ def vm_absent(name, archive=False): if name not in __salt__["vmadm.list"](order="hostname"): # we're good ret["result"] = True - ret["comment"] = "vm {0} is absent".format(name) + ret["comment"] = "vm {} is absent".format(name) else: # delete vm if not __opts__["test"]: @@ -1250,9 +1236,9 @@ def vm_absent(name, archive=False): if not isinstance(ret["result"], bool) and ret["result"].get("Error"): ret["result"] = False - ret["comment"] = "failed to delete vm {0}".format(name) + ret["comment"] = "failed to delete vm {}".format(name) else: - ret["comment"] = "vm {0} deleted".format(name) + ret["comment"] = "vm {} deleted".format(name) ret["changes"][name] = None return ret @@ -1276,7 +1262,7 @@ def vm_running(name): if name in __salt__["vmadm.list"](order="hostname", search="state=running"): # we're good ret["result"] = True - ret["comment"] = "vm {0} already running".format(name) + ret["comment"] = "vm {} already running".format(name) else: # start the vm ret["result"] = ( @@ -1284,10 +1270,10 @@ def vm_running(name): ) if not isinstance(ret["result"], bool) and ret["result"].get("Error"): ret["result"] = False - ret["comment"] = "failed to start {0}".format(name) + ret["comment"] = "failed to start {}".format(name) else: ret["changes"][name] = "running" - ret["comment"] = "vm {0} started".format(name) + ret["comment"] = "vm {} started".format(name) return ret @@ -1310,7 +1296,7 @@ def vm_stopped(name): if name in __salt__["vmadm.list"](order="hostname", search="state=stopped"): # we're good ret["result"] = True - ret["comment"] = "vm {0} already stopped".format(name) + ret["comment"] = "vm {} already stopped".format(name) else: # stop the vm ret["result"] = ( @@ -1318,10 +1304,10 @@ def vm_stopped(name): ) if not isinstance(ret["result"], bool) and ret["result"].get("Error"): ret["result"] = False - ret["comment"] = "failed to stop {0}".format(name) + ret["comment"] = "failed to stop {}".format(name) else: ret["changes"][name] = "stopped" - ret["comment"] = "vm {0} stopped".format(name) + ret["comment"] = "vm {} stopped".format(name) return ret diff --git a/salt/states/snapper.py b/salt/states/snapper.py index 3efc5d4d769..964c88c5001 100644 --- a/salt/states/snapper.py +++ b/salt/states/snapper.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Managing implicit state and baselines using snapshots ===================================================== @@ -107,7 +106,6 @@ and include this change. :platform: Linux """ -from __future__ import absolute_import, print_function, unicode_literals import os @@ -181,7 +179,7 @@ def baseline_snapshot( snapshot = _get_baseline_from_tag(config, tag) if not snapshot: ret.update( - {"result": False, "comment": 'Baseline tag "{0}" not found'.format(tag)} + {"result": False, "comment": 'Baseline tag "{}" not found'.format(tag)} ) return ret number = snapshot["id"] @@ -211,7 +209,7 @@ def baseline_snapshot( if __opts__["test"] and status: ret["changes"] = status - ret["comment"] = "{0} files changes are set to be undone".format( + ret["comment"] = "{} files changes are set to be undone".format( len(status.keys()) ) ret["result"] = None diff --git a/salt/states/solrcloud.py b/salt/states/solrcloud.py index 3da19306250..31768a3e9e3 100644 --- a/salt/states/solrcloud.py +++ b/salt/states/solrcloud.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ States for solrcloud alias and collection configuration @@ -6,15 +5,9 @@ States for solrcloud alias and collection configuration """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals -# Import Salt libs import salt.utils.json -# Import 3rd party libs -from salt.ext import six - def alias(name, collections, **kwargs): """ @@ -46,11 +39,11 @@ def alias(name, collections, **kwargs): return ret if __opts__["test"]: - ret["comment"] = 'The alias "{0}" will be updated.'.format(name) + ret["comment"] = 'The alias "{}" will be updated.'.format(name) ret["result"] = None else: __salt__["solrcloud.alias_set_collections"](name, collections, **kwargs) - ret["comment"] = 'The alias "{0}" has been updated.'.format(name) + ret["comment"] = 'The alias "{}" has been updated.'.format(name) ret["result"] = True ret["changes"] = { @@ -60,11 +53,11 @@ def alias(name, collections, **kwargs): else: if __opts__["test"]: - ret["comment"] = 'The alias "{0}" will be created.'.format(name) + ret["comment"] = 'The alias "{}" will be created.'.format(name) ret["result"] = None else: __salt__["solrcloud.alias_set_collections"](name, collections, **kwargs) - ret["comment"] = 'The alias "{0}" has been created.'.format(name) + ret["comment"] = 'The alias "{}" has been created.'.format(name) ret["result"] = True ret["changes"] = { @@ -114,7 +107,7 @@ def collection(name, options=None, **kwargs): "snitch", ] - options = [k for k in six.iteritems(options) if k in updatable_options] + options = [k for k in options.items() if k in updatable_options] for key, value in options: if key not in current_options or current_options[key] != value: @@ -128,13 +121,11 @@ def collection(name, options=None, **kwargs): else: if __opts__["test"]: - ret["comment"] = 'Collection options "{0}" will be changed.'.format( - name - ) + ret["comment"] = 'Collection options "{}" will be changed.'.format(name) ret["result"] = None else: __salt__["solrcloud.collection_set_options"](name, diff, **kwargs) - ret["comment"] = 'Parameters were updated for collection "{0}".'.format( + ret["comment"] = 'Parameters were updated for collection "{}".'.format( name ) ret["result"] = True @@ -155,16 +146,16 @@ def collection(name, options=None, **kwargs): options, sort_keys=True, indent=4, separators=(",", ": ") ) if __opts__["test"]: - ret["comment"] = 'The collection "{0}" will be created.'.format(name) + ret["comment"] = 'The collection "{}" will be created.'.format(name) ret["result"] = None else: __salt__["solrcloud.collection_create"](name, options, **kwargs) - ret["comment"] = 'The collection "{0}" has been created.'.format(name) + ret["comment"] = 'The collection "{}" has been created.'.format(name) ret["result"] = True ret["changes"] = { "old": None, - "new": str("options=") + "new": "options=" + new_changes, # future lint: disable=blacklisted-function } diff --git a/salt/states/splunk_search.py b/salt/states/splunk_search.py index fcfa87bb8cf..a12ca481e29 100644 --- a/salt/states/splunk_search.py +++ b/salt/states/splunk_search.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Splunk Search State Module @@ -13,7 +12,6 @@ This state is used to ensure presence of splunk searches. - name: This is the splunk search name - search: index=main sourcetype= """ -from __future__ import absolute_import, print_function, unicode_literals def __virtual__(): @@ -46,7 +44,7 @@ def present(name, profile="splunk", **kwargs): target = __salt__["splunk_search.get"](name, profile=profile) if target: if __opts__["test"]: - ret["comment"] = "Would update {0}".format(name) + ret["comment"] = "Would update {}".format(name) return ret # found a search... updating result = __salt__["splunk_search.update"](name, profile=profile, **kwargs) @@ -66,7 +64,7 @@ def present(name, profile="splunk", **kwargs): ret["changes"]["new"] = newvalues else: if __opts__["test"]: - ret["comment"] = "Would create {0}".format(name) + ret["comment"] = "Would create {}".format(name) return ret # creating a new search result = __salt__["splunk_search.create"](name, profile=profile, **kwargs) @@ -76,7 +74,7 @@ def present(name, profile="splunk", **kwargs): ret["changes"]["new"] = kwargs else: ret["result"] = False - ret["comment"] = "Failed to create {0}".format(name) + ret["comment"] = "Failed to create {}".format(name) return ret @@ -98,7 +96,7 @@ def absent(name, profile="splunk"): "name": name, "changes": {}, "result": True, - "comment": "{0} is absent.".format(name), + "comment": "{} is absent.".format(name), } target = __salt__["splunk_search.get"](name, profile=profile) @@ -106,14 +104,14 @@ def absent(name, profile="splunk"): if __opts__["test"]: ret = {} ret["name"] = name - ret["comment"] = "Would delete {0}".format(name) + ret["comment"] = "Would delete {}".format(name) ret["result"] = None return ret result = __salt__["splunk_search.delete"](name, profile=profile) if result: - ret["comment"] = "{0} was deleted".format(name) + ret["comment"] = "{} was deleted".format(name) else: - ret["comment"] = "Failed to delete {0}".format(name) + ret["comment"] = "Failed to delete {}".format(name) ret["result"] = False return ret diff --git a/salt/states/sqlite3.py b/salt/states/sqlite3.py index 96181e98a41..d0eb0615dd2 100644 --- a/salt/states/sqlite3.py +++ b/salt/states/sqlite3.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of SQLite3 databases =============================== @@ -93,11 +92,6 @@ can be approximated with sqlite3's module functions and module.run: - sqlite3: zone-insert-12 """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - -# Import Salt libs -from salt.ext import six try: import sqlite3 @@ -181,7 +175,7 @@ def row_absent(name, db, table, where_sql, where_args=None): except Exception as e: # pylint: disable=broad-except changes["result"] = False - changes["comment"] = six.text_type(e) + changes["comment"] = str(e) finally: if conn: @@ -240,7 +234,7 @@ def row_present(name, db, table, data, where_sql, where_args=None, update=False) changes["result"] = False changes["comment"] = "More than one row matched the specified query" elif len(rows) == 1: - for key, value in six.iteritems(data): + for key, value in data.items(): if key in rows[0] and rows[0][key] != value: if update: if __opts__["test"]: @@ -250,7 +244,7 @@ def row_present(name, db, table, data, where_sql, where_args=None, update=False) else: columns = [] params = [] - for key, value in six.iteritems(data): + for key, value in data.items(): columns.append("`" + key + "`=?") params.append(value) @@ -290,7 +284,7 @@ def row_present(name, db, table, data, where_sql, where_args=None, update=False) columns = [] value_stmt = [] values = [] - for key, value in six.iteritems(data): + for key, value in data.items(): value_stmt.append("?") values.append(value) columns.append("`" + key + "`") @@ -312,7 +306,7 @@ def row_present(name, db, table, data, where_sql, where_args=None, update=False) except Exception as e: # pylint: disable=broad-except changes["result"] = False - changes["comment"] = six.text_type(e) + changes["comment"] = str(e) finally: if conn: @@ -360,7 +354,7 @@ def table_absent(name, db): except Exception as e: # pylint: disable=broad-except changes["result"] = False - changes["comment"] = six.text_type(e) + changes["comment"] = str(e) finally: if conn: @@ -399,7 +393,7 @@ def table_present(name, db, schema, force=False): if len(tables) == 1: sql = None - if isinstance(schema, six.string_types): + if isinstance(schema, str): sql = schema.strip() else: sql = _get_sql_from_schema(name, schema) @@ -430,7 +424,7 @@ def table_present(name, db, schema, force=False): elif len(tables) == 0: # Create the table sql = None - if isinstance(schema, six.string_types): + if isinstance(schema, str): sql = schema else: sql = _get_sql_from_schema(name, schema) diff --git a/salt/states/statuspage.py b/salt/states/statuspage.py index a64bc1d8a31..6f999760530 100644 --- a/salt/states/statuspage.py +++ b/salt/states/statuspage.py @@ -18,8 +18,6 @@ In the minion configuration file, the following block is required: """ import logging - -# import python std lib import time # ---------------------------------------------------------------------------------------------------------------------- diff --git a/salt/states/supervisord.py b/salt/states/supervisord.py index 0f1b32fd21f..d0a5614c939 100644 --- a/salt/states/supervisord.py +++ b/salt/states/supervisord.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Interaction with the Supervisor daemon ====================================== @@ -12,13 +11,9 @@ Interaction with the Supervisor daemon - watch: - file: /etc/nginx/sites-enabled/wsgi_server.conf """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import logging -from salt.ext import six - log = logging.getLogger(__name__) @@ -114,7 +109,7 @@ def running( if __opts__["test"]: if not to_add: # Process/group already present, check if any need to be started - to_start = [x for x, y in six.iteritems(matches) if y is False] + to_start = [x for x, y in matches.items() if y is False] if to_start: ret["result"] = None if name.endswith(":"): @@ -122,32 +117,32 @@ def running( if len(to_start) == len(matches): ret[ "comment" - ] = "All services in group '{0}' will be started".format(name) + ] = "All services in group '{}' will be started".format(name) else: ret[ "comment" - ] = "The following services will be started: {0}".format( + ] = "The following services will be started: {}".format( " ".join(to_start) ) else: # Single program - ret["comment"] = "Service {0} will be started".format(name) + ret["comment"] = "Service {} will be started".format(name) else: if name.endswith(":"): # Process group ret[ "comment" - ] = "All services in group '{0}' are already running".format(name) + ] = "All services in group '{}' are already running".format(name) else: - ret["comment"] = "Service {0} is already running".format(name) + ret["comment"] = "Service {} is already running".format(name) else: ret["result"] = None # Process/group needs to be added if name.endswith(":"): - _type = "Group '{0}'".format(name) + _type = "Group '{}'".format(name) else: - _type = "Service {0}".format(name) - ret["comment"] = "{0} will be added and started".format(_type) + _type = "Service {}".format(name) + ret["comment"] = "{} will be added and started".format(_type) return ret changes = [] @@ -167,11 +162,11 @@ def running( ret.update(_check_error(result, comment)) log.debug(comment) - if "{0}: updated".format(name) in result: + if "{}: updated".format(name) in result: just_updated = True elif to_add: # Not sure if this condition is precise enough. - comment = "Adding service: {0}".format(name) + comment = "Adding service: {}".format(name) __salt__["supervisord.reread"](user=user, conf_file=conf_file, bin_env=bin_env) # Causes supervisorctl to throw `ERROR: process group already active` # if process group exists. At this moment, I'm not sure how to handle @@ -209,8 +204,8 @@ def running( if is_stopped is False: if restart and not just_updated: - comment = "Restarting{0}: {1}".format( - process_type is not None and " {0}".format(process_type) or "", name + comment = "Restarting{}: {}".format( + process_type is not None and " {}".format(process_type) or "", name ) log.debug(comment) result = __salt__["supervisord.restart"]( @@ -219,21 +214,21 @@ def running( ret.update(_check_error(result, comment)) changes.append(comment) elif just_updated: - comment = "Not starting updated{0}: {1}".format( - process_type is not None and " {0}".format(process_type) or "", name + comment = "Not starting updated{}: {}".format( + process_type is not None and " {}".format(process_type) or "", name ) result = comment ret.update({"comment": comment}) else: - comment = "Not starting already running{0}: {1}".format( - process_type is not None and " {0}".format(process_type) or "", name + comment = "Not starting already running{}: {}".format( + process_type is not None and " {}".format(process_type) or "", name ) result = comment ret.update({"comment": comment}) elif not just_updated: - comment = "Starting{0}: {1}".format( - process_type is not None and " {0}".format(process_type) or "", name + comment = "Starting{}: {}".format( + process_type is not None and " {}".format(process_type) or "", name ) changes.append(comment) log.debug(comment) @@ -242,7 +237,7 @@ def running( ) ret.update(_check_error(result, comment)) - log.debug(six.text_type(result)) + log.debug(str(result)) if ret["result"] and changes: ret["changes"][name] = " ".join(changes) @@ -273,9 +268,9 @@ def dead(name, user=None, conf_file=None, bin_env=None, **kwargs): if __opts__["test"]: ret["result"] = None - ret["comment"] = "Service {0} is set to be stopped".format(name) + ret["comment"] = "Service {} is set to be stopped".format(name) else: - comment = "Stopping service: {0}".format(name) + comment = "Stopping service: {}".format(name) log.debug(comment) all_processes = __salt__["supervisord.status"]( @@ -308,11 +303,11 @@ def dead(name, user=None, conf_file=None, bin_env=None, **kwargs): is_stopped = False else: # process name doesn't exist - ret["comment"] = "Service {0} doesn't exist".format(name) + ret["comment"] = "Service {} doesn't exist".format(name) return ret if is_stopped is True: - ret["comment"] = "Service {0} is not running".format(name) + ret["comment"] = "Service {} is not running".format(name) else: result = { name: __salt__["supervisord.stop"]( @@ -321,7 +316,7 @@ def dead(name, user=None, conf_file=None, bin_env=None, **kwargs): } ret.update(_check_error(result, comment)) ret["changes"][name] = comment - log.debug(six.text_type(result)) + log.debug(str(result)) return ret diff --git a/salt/states/sysrc.py b/salt/states/sysrc.py index 852046ac337..991e33bbff9 100644 --- a/salt/states/sysrc.py +++ b/salt/states/sysrc.py @@ -1,14 +1,8 @@ -# -*- coding: utf-8 -*- """ State to work with sysrc """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - -# Import 3rd-party libs -from salt.ext import six # define the module's virtual name __virtualname__ = "sysrc" @@ -51,14 +45,14 @@ def managed(name, value, **kwargs): # Check the current state current_state = __salt__["sysrc.get"](name=name, **kwargs) if current_state is not None: - for rcname, rcdict in six.iteritems(current_state): + for rcname, rcdict in current_state.items(): if rcdict[name] == value: ret["result"] = True - ret["comment"] = "{0} is already set to the desired value.".format(name) + ret["comment"] = "{} is already set to the desired value.".format(name) return ret if __opts__["test"] is True: - ret["comment"] = 'The value of "{0}" will be changed!'.format(name) + ret["comment"] = 'The value of "{}" will be changed!'.format(name) ret["changes"] = { "old": current_state, "new": name + " = " + value + " will be set.", @@ -71,7 +65,7 @@ def managed(name, value, **kwargs): new_state = __salt__["sysrc.set"](name=name, value=value, **kwargs) - ret["comment"] = 'The value of "{0}" was changed!'.format(name) + ret["comment"] = 'The value of "{}" was changed!'.format(name) ret["changes"] = {"old": current_state, "new": new_state} @@ -98,14 +92,14 @@ def absent(name, **kwargs): current_state = __salt__["sysrc.get"](name=name, **kwargs) if current_state is None: ret["result"] = True - ret["comment"] = '"{0}" is already absent.'.format(name) + ret["comment"] = '"{}" is already absent.'.format(name) return ret if __opts__["test"] is True: - ret["comment"] = '"{0}" will be removed!'.format(name) + ret["comment"] = '"{}" will be removed!'.format(name) ret["changes"] = { "old": current_state, - "new": '"{0}" will be removed.'.format(name), + "new": '"{}" will be removed.'.format(name), } # When test=true return none @@ -115,7 +109,7 @@ def absent(name, **kwargs): new_state = __salt__["sysrc.remove"](name=name, **kwargs) - ret["comment"] = '"{0}" was removed!'.format(name) + ret["comment"] = '"{}" was removed!'.format(name) ret["changes"] = {"old": current_state, "new": new_state} diff --git a/salt/states/testinframod.py b/salt/states/testinframod.py index b04cc6896d5..493fc8ef2eb 100644 --- a/salt/states/testinframod.py +++ b/salt/states/testinframod.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals - import logging from salt.utils.stringutils import camel_to_snake_case @@ -43,7 +40,7 @@ def _generate_functions(): modules_ = [module_ for module_ in modules.modules] for module_name in modules_: - func_name = "testinfra.{0}".format(module_name) + func_name = "testinfra.{}".format(module_name) __all__.append(module_name) log.debug( "Generating state for module %s as function %s", module_name, func_name diff --git a/salt/states/tomcat.py b/salt/states/tomcat.py index 9258d23a92e..d4511911fd4 100644 --- a/salt/states/tomcat.py +++ b/salt/states/tomcat.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Manage Apache Tomcat web applications ===================================== @@ -55,10 +54,6 @@ Notes 3.10.0-327.22.2.el7.x86_64 """ -from __future__ import absolute_import, print_function, unicode_literals - -from salt.ext import six - # Private def __virtual__(): @@ -147,7 +142,7 @@ def war_deployed( status = True # Gathered/specified new WAR version string - specified_ver = "version {0}".format(version) if version else "no version" + specified_ver = "version {}".format(version) if version else "no version" # Determine what to do try: @@ -165,25 +160,25 @@ def war_deployed( ): deploy = True undeploy = True - ret["changes"]["undeploy"] = "undeployed {0} with {1}".format( + ret["changes"]["undeploy"] = "undeployed {} with {}".format( name, current_ver ) - ret["changes"]["deploy"] = "will deploy {0} with {1}".format( + ret["changes"]["deploy"] = "will deploy {} with {}".format( name, specified_ver ) else: deploy = False - ret["comment"] = "{0} with {1} is already deployed".format( + ret["comment"] = "{} with {} is already deployed".format( name, specified_ver ) if webapps[name]["mode"] != "running": - ret["changes"]["start"] = "starting {0}".format(name) + ret["changes"]["start"] = "starting {}".format(name) status = False else: return ret except Exception: # pylint: disable=broad-except deploy = True - ret["changes"]["deploy"] = "deployed {0} with {1}".format(name, specified_ver) + ret["changes"]["deploy"] = "deployed {} with {}".format(name, specified_ver) # Test if __opts__["test"]: @@ -220,8 +215,8 @@ def war_deployed( # Return if deploy_res.startswith("OK"): ret["result"] = True - ret["comment"] = six.text_type(__salt__["tomcat.ls"](url, timeout)[name]) - ret["changes"]["deploy"] = "deployed {0} with {1}".format(name, specified_ver) + ret["comment"] = str(__salt__["tomcat.ls"](url, timeout)[name]) + ret["changes"]["deploy"] = "deployed {} with {}".format(name, specified_ver) else: ret["result"] = False ret["comment"] = deploy_res diff --git a/salt/states/trafficserver.py b/salt/states/trafficserver.py index 16181053973..7c2ed8e5539 100644 --- a/salt/states/trafficserver.py +++ b/salt/states/trafficserver.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Control Apache Traffic Server ============================= @@ -6,9 +5,6 @@ Control Apache Traffic Server .. versionadded:: 2015.8.0 """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - def __virtual__(): """ @@ -204,13 +200,13 @@ def config(name, value): ret = {"name": name, "changes": {}, "result": None, "comment": ""} if __opts__["test"]: - ret["comment"] = "Configuring {0} to {1}".format(name, value,) + ret["comment"] = "Configuring {} to {}".format(name, value,) return ret __salt__["trafficserver.set_config"](name, value) ret["result"] = True - ret["comment"] = "Configured {0} to {1}".format(name, value) + ret["comment"] = "Configured {} to {}".format(name, value) return ret @@ -346,11 +342,11 @@ def offline(name, path): ret = {"name": name, "changes": {}, "result": None, "comment": ""} if __opts__["test"]: - ret["comment"] = "Setting {0} to offline".format(path) + ret["comment"] = "Setting {} to offline".format(path) return ret __salt__["trafficserver.offline"](path) ret["result"] = True - ret["comment"] = "Set {0} as offline".format(path) + ret["comment"] = "Set {} as offline".format(path) return ret diff --git a/salt/states/vagrant.py b/salt/states/vagrant.py index 92e32b9baf9..4210715f92e 100644 --- a/salt/states/vagrant.py +++ b/salt/states/vagrant.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- r""" Manage Vagrant VMs ================== @@ -49,14 +48,9 @@ value will select the ``primary`` (or only) machine in the Vagrantfile. create_table: True # if not present """ -from __future__ import absolute_import, print_function, unicode_literals -# Import Python libs import fnmatch -import salt.ext.six as six - -# Import Salt libs import salt.utils.args from salt.exceptions import CommandExecutionError, SaltInvocationError @@ -88,7 +82,7 @@ def _vagrant_call(node, function, section, comment, status_when_done=None, **kwa ret = {"name": node, "changes": {}, "result": True, "comment": ""} targeted_nodes = [] - if isinstance(node, six.string_types): + if isinstance(node, str): try: # use shortcut if a single node name if __salt__["vagrant.get_vm_info"](node): targeted_nodes = [node] @@ -109,12 +103,12 @@ def _vagrant_call(node, function, section, comment, status_when_done=None, **kwa except (IndexError, SaltInvocationError, CommandExecutionError): pass try: - response = __salt__["vagrant.{0}".format(function)](node, **kwargs) + response = __salt__["vagrant.{}".format(function)](node, **kwargs) if isinstance(response, dict): response = response["name"] changed_nodes.append({"node": node, function: response}) except (SaltInvocationError, CommandExecutionError) as err: - ignored_nodes.append({"node": node, "issue": six.text_type(err)}) + ignored_nodes.append({"node": node, "issue": str(err)}) if not changed_nodes: ret["result"] = True ret["comment"] = "No changes seen" @@ -176,7 +170,7 @@ def running(name, **kwargs): "name": name, "changes": {}, "result": True, - "comment": "{0} is already running".format(name), + "comment": "{} is already running".format(name), } try: @@ -184,14 +178,14 @@ def running(name, **kwargs): if info[0]["state"] != "running": __salt__["vagrant.start"](name) ret["changes"][name] = "Machine started" - ret["comment"] = "Node {0} started".format(name) + ret["comment"] = "Node {} started".format(name) except (SaltInvocationError, CommandExecutionError): # there was no viable existing machine to start ret, kwargs = _find_init_change(name, ret, **kwargs) kwargs["start"] = True __salt__["vagrant.init"](name, **kwargs) ret["changes"][name] = "Node defined and started" - ret["comment"] = "Node {0} defined and started".format(name) + ret["comment"] = "Node {} defined and started".format(name) return ret @@ -278,7 +272,7 @@ def initialized(name, **kwargs): kwargs["start"] = False __salt__["vagrant.init"](name, **kwargs) ret["changes"][name] = "Node initialized" - ret["comment"] = "Node {0} defined but not started.".format(name) + ret["comment"] = "Node {} defined but not started.".format(name) return ret diff --git a/salt/states/vault.py b/salt/states/vault.py index a4060b9d2f5..54de5b8f435 100644 --- a/salt/states/vault.py +++ b/salt/states/vault.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ States for managing Hashicorp Vault. Currently handles policies. Configuration instructions are documented in the execution module docs. @@ -10,8 +9,6 @@ Currently handles policies. Configuration instructions are documented in the exe .. versionadded:: 2017.7.0 """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import difflib import logging @@ -44,7 +41,7 @@ def policy_present(name, rules): } """ - url = "v1/sys/policy/{0}".format(name) + url = "v1/sys/policy/{}".format(name) response = __utils__["vault.make_request"]("GET", url) try: if response.status_code == 200: @@ -58,7 +55,7 @@ def policy_present(name, rules): "name": name, "changes": {}, "result": False, - "comment": "Failed to get policy: {0}".format(e), + "comment": "Failed to get policy: {}".format(e), } @@ -72,14 +69,14 @@ def _create_new_policy(name, rules): } payload = {"rules": rules} - url = "v1/sys/policy/{0}".format(name) + url = "v1/sys/policy/{}".format(name) response = __utils__["vault.make_request"]("PUT", url, json=payload) if response.status_code not in [200, 204]: return { "name": name, "changes": {}, "result": False, - "comment": "Failed to create policy: {0}".format(response.reason), + "comment": "Failed to create policy: {}".format(response.reason), } return { @@ -111,14 +108,14 @@ def _handle_existing_policy(name, new_rules, existing_rules): payload = {"rules": new_rules} - url = "v1/sys/policy/{0}".format(name) + url = "v1/sys/policy/{}".format(name) response = __utils__["vault.make_request"]("PUT", url, json=payload) if response.status_code not in [200, 204]: return { "name": name, "changes": {}, "result": False, - "comment": "Failed to change policy: {0}".format(response.reason), + "comment": "Failed to change policy: {}".format(response.reason), } ret["result"] = True diff --git a/salt/states/vbox_guest.py b/salt/states/vbox_guest.py index ba6bd5731ac..1ae98b79545 100644 --- a/salt/states/vbox_guest.py +++ b/salt/states/vbox_guest.py @@ -1,10 +1,7 @@ -# -*- coding: utf-8 -*- """ VirtualBox Guest Additions installer state """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import logging log = logging.getLogger(__name__) diff --git a/salt/states/victorops.py b/salt/states/victorops.py index 6f46195a0c2..54cf5353a2c 100644 --- a/salt/states/victorops.py +++ b/salt/states/victorops.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Create an Event in VictorOps ============================ @@ -17,9 +16,6 @@ VictorOps service during state runs. - state_message: 'Webserver diskspace is low.' """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - def __virtual__(): """ @@ -97,7 +93,7 @@ def create_event(name, message_type, routing_key="everyone", **kwargs): ret = {"name": name, "changes": {}, "result": None, "comment": ""} if __opts__["test"]: - ret["comment"] = "Need to create event: {0}".format(name) + ret["comment"] = "Need to create event: {}".format(name) return ret res = __salt__["victorops.create_event"]( @@ -105,10 +101,10 @@ def create_event(name, message_type, routing_key="everyone", **kwargs): ) if res["result"] == "success": ret["result"] = True - ret["comment"] = "Created event: {0} for entity {1}".format( + ret["comment"] = "Created event: {} for entity {}".format( name, res["entity_id"] ) else: ret["result"] = False - ret["comment"] = "Failed to create event: {0}".format(res["message"]) + ret["comment"] = "Failed to create event: {}".format(res["message"]) return ret diff --git a/salt/states/virtualenv_mod.py b/salt/states/virtualenv_mod.py index a052432ecee..23eb55657dd 100644 --- a/salt/states/virtualenv_mod.py +++ b/salt/states/virtualenv_mod.py @@ -1,12 +1,9 @@ -# -*- coding: utf-8 -*- """ Setup of Python virtualenv sandboxes. .. versionadded:: 0.17.0 """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import logging import os @@ -14,14 +11,9 @@ import os import salt.utils.functools import salt.utils.platform import salt.utils.versions - -# Import Salt libs import salt.version from salt.exceptions import CommandExecutionError, CommandNotFoundError -# Import 3rd-party libs -from salt.ext import six - log = logging.getLogger(__name__) # Define the module's virtual name @@ -169,7 +161,7 @@ def managed( ret.update( { "result": False, - "comment": "pip requirements file '{0}' not found".format( + "comment": "pip requirements file '{}' not found".format( requirements ), } @@ -181,20 +173,20 @@ def managed( if venv_exists and clear: ret["changes"]["cleared_packages"] = __salt__["pip.freeze"](bin_env=name) ret["changes"]["old"] = __salt__["cmd.run_stderr"]( - "{0} -V".format(venv_py) + "{} -V".format(venv_py) ).strip("\n") # Create (or clear) the virtualenv if __opts__["test"]: if venv_exists and clear: ret["result"] = None - ret["comment"] = "Virtualenv {0} is set to be cleared".format(name) + ret["comment"] = "Virtualenv {} is set to be cleared".format(name) return ret if venv_exists and not clear: - ret["comment"] = "Virtualenv {0} is already created".format(name) + ret["comment"] = "Virtualenv {} is already created".format(name) return ret ret["result"] = None - ret["comment"] = "Virtualenv {0} is set to be created".format(name) + ret["comment"] = "Virtualenv {} is set to be created".format(name) return ret if not venv_exists or (venv_exists and clear): @@ -215,7 +207,7 @@ def managed( ) except CommandNotFoundError as err: ret["result"] = False - ret["comment"] = "Failed to create virtualenv: {0}".format(err) + ret["comment"] = "Failed to create virtualenv: {}".format(err) return ret if venv_ret["retcode"] != 0: @@ -225,7 +217,7 @@ def managed( ret["result"] = True ret["changes"]["new"] = __salt__["cmd.run_stderr"]( - "{0} -V".format(venv_py) + "{} -V".format(venv_py) ).strip("\n") if clear: @@ -251,8 +243,8 @@ def managed( ret["result"] = False ret["comment"] = ( "The 'use_wheel' option is only supported in " - "pip between {0} and {1}. The version of pip detected " - "was {2}." + "pip between {} and {}. The version of pip detected " + "was {}." ).format(min_version, max_version, cur_version) return ret @@ -271,8 +263,8 @@ def managed( ret["result"] = False ret["comment"] = ( "The 'no_use_wheel' option is only supported in " - "pip between {0} and {1}. The version of pip detected " - "was {2}." + "pip between {} and {}. The version of pip detected " + "was {}." ).format(min_version, max_version, cur_version) return ret @@ -287,8 +279,8 @@ def managed( ret["result"] = False ret["comment"] = ( "The 'no_binary' option is only supported in " - "pip {0} and newer. The version of pip detected " - "was {1}." + "pip {} and newer. The version of pip detected " + "was {}." ).format(min_version, cur_version) return ret @@ -303,7 +295,7 @@ def managed( if requirements: - if isinstance(requirements, six.string_types): + if isinstance(requirements, str): req_canary = requirements.split(",")[0] elif isinstance(requirements, list): req_canary = requirements[0] @@ -341,7 +333,7 @@ def managed( ) ret["result"] &= pip_ret["retcode"] == 0 if pip_ret["retcode"] > 0: - ret["comment"] = "{0}\n{1}\n{2}".format( + ret["comment"] = "{}\n{}\n{}".format( ret["comment"], pip_ret["stdout"], pip_ret["stderr"] ) diff --git a/salt/states/webutil.py b/salt/states/webutil.py index b2ac9eb779c..b026da6fd62 100644 --- a/salt/states/webutil.py +++ b/salt/states/webutil.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Support for htpasswd module. Requires the apache2-utils package for Debian-based distros. @@ -15,10 +14,7 @@ Support for htpasswd module. Requires the apache2-utils package for Debian-based """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals -# Import Salt libs import salt.utils.path __virtualname__ = "webutil" @@ -70,7 +66,7 @@ def user_exists( """ ret = {"name": name, "changes": {}, "comment": "", "result": None} - exists = __salt__["file.grep"](htpasswd_file, "^{0}:".format(name))["retcode"] == 0 + exists = __salt__["file.grep"](htpasswd_file, "^{}:".format(name))["retcode"] == 0 # If user exists, but we're supposed to update the password, find out if # it's changed, but not if we're forced to update the file regardless. @@ -83,7 +79,7 @@ def user_exists( if not exists or password_changed or force: if __opts__["test"]: ret["result"] = None - ret["comment"] = "User '{0}' is set to be added to htpasswd file".format( + ret["comment"] = "User '{}' is set to be added to htpasswd file".format( name ) ret["changes"] = {name: True} @@ -126,7 +122,7 @@ def user_absent(name, htpasswd_file=None, runas=None): """ ret = {"name": name, "changes": {}, "comment": "", "result": None} - exists = __salt__["file.grep"](htpasswd_file, "^{0}:".format(name))["retcode"] == 0 + exists = __salt__["file.grep"](htpasswd_file, "^{}:".format(name))["retcode"] == 0 if not exists: if __opts__["test"]: @@ -137,9 +133,9 @@ def user_absent(name, htpasswd_file=None, runas=None): else: if __opts__["test"]: ret["result"] = None - ret[ - "comment" - ] = "User '{0}' is set to be removed from htpasswd file".format(name) + ret["comment"] = "User '{}' is set to be removed from htpasswd file".format( + name + ) ret["changes"] = {name: True} else: userdel_ret = __salt__["webutil.userdel"]( diff --git a/salt/states/wordpress.py b/salt/states/wordpress.py index d1c7226e610..e672e30be4a 100644 --- a/salt/states/wordpress.py +++ b/salt/states/wordpress.py @@ -1,13 +1,9 @@ -# -*- coding: utf-8 -*- """ This state module is used to manage Wordpress installations :depends: wp binary from http://wp-cli.org/ """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - def __virtual__(): if "wordpress.show_plugin" in __salt__: @@ -57,11 +53,11 @@ def installed(name, user, admin_user, admin_password, admin_email, title, url): if check: ret["result"] = True - ret["comment"] = "Wordpress is already installed: {0}".format(name) + ret["comment"] = "Wordpress is already installed: {}".format(name) return ret elif __opts__["test"]: ret["result"] = None - ret["comment"] = "Wordpress will be installed: {0}".format(name) + ret["comment"] = "Wordpress will be installed: {}".format(name) return ret resp = __salt__["wordpress.install"]( @@ -69,10 +65,10 @@ def installed(name, user, admin_user, admin_password, admin_email, title, url): ) if resp: ret["result"] = True - ret["comment"] = "Wordpress Installed: {0}".format(name) + ret["comment"] = "Wordpress Installed: {}".format(name) ret["changes"] = {"new": resp} else: - ret["comment"] = "Failed to install wordpress: {0}".format(name) + ret["comment"] = "Failed to install wordpress: {}".format(name) return ret @@ -103,30 +99,30 @@ def activated(name, path, user): if check["status"] == "active": ret["result"] = True - ret["comment"] = "Plugin already activated: {0}".format(name) + ret["comment"] = "Plugin already activated: {}".format(name) return ret elif __opts__["test"]: ret["result"] = None - ret["comment"] = "Plugin will be activated: {0}".format(name) + ret["comment"] = "Plugin will be activated: {}".format(name) return ret resp = __salt__["wordpress.activate"](name, path, user) if resp is True: ret["result"] = True - ret["comment"] = "Plugin activated: {0}".format(name) + ret["comment"] = "Plugin activated: {}".format(name) ret["changes"] = { "old": check, "new": __salt__["wordpress.show_plugin"](name, path, user), } elif resp is None: ret["result"] = True - ret["comment"] = "Plugin already activated: {0}".format(name) + ret["comment"] = "Plugin already activated: {}".format(name) ret["changes"] = { "old": check, "new": __salt__["wordpress.show_plugin"](name, path, user), } else: - ret["comment"] = "Plugin failed to activate: {0}".format(name) + ret["comment"] = "Plugin failed to activate: {}".format(name) return ret @@ -157,29 +153,29 @@ def deactivated(name, path, user): if check["status"] == "inactive": ret["result"] = True - ret["comment"] = "Plugin already deactivated: {0}".format(name) + ret["comment"] = "Plugin already deactivated: {}".format(name) return ret elif __opts__["test"]: ret["result"] = None - ret["comment"] = "Plugin will be deactivated: {0}".format(name) + ret["comment"] = "Plugin will be deactivated: {}".format(name) return ret resp = __salt__["wordpress.deactivate"](name, path, user) if resp is True: ret["result"] = True - ret["comment"] = "Plugin deactivated: {0}".format(name) + ret["comment"] = "Plugin deactivated: {}".format(name) ret["changes"] = { "old": check, "new": __salt__["wordpress.show_plugin"](name, path, user), } elif resp is None: ret["result"] = True - ret["comment"] = "Plugin already deactivated: {0}".format(name) + ret["comment"] = "Plugin already deactivated: {}".format(name) ret["changes"] = { "old": check, "new": __salt__["wordpress.show_plugin"](name, path, user), } else: - ret["comment"] = "Plugin failed to deactivate: {0}".format(name) + ret["comment"] = "Plugin failed to deactivate: {}".format(name) return ret diff --git a/salt/states/xml.py b/salt/states/xml.py index 64b36e15923..67cf30a825b 100644 --- a/salt/states/xml.py +++ b/salt/states/xml.py @@ -1,13 +1,10 @@ -# -*- coding: utf-8 -*- """ XML Manager =========== State management of XML files """ -from __future__ import absolute_import, print_function, unicode_literals -# Import Python libs import logging log = logging.getLogger(__name__) @@ -54,20 +51,20 @@ def value_present(name, xpath, value, **kwargs): current_value = __salt__["xml.get_value"](name, xpath) if not current_value: ret["result"] = False - ret["comment"] = "xpath query {0} not found in {1}".format(xpath, name) + ret["comment"] = "xpath query {} not found in {}".format(xpath, name) return ret if current_value != value: if kwargs["test"]: ret["result"] = None - ret["comment"] = "{0} will be updated".format(name) + ret["comment"] = "{} will be updated".format(name) ret["changes"] = {name: {"old": current_value, "new": value}} else: results = __salt__["xml.set_value"](name, xpath, value) ret["result"] = results - ret["comment"] = "{0} updated".format(name) + ret["comment"] = "{} updated".format(name) ret["changes"] = {name: {"old": current_value, "new": value}} else: - ret["comment"] = "{0} is already present".format(value) + ret["comment"] = "{} is already present".format(value) return ret diff --git a/salt/states/xmpp.py b/salt/states/xmpp.py index b67c31abbe7..5d07238015a 100644 --- a/salt/states/xmpp.py +++ b/salt/states/xmpp.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Sending Messages over XMPP ========================== @@ -17,9 +16,6 @@ protocol - recipient: admins@xmpp.example.com/salt """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - def __virtual__(): """ @@ -47,13 +43,13 @@ def send_msg(name, recipient, profile): """ ret = {"name": name, "changes": {}, "result": None, "comment": ""} if __opts__["test"]: - ret["comment"] = "Need to send message to {0}: {1}".format(recipient, name,) + ret["comment"] = "Need to send message to {}: {}".format(recipient, name,) return ret __salt__["xmpp.send_msg_multi"]( message=name, recipients=[recipient], profile=profile, ) ret["result"] = True - ret["comment"] = "Sent message to {0}: {1}".format(recipient, name) + ret["comment"] = "Sent message to {}: {}".format(recipient, name) return ret @@ -83,10 +79,10 @@ def send_msg_multi(name, profile, recipients=None, rooms=None): comment = "" if recipients: - comment += " users {0}".format(recipients) + comment += " users {}".format(recipients) if rooms: - comment += " rooms {0}".format(rooms) - comment += ", message: {0}".format(name) + comment += " rooms {}".format(rooms) + comment += ", message: {}".format(name) if __opts__["test"]: ret["comment"] = "Need to send" + comment diff --git a/salt/states/zabbix_action.py b/salt/states/zabbix_action.py index e17340ff44a..457c27f3102 100644 --- a/salt/states/zabbix_action.py +++ b/salt/states/zabbix_action.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ .. versionadded:: 2017.7 @@ -6,19 +5,11 @@ Management of Zabbix Action object over Zabbix API. :codeauthor: Jakub Sliva """ -from __future__ import absolute_import, unicode_literals import json import logging -try: - from salt.ext import six - from salt.exceptions import SaltException - - IMPORTS_OK = True -except ImportError: - IMPORTS_OK = False - +from salt.exceptions import SaltException log = logging.getLogger(__name__) @@ -28,7 +19,7 @@ def __virtual__(): Only make these states available if Zabbix module and run_query function is available and all 3rd party modules imported. """ - if "zabbix.run_query" in __salt__ and IMPORTS_OK: + if "zabbix.run_query" in __salt__: return True return False, "Import zabbix or other needed modules failed." @@ -90,8 +81,7 @@ def present(name, params, **kwargs): input_params = __salt__["zabbix.substitute_params"](params, **kwargs) log.info( - "Zabbix Action: input params: %s", - six.text_type(json.dumps(input_params, indent=4)), + "Zabbix Action: input params: %s", str(json.dumps(input_params, indent=4)), ) search = { @@ -103,8 +93,7 @@ def present(name, params, **kwargs): # GET Action object if exists action_get = __salt__["zabbix.run_query"]("action.get", search, **kwargs) log.info( - "Zabbix Action: action.get result: %s", - six.text_type(json.dumps(action_get, indent=4)), + "Zabbix Action: action.get result: %s", str(json.dumps(action_get, indent=4)), ) existing_obj = ( @@ -116,12 +105,11 @@ def present(name, params, **kwargs): if existing_obj: diff_params = __salt__["zabbix.compare_params"](input_params, existing_obj) log.info( - "Zabbix Action: input params: {%s", - six.text_type(json.dumps(input_params, indent=4)), + "Zabbix Action: input params: {%s", str(json.dumps(input_params, indent=4)), ) log.info( "Zabbix Action: Object comparison result. Differences: %s", - six.text_type(diff_params), + str(diff_params), ) if diff_params: @@ -131,17 +119,17 @@ def present(name, params, **kwargs): # diff_params['name'] = 'VMs' - BUG - https://support.zabbix.com/browse/ZBX-12078 log.info( "Zabbix Action: update params: %s", - six.text_type(json.dumps(diff_params, indent=4)), + str(json.dumps(diff_params, indent=4)), ) if dry_run: ret["result"] = True - ret["comment"] = 'Zabbix Action "{0}" would be fixed.'.format(name) + ret["comment"] = 'Zabbix Action "{}" would be fixed.'.format(name) ret["changes"] = { name: { - "old": 'Zabbix Action "{0}" differs ' - "in following parameters: {1}".format(name, diff_params), - "new": 'Zabbix Action "{0}" would correspond to definition.'.format( + "old": 'Zabbix Action "{}" differs ' + "in following parameters: {}".format(name, diff_params), + "new": 'Zabbix Action "{}" would correspond to definition.'.format( name ), } @@ -151,17 +139,16 @@ def present(name, params, **kwargs): "action.update", diff_params, **kwargs ) log.info( - "Zabbix Action: action.update result: %s", - six.text_type(action_update), + "Zabbix Action: action.update result: %s", str(action_update), ) if action_update: ret["result"] = True - ret["comment"] = 'Zabbix Action "{0}" updated.'.format(name) + ret["comment"] = 'Zabbix Action "{}" updated.'.format(name) ret["changes"] = { name: { - "old": 'Zabbix Action "{0}" differed ' - "in following parameters: {1}".format(name, diff_params), - "new": 'Zabbix Action "{0}" fixed.'.format(name), + "old": 'Zabbix Action "{}" differed ' + "in following parameters: {}".format(name, diff_params), + "new": 'Zabbix Action "{}" fixed.'.format(name), } } @@ -169,18 +156,18 @@ def present(name, params, **kwargs): ret["result"] = True ret[ "comment" - ] = 'Zabbix Action "{0}" already exists and corresponds to a definition.'.format( + ] = 'Zabbix Action "{}" already exists and corresponds to a definition.'.format( name ) else: if dry_run: ret["result"] = True - ret["comment"] = 'Zabbix Action "{0}" would be created.'.format(name) + ret["comment"] = 'Zabbix Action "{}" would be created.'.format(name) ret["changes"] = { name: { - "old": 'Zabbix Action "{0}" does not exist.'.format(name), - "new": 'Zabbix Action "{0}" would be created according definition.'.format( + "old": 'Zabbix Action "{}" does not exist.'.format(name), + "new": 'Zabbix Action "{}" would be created according definition.'.format( name ), } @@ -190,17 +177,15 @@ def present(name, params, **kwargs): action_create = __salt__["zabbix.run_query"]( "action.create", input_params, **kwargs ) - log.info( - "Zabbix Action: action.create result: %s", six.text_type(action_create) - ) + log.info("Zabbix Action: action.create result: %s", str(action_create)) if action_create: ret["result"] = True - ret["comment"] = 'Zabbix Action "{0}" created.'.format(name) + ret["comment"] = 'Zabbix Action "{}" created.'.format(name) ret["changes"] = { name: { - "old": 'Zabbix Action "{0}" did not exist.'.format(name), - "new": 'Zabbix Action "{0}" created according definition.'.format( + "old": 'Zabbix Action "{}" did not exist.'.format(name), + "new": 'Zabbix Action "{}" created according definition.'.format( name ), } @@ -236,15 +221,15 @@ def absent(name, **kwargs): if not object_id: ret["result"] = True - ret["comment"] = 'Zabbix Action "{0}" does not exist.'.format(name) + ret["comment"] = 'Zabbix Action "{}" does not exist.'.format(name) else: if dry_run: ret["result"] = True - ret["comment"] = 'Zabbix Action "{0}" would be deleted.'.format(name) + ret["comment"] = 'Zabbix Action "{}" would be deleted.'.format(name) ret["changes"] = { name: { - "old": 'Zabbix Action "{0}" exists.'.format(name), - "new": 'Zabbix Action "{0}" would be deleted.'.format(name), + "old": 'Zabbix Action "{}" exists.'.format(name), + "new": 'Zabbix Action "{}" would be deleted.'.format(name), } } else: @@ -254,11 +239,11 @@ def absent(name, **kwargs): if action_delete: ret["result"] = True - ret["comment"] = 'Zabbix Action "{0}" deleted.'.format(name) + ret["comment"] = 'Zabbix Action "{}" deleted.'.format(name) ret["changes"] = { name: { - "old": 'Zabbix Action "{0}" existed.'.format(name), - "new": 'Zabbix Action "{0}" deleted.'.format(name), + "old": 'Zabbix Action "{}" existed.'.format(name), + "new": 'Zabbix Action "{}" deleted.'.format(name), } } diff --git a/salt/states/zabbix_hostgroup.py b/salt/states/zabbix_hostgroup.py index d7bb754f8c1..9822f160eec 100644 --- a/salt/states/zabbix_hostgroup.py +++ b/salt/states/zabbix_hostgroup.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of Zabbix host groups. @@ -7,12 +6,6 @@ Management of Zabbix host groups. """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - -# Import Salt libs -from salt.ext import six - def __virtual__(): """ @@ -52,13 +45,13 @@ def present(name, **kwargs): ret = {"name": name, "changes": {}, "result": False, "comment": ""} # Comment and change messages - comment_hostgroup_created = "Host group {0} created.".format(name) - comment_hostgroup_notcreated = "Unable to create host group: {0}. ".format(name) - comment_hostgroup_exists = "Host group {0} already exists.".format(name) + comment_hostgroup_created = "Host group {} created.".format(name) + comment_hostgroup_notcreated = "Unable to create host group: {}. ".format(name) + comment_hostgroup_exists = "Host group {} already exists.".format(name) changes_hostgroup_created = { name: { - "old": "Host group {0} does not exist.".format(name), - "new": "Host group {0} created.".format(name), + "old": "Host group {} does not exist.".format(name), + "new": "Host group {} created.".format(name), } } @@ -87,7 +80,7 @@ def present(name, **kwargs): ret["changes"] = changes_hostgroup_created else: ret["result"] = False - ret["comment"] = comment_hostgroup_notcreated + six.text_type( + ret["comment"] = comment_hostgroup_notcreated + str( hostgroup_create["error"] ) @@ -116,13 +109,13 @@ def absent(name, **kwargs): ret = {"name": name, "changes": {}, "result": False, "comment": ""} # Comment and change messages - comment_hostgroup_deleted = "Host group {0} deleted.".format(name) - comment_hostgroup_notdeleted = "Unable to delete host group: {0}. ".format(name) - comment_hostgroup_notexists = "Host group {0} does not exist.".format(name) + comment_hostgroup_deleted = "Host group {} deleted.".format(name) + comment_hostgroup_notdeleted = "Unable to delete host group: {}. ".format(name) + comment_hostgroup_notexists = "Host group {} does not exist.".format(name) changes_hostgroup_deleted = { name: { - "old": "Host group {0} exists.".format(name), - "new": "Host group {0} deleted.".format(name), + "old": "Host group {} exists.".format(name), + "new": "Host group {} deleted.".format(name), } } @@ -167,7 +160,7 @@ def absent(name, **kwargs): ret["changes"] = changes_hostgroup_deleted else: ret["result"] = False - ret["comment"] = comment_hostgroup_notdeleted + six.text_type( + ret["comment"] = comment_hostgroup_notdeleted + str( hostgroup_delete["error"] ) diff --git a/salt/states/zabbix_mediatype.py b/salt/states/zabbix_mediatype.py index 4b57534b015..4c29914adab 100644 --- a/salt/states/zabbix_mediatype.py +++ b/salt/states/zabbix_mediatype.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of Zabbix mediatypes. @@ -6,12 +5,6 @@ Management of Zabbix mediatypes. """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - -# Import Salt libs -from salt.ext import six - def __virtual__(): """ @@ -56,14 +49,14 @@ def present(name, mediatype, **kwargs): ret = {"name": name, "changes": {}, "result": False, "comment": ""} # Comment and change messages - comment_mediatype_created = "Mediatype {0} created.".format(name) - comment_mediatype_updated = "Mediatype {0} updated.".format(name) - comment_mediatype_notcreated = "Unable to create mediatype: {0}. ".format(name) - comment_mediatype_exists = "Mediatype {0} already exists.".format(name) + comment_mediatype_created = "Mediatype {} created.".format(name) + comment_mediatype_updated = "Mediatype {} updated.".format(name) + comment_mediatype_notcreated = "Unable to create mediatype: {}. ".format(name) + comment_mediatype_exists = "Mediatype {} already exists.".format(name) changes_mediatype_created = { name: { - "old": "Mediatype {0} does not exist.".format(name), - "new": "Mediatype {0} created.".format(name), + "old": "Mediatype {} does not exist.".format(name), + "new": "Mediatype {} created.".format(name), } } @@ -72,7 +65,7 @@ def present(name, mediatype, **kwargs): if isinstance(kwargs["exec_params"], list): kwargs["exec_params"] = "\n".join(kwargs["exec_params"]) + "\n" else: - kwargs["exec_params"] = six.text_type(kwargs["exec_params"]) + "\n" + kwargs["exec_params"] = str(kwargs["exec_params"]) + "\n" mediatype_exists = __salt__["zabbix.mediatype_get"](name, **connection_args) @@ -372,7 +365,7 @@ def present(name, mediatype, **kwargs): ret["changes"] = changes_mediatype_created else: ret["result"] = False - ret["comment"] = comment_mediatype_notcreated + six.text_type( + ret["comment"] = comment_mediatype_notcreated + str( mediatype_create["error"] ) @@ -380,7 +373,7 @@ def present(name, mediatype, **kwargs): if error: ret["changes"] = {} ret["result"] = False - ret["comment"] = six.text_type(error) + ret["comment"] = str(error) return ret @@ -411,13 +404,13 @@ def absent(name, **kwargs): ret = {"name": name, "changes": {}, "result": False, "comment": ""} # Comment and change messages - comment_mediatype_deleted = "Mediatype {0} deleted.".format(name) - comment_mediatype_notdeleted = "Unable to delete mediatype: {0}. ".format(name) - comment_mediatype_notexists = "Mediatype {0} does not exist.".format(name) + comment_mediatype_deleted = "Mediatype {} deleted.".format(name) + comment_mediatype_notdeleted = "Unable to delete mediatype: {}. ".format(name) + comment_mediatype_notexists = "Mediatype {} does not exist.".format(name) changes_mediatype_deleted = { name: { - "old": "Mediatype {0} exists.".format(name), - "new": "Mediatype {0} deleted.".format(name), + "old": "Mediatype {} exists.".format(name), + "new": "Mediatype {} deleted.".format(name), } } @@ -451,7 +444,7 @@ def absent(name, **kwargs): ret["changes"] = changes_mediatype_deleted else: ret["result"] = False - ret["comment"] = comment_mediatype_notdeleted + six.text_type( + ret["comment"] = comment_mediatype_notdeleted + str( mediatype_delete["error"] ) diff --git a/salt/states/zabbix_template.py b/salt/states/zabbix_template.py index d21aeefd3a2..76074a925b9 100644 --- a/salt/states/zabbix_template.py +++ b/salt/states/zabbix_template.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ .. versionadded:: 2017.7 @@ -6,19 +5,11 @@ Management of Zabbix Template object over Zabbix API. :codeauthor: Jakub Sliva """ -from __future__ import absolute_import, unicode_literals import json import logging -try: - from salt.ext import six - from salt.exceptions import SaltException - - IMPORTS_OK = True -except ImportError: - IMPORTS_OK = False - +from salt.exceptions import SaltException log = logging.getLogger(__name__) @@ -284,7 +275,7 @@ def __virtual__(): Only make these states available if Zabbix module and run_query function is available and all 3rd party modules imported. """ - if "zabbix.run_query" in __salt__ and IMPORTS_OK: + if "zabbix.run_query" in __salt__: return True return False, "Import zabbix or other needed modules failed." @@ -299,16 +290,14 @@ def _diff_and_merge_host_list(defined, existing): :return: list to be updated (combinated or empty list) """ try: - defined_host_ids = set([host["hostid"] for host in defined]) - existing_host_ids = set([host["hostid"] for host in existing]) + defined_host_ids = {host["hostid"] for host in defined} + existing_host_ids = {host["hostid"] for host in existing} except KeyError: raise SaltException("List of hosts in template not defined correctly.") diff = defined_host_ids - existing_host_ids return ( - [{"hostid": six.text_type(hostid)} for hostid in diff | existing_host_ids] - if diff - else [] + [{"hostid": str(hostid)} for hostid in diff | existing_host_ids] if diff else [] ) @@ -381,8 +370,8 @@ def _manage_component( c_def = TEMPLATE_COMPONENT_DEF[component] compare_key = c_def["filter"] - defined_set = set([item[compare_key] for item in defined]) - existing_set = set([item[compare_key] for item in existing]) + defined_set = {item[compare_key] for item in defined} + existing_set = {item[compare_key] for item in existing} create_set = defined_set - existing_set update_set = defined_set & existing_set @@ -498,10 +487,10 @@ def is_present(name, **kwargs): if not object_id: ret["result"] = False - ret["comment"] = 'Zabbix Template "{0}" does not exist.'.format(name) + ret["comment"] = 'Zabbix Template "{}" does not exist.'.format(name) else: ret["result"] = True - ret["comment"] = 'Zabbix Template "{0}" exists.'.format(name) + ret["comment"] = 'Zabbix Template "{}" exists.'.format(name) return ret @@ -649,10 +638,10 @@ def present(name, params, static_host_list=True, **kwargs): discovery_components = [] for attr in params: - if attr in TEMPLATE_COMPONENT_ORDER and six.text_type(attr) != "discoveries": + if attr in TEMPLATE_COMPONENT_ORDER and str(attr) != "discoveries": template_components[attr] = params[attr] - elif six.text_type(attr) == "discoveries": + elif str(attr) == "discoveries": d_rules = [] for d_rule in params[attr]: d_rule_components = { @@ -687,8 +676,7 @@ def present(name, params, static_host_list=True, **kwargs): defined_obj = __salt__["zabbix.substitute_params"](template_definition, **kwargs) log.info( - "SUBSTITUTED template_definition: %s", - six.text_type(json.dumps(defined_obj, indent=4)), + "SUBSTITUTED template_definition: %s", str(json.dumps(defined_obj, indent=4)), ) tmpl_get = __salt__["zabbix.run_query"]( @@ -703,7 +691,7 @@ def present(name, params, static_host_list=True, **kwargs): }, **kwargs ) - log.info("TEMPLATE get result: %s", six.text_type(json.dumps(tmpl_get, indent=4))) + log.info("TEMPLATE get result: %s", str(json.dumps(tmpl_get, indent=4))) existing_obj = ( __salt__["zabbix.substitute_params"](tmpl_get[0], **kwargs) @@ -752,8 +740,7 @@ def present(name, params, static_host_list=True, **kwargs): diff_params["new"][zabbix_id_mapper["template"]] = template_id diff_params["old"][zabbix_id_mapper["template"]] = template_id log.info( - "TEMPLATE: update params: %s", - six.text_type(json.dumps(diff_params, indent=4)), + "TEMPLATE: update params: %s", str(json.dumps(diff_params, indent=4)), ) CHANGE_STACK.append( @@ -767,7 +754,7 @@ def present(name, params, static_host_list=True, **kwargs): tmpl_update = __salt__["zabbix.run_query"]( "template.update", diff_params["new"], **kwargs ) - log.info("TEMPLATE update result: %s", six.text_type(tmpl_update)) + log.info("TEMPLATE update result: %s", str(tmpl_update)) else: CHANGE_STACK.append( @@ -777,22 +764,19 @@ def present(name, params, static_host_list=True, **kwargs): tmpl_create = __salt__["zabbix.run_query"]( "template.create", defined_obj, **kwargs ) - log.info("TEMPLATE create result: %s", six.text_type(tmpl_create)) + log.info("TEMPLATE create result: %s", str(tmpl_create)) if tmpl_create: template_id = tmpl_create["templateids"][0] log.info("\n\ntemplate_components: %s", json.dumps(template_components, indent=4)) log.info("\n\ndiscovery_components: %s", json.dumps(discovery_components, indent=4)) log.info( - "\n\nCurrent CHANGE_STACK: %s", - six.text_type(json.dumps(CHANGE_STACK, indent=4)), + "\n\nCurrent CHANGE_STACK: %s", str(json.dumps(CHANGE_STACK, indent=4)), ) if existing_obj or not dry_run: for component in TEMPLATE_COMPONENT_ORDER: - log.info( - "\n\n\n\n\nCOMPONENT: %s\n\n", six.text_type(json.dumps(component)) - ) + log.info("\n\n\n\n\nCOMPONENT: %s\n\n", str(json.dumps(component))) # 1) query for components which belongs to the template existing_c_list = _get_existing_template_c_list( component, template_id, **kwargs @@ -824,8 +808,7 @@ def present(name, params, static_host_list=True, **kwargs): ) log.info( - "\n\nCurrent CHANGE_STACK: %s", - six.text_type(json.dumps(CHANGE_STACK, indent=4)), + "\n\nCurrent CHANGE_STACK: %s", str(json.dumps(CHANGE_STACK, indent=4)), ) for d_rule_component in discovery_components: @@ -843,8 +826,7 @@ def present(name, params, static_host_list=True, **kwargs): for proto_name in DISCOVERYRULE_COMPONENT_ORDER: log.info( - "\n\n\n\n\nPROTOTYPE_NAME: %s\n\n", - six.text_type(json.dumps(proto_name)), + "\n\n\n\n\nPROTOTYPE_NAME: %s\n\n", str(json.dumps(proto_name)), ) existing_p_list = _get_existing_template_c_list( proto_name, parent_id, **kwargs @@ -874,15 +856,14 @@ def present(name, params, static_host_list=True, **kwargs): ) log.info( - "\n\nCurrent CHANGE_STACK: %s", - six.text_type(json.dumps(CHANGE_STACK, indent=4)), + "\n\nCurrent CHANGE_STACK: %s", str(json.dumps(CHANGE_STACK, indent=4)), ) if not CHANGE_STACK: ret["result"] = True ret[ "comment" - ] = 'Zabbix Template "{0}" already exists and corresponds to a definition.'.format( + ] = 'Zabbix Template "{}" already exists and corresponds to a definition.'.format( name ) else: @@ -897,20 +878,20 @@ def present(name, params, static_host_list=True, **kwargs): if tmpl_action: ret["result"] = True if dry_run: - ret["comment"] = 'Zabbix Template "{0}" would be created.'.format(name) + ret["comment"] = 'Zabbix Template "{}" would be created.'.format(name) ret["changes"] = { name: { - "old": 'Zabbix Template "{0}" does not exist.'.format(name), - "new": 'Zabbix Template "{0}" would be created ' + "old": 'Zabbix Template "{}" does not exist.'.format(name), + "new": 'Zabbix Template "{}" would be created ' "according definition.".format(name), } } else: - ret["comment"] = 'Zabbix Template "{0}" created.'.format(name) + ret["comment"] = 'Zabbix Template "{}" created.'.format(name) ret["changes"] = { name: { - "old": 'Zabbix Template "{0}" did not exist.'.format(name), - "new": 'Zabbix Template "{0}" created according definition.'.format( + "old": 'Zabbix Template "{}" did not exist.'.format(name), + "new": 'Zabbix Template "{}" created according definition.'.format( name ), } @@ -918,20 +899,20 @@ def present(name, params, static_host_list=True, **kwargs): else: ret["result"] = True if dry_run: - ret["comment"] = 'Zabbix Template "{0}" would be updated.'.format(name) + ret["comment"] = 'Zabbix Template "{}" would be updated.'.format(name) ret["changes"] = { name: { - "old": 'Zabbix Template "{0}" differs.'.format(name), - "new": 'Zabbix Template "{0}" would be updated ' + "old": 'Zabbix Template "{}" differs.'.format(name), + "new": 'Zabbix Template "{}" would be updated ' "according definition.".format(name), } } else: - ret["comment"] = 'Zabbix Template "{0}" updated.'.format(name) + ret["comment"] = 'Zabbix Template "{}" updated.'.format(name) ret["changes"] = { name: { - "old": 'Zabbix Template "{0}" differed.'.format(name), - "new": 'Zabbix Template "{0}" updated according definition.'.format( + "old": 'Zabbix Template "{}" differed.'.format(name), + "new": 'Zabbix Template "{}" updated according definition.'.format( name ), } @@ -967,15 +948,15 @@ def absent(name, **kwargs): if not object_id: ret["result"] = True - ret["comment"] = 'Zabbix Template "{0}" does not exist.'.format(name) + ret["comment"] = 'Zabbix Template "{}" does not exist.'.format(name) else: if dry_run: ret["result"] = True - ret["comment"] = 'Zabbix Template "{0}" would be deleted.'.format(name) + ret["comment"] = 'Zabbix Template "{}" would be deleted.'.format(name) ret["changes"] = { name: { - "old": 'Zabbix Template "{0}" exists.'.format(name), - "new": 'Zabbix Template "{0}" would be deleted.'.format(name), + "old": 'Zabbix Template "{}" exists.'.format(name), + "new": 'Zabbix Template "{}" would be deleted.'.format(name), } } else: @@ -984,11 +965,11 @@ def absent(name, **kwargs): ) if tmpl_delete: ret["result"] = True - ret["comment"] = 'Zabbix Template "{0}" deleted.'.format(name) + ret["comment"] = 'Zabbix Template "{}" deleted.'.format(name) ret["changes"] = { name: { - "old": 'Zabbix Template "{0}" existed.'.format(name), - "new": 'Zabbix Template "{0}" deleted.'.format(name), + "old": 'Zabbix Template "{}" existed.'.format(name), + "new": 'Zabbix Template "{}" deleted.'.format(name), } } diff --git a/salt/states/zabbix_user.py b/salt/states/zabbix_user.py index 4f4d4c577c2..29bde864ee9 100644 --- a/salt/states/zabbix_user.py +++ b/salt/states/zabbix_user.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of Zabbix users. @@ -7,15 +6,11 @@ Management of Zabbix users. """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals from copy import deepcopy -# Import Salt libs import salt.utils.json from salt.exceptions import SaltException -from salt.ext import six def __virtual__(): @@ -77,9 +72,7 @@ def admin_password_present(name, password=None, **kwargs): # get unique list in preserved order and reverse it seen = set() - unique_passwords = [ - six.text_type(x) for x in passwords if x not in seen and not seen.add(x) - ] + unique_passwords = [str(x) for x in passwords if x not in seen and not seen.add(x)] unique_passwords.reverse() if not unique_passwords: @@ -99,7 +92,7 @@ def admin_password_present(name, password=None, **kwargs): default_zabbix_user, **connection_args ) except SaltException as err: - if "Login name or password is incorrect" in six.text_type(err): + if "Login name or password is incorrect" in str(err): user_get = False else: raise @@ -118,16 +111,14 @@ def admin_password_present(name, password=None, **kwargs): ) if user_update: ret["result"] = True - ret["changes"]["passwd"] = ( - "changed to '" + six.text_type(desired_password) + "'" - ) + ret["changes"]["passwd"] = "changed to '" + str(desired_password) + "'" else: ret["result"] = None ret["comment"] = ( "Password for user " - + six.text_type(default_zabbix_user) + + str(default_zabbix_user) + " updated to '" - + six.text_type(desired_password) + + str(desired_password) + "'" ) @@ -193,14 +184,14 @@ def present(alias, passwd, usrgrps, medias=None, password_reset=False, **kwargs) ret = {"name": alias, "changes": {}, "result": False, "comment": ""} # Comment and change messages - comment_user_created = "User {0} created.".format(alias) - comment_user_updated = "User {0} updated.".format(alias) - comment_user_notcreated = "Unable to create user: {0}. ".format(alias) - comment_user_exists = "User {0} already exists.".format(alias) + comment_user_created = "User {} created.".format(alias) + comment_user_updated = "User {} updated.".format(alias) + comment_user_notcreated = "Unable to create user: {}. ".format(alias) + comment_user_exists = "User {} already exists.".format(alias) changes_user_created = { alias: { - "old": "User {0} does not exist.".format(alias), - "new": "User {0} created.".format(alias), + "old": "User {} does not exist.".format(alias), + "new": "User {} created.".format(alias), } } @@ -231,24 +222,20 @@ def present(alias, passwd, usrgrps, medias=None, password_reset=False, **kwargs) medias_list = list() for key, value in medias_dict.items(): # Load media values or default values - active = ( - "0" - if six.text_type(value.get("active", "true")).lower() == "true" - else "1" - ) - mediatype_sls = six.text_type(value.get("mediatype", "mail")).lower() - mediatypeid = six.text_type(media_type.get(mediatype_sls, 1)) + active = "0" if str(value.get("active", "true")).lower() == "true" else "1" + mediatype_sls = str(value.get("mediatype", "mail")).lower() + mediatypeid = str(media_type.get(mediatype_sls, 1)) period = value.get("period", "1-7,00:00-24:00") sendto = value.get("sendto", key) severity_sls = value.get("severity", "HD") - severity_bin = six.text_type() + severity_bin = "" for sev in media_severities: if sev in severity_sls: severity_bin += "1" else: severity_bin += "0" - severity = six.text_type(int(severity_bin, 2)) + severity = str(int(severity_bin, 2)) medias_list.append( { @@ -330,9 +317,9 @@ def present(alias, passwd, usrgrps, medias=None, password_reset=False, **kwargs) usrgrp_diff = list(set(usrgrps) - set(cur_usrgrps)) if usrgrp_diff: - error.append("Unable to update grpup(s): {0}".format(usrgrp_diff)) + error.append("Unable to update grpup(s): {}".format(usrgrp_diff)) - ret["changes"]["usrgrps"] = six.text_type(updated_groups) + ret["changes"]["usrgrps"] = str(updated_groups) if password_reset: updated_password = __salt__["zabbix.user_update"]( @@ -365,7 +352,7 @@ def present(alias, passwd, usrgrps, medias=None, password_reset=False, **kwargs) if "error" in updatemed: error.append(updatemed["error"]) - ret["changes"]["medias"] = six.text_type(medias_formated) + ret["changes"]["medias"] = str(medias_formated) else: ret["comment"] = comment_user_exists @@ -378,15 +365,13 @@ def present(alias, passwd, usrgrps, medias=None, password_reset=False, **kwargs) ret["changes"] = changes_user_created else: ret["result"] = False - ret["comment"] = comment_user_notcreated + six.text_type( - user_create["error"] - ) + ret["comment"] = comment_user_notcreated + str(user_create["error"]) # error detected if error: ret["changes"] = {} ret["result"] = False - ret["comment"] = six.text_type(error) + ret["comment"] = str(error) return ret @@ -419,13 +404,13 @@ def absent(name, **kwargs): ret = {"name": name, "changes": {}, "result": False, "comment": ""} # Comment and change messages - comment_user_deleted = "USer {0} deleted.".format(name) - comment_user_notdeleted = "Unable to delete user: {0}. ".format(name) - comment_user_notexists = "User {0} does not exist.".format(name) + comment_user_deleted = "USer {} deleted.".format(name) + comment_user_notdeleted = "Unable to delete user: {}. ".format(name) + comment_user_notexists = "User {} does not exist.".format(name) changes_user_deleted = { name: { - "old": "User {0} exists.".format(name), - "new": "User {0} deleted.".format(name), + "old": "User {} exists.".format(name), + "new": "User {} deleted.".format(name), } } @@ -457,8 +442,6 @@ def absent(name, **kwargs): ret["changes"] = changes_user_deleted else: ret["result"] = False - ret["comment"] = comment_user_notdeleted + six.text_type( - user_delete["error"] - ) + ret["comment"] = comment_user_notdeleted + str(user_delete["error"]) return ret diff --git a/salt/states/zabbix_usergroup.py b/salt/states/zabbix_usergroup.py index c7d854a1cf0..0a054228866 100644 --- a/salt/states/zabbix_usergroup.py +++ b/salt/states/zabbix_usergroup.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of Zabbix user groups. @@ -6,12 +5,6 @@ Management of Zabbix user groups. """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - -# Import Salt libs -from salt.ext import six - def __virtual__(): """ @@ -57,14 +50,14 @@ def present(name, **kwargs): ret = {"name": name, "changes": {}, "result": False, "comment": ""} # Comment and change messages - comment_usergroup_created = "User group {0} created.".format(name) - comment_usergroup_updated = "User group {0} updated.".format(name) - comment_usergroup_notcreated = "Unable to create user group: {0}. ".format(name) - comment_usergroup_exists = "User group {0} already exists.".format(name) + comment_usergroup_created = "User group {} created.".format(name) + comment_usergroup_updated = "User group {} updated.".format(name) + comment_usergroup_notcreated = "Unable to create user group: {}. ".format(name) + comment_usergroup_exists = "User group {} already exists.".format(name) changes_usergroup_created = { name: { - "old": "User group {0} does not exist.".format(name), - "new": "User group {0} created.".format(name), + "old": "User group {} does not exist.".format(name), + "new": "User group {} created.".format(name), } } @@ -93,7 +86,7 @@ def present(name, **kwargs): # Make sure right values are strings so we can compare them with the current user group rights for right in kwargs["rights"]: for key in right: - right[key] = six.text_type(right[key]) + right[key] = str(right[key]) if sorted(kwargs["rights"]) != sorted(usergroup["rights"]): update_rights = True else: @@ -185,7 +178,7 @@ def present(name, **kwargs): ret["changes"] = changes_usergroup_created else: ret["result"] = False - ret["comment"] = comment_usergroup_notcreated + six.text_type( + ret["comment"] = comment_usergroup_notcreated + str( usergroup_create["error"] ) @@ -193,7 +186,7 @@ def present(name, **kwargs): if error: ret["changes"] = {} ret["result"] = False - ret["comment"] = six.text_type(error) + ret["comment"] = str(error) return ret @@ -226,13 +219,13 @@ def absent(name, **kwargs): ret = {"name": name, "changes": {}, "result": False, "comment": ""} # Comment and change messages - comment_usergroup_deleted = "User group {0} deleted.".format(name) - comment_usergroup_notdeleted = "Unable to delete user group: {0}. ".format(name) - comment_usergroup_notexists = "User group {0} does not exist.".format(name) + comment_usergroup_deleted = "User group {} deleted.".format(name) + comment_usergroup_notdeleted = "Unable to delete user group: {}. ".format(name) + comment_usergroup_notexists = "User group {} does not exist.".format(name) changes_usergroup_deleted = { name: { - "old": "User group {0} exists.".format(name), - "new": "User group {0} deleted.".format(name), + "old": "User group {} exists.".format(name), + "new": "User group {} deleted.".format(name), } } @@ -268,7 +261,7 @@ def absent(name, **kwargs): ret["changes"] = changes_usergroup_deleted else: ret["result"] = False - ret["comment"] = comment_usergroup_notdeleted + six.text_type( + ret["comment"] = comment_usergroup_notdeleted + str( usergroup_delete["error"] ) diff --git a/salt/states/zabbix_usermacro.py b/salt/states/zabbix_usermacro.py index 5c1fdf38ed4..8b82d39101a 100644 --- a/salt/states/zabbix_usermacro.py +++ b/salt/states/zabbix_usermacro.py @@ -1,16 +1,9 @@ -# -*- coding: utf-8 -*- """ Management of Zabbix usermacros. :codeauthor: Raymond Kuiper """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - -# Import Salt libs -from salt.ext import six - def __virtual__(): """ @@ -54,35 +47,33 @@ def present(name, value, hostid=None, **kwargs): # Comment and change messages if hostid: - comment_usermacro_created = "Usermacro {0} created on hostid {1}.".format( + comment_usermacro_created = "Usermacro {} created on hostid {}.".format( name, hostid ) - comment_usermacro_updated = "Usermacro {0} updated on hostid {1}.".format( + comment_usermacro_updated = "Usermacro {} updated on hostid {}.".format( name, hostid ) - comment_usermacro_notcreated = "Unable to create usermacro: {0} on hostid {1}. ".format( + comment_usermacro_notcreated = "Unable to create usermacro: {} on hostid {}. ".format( name, hostid ) - comment_usermacro_exists = "Usermacro {0} already exists on hostid {1}.".format( + comment_usermacro_exists = "Usermacro {} already exists on hostid {}.".format( name, hostid ) changes_usermacro_created = { name: { - "old": "Usermacro {0} does not exist on hostid {1}.".format( - name, hostid - ), - "new": "Usermacro {0} created on hostid {1}.".format(name, hostid), + "old": "Usermacro {} does not exist on hostid {}.".format(name, hostid), + "new": "Usermacro {} created on hostid {}.".format(name, hostid), } } else: - comment_usermacro_created = "Usermacro {0} created.".format(name) - comment_usermacro_updated = "Usermacro {0} updated.".format(name) - comment_usermacro_notcreated = "Unable to create usermacro: {0}. ".format(name) - comment_usermacro_exists = "Usermacro {0} already exists.".format(name) + comment_usermacro_created = "Usermacro {} created.".format(name) + comment_usermacro_updated = "Usermacro {} updated.".format(name) + comment_usermacro_notcreated = "Unable to create usermacro: {}. ".format(name) + comment_usermacro_exists = "Usermacro {} already exists.".format(name) changes_usermacro_created = { name: { - "old": "Usermacro {0} does not exist.".format(name), - "new": "Usermacro {0} created.".format(name), + "old": "Usermacro {} does not exist.".format(name), + "new": "Usermacro {} created.".format(name), } } @@ -91,7 +82,7 @@ def present(name, value, hostid=None, **kwargs): if isinstance(kwargs["exec_params"], list): kwargs["exec_params"] = "\n".join(kwargs["exec_params"]) + "\n" else: - kwargs["exec_params"] = six.text_type(kwargs["exec_params"]) + "\n" + kwargs["exec_params"] = str(kwargs["exec_params"]) + "\n" if hostid: usermacro_exists = __salt__["zabbix.usermacro_get"]( name, hostids=hostid, **connection_args @@ -109,7 +100,7 @@ def present(name, value, hostid=None, **kwargs): usermacroid = int(usermacroobj["globalmacroid"]) update_value = False - if six.text_type(value) != usermacroobj["value"]: + if str(value) != usermacroobj["value"]: update_value = True # Dry run, test=true mode @@ -165,7 +156,7 @@ def present(name, value, hostid=None, **kwargs): ret["changes"] = changes_usermacro_created else: ret["result"] = False - ret["comment"] = comment_usermacro_notcreated + six.text_type( + ret["comment"] = comment_usermacro_notcreated + str( usermacro_create["error"] ) @@ -173,7 +164,7 @@ def present(name, value, hostid=None, **kwargs): if error: ret["changes"] = {} ret["result"] = False - ret["comment"] = six.text_type(error) + ret["comment"] = str(error) return ret @@ -208,29 +199,29 @@ def absent(name, hostid=None, **kwargs): # Comment and change messages if hostid: - comment_usermacro_deleted = "Usermacro {0} deleted from hostid {1}.".format( + comment_usermacro_deleted = "Usermacro {} deleted from hostid {}.".format( name, hostid ) - comment_usermacro_notdeleted = "Unable to delete usermacro: {0} from hostid {1}.".format( + comment_usermacro_notdeleted = "Unable to delete usermacro: {} from hostid {}.".format( name, hostid ) - comment_usermacro_notexists = "Usermacro {0} does not exist on hostid {1}.".format( + comment_usermacro_notexists = "Usermacro {} does not exist on hostid {}.".format( name, hostid ) changes_usermacro_deleted = { name: { - "old": "Usermacro {0} exists on hostid {1}.".format(name, hostid), - "new": "Usermacro {0} deleted from {1}.".format(name, hostid), + "old": "Usermacro {} exists on hostid {}.".format(name, hostid), + "new": "Usermacro {} deleted from {}.".format(name, hostid), } } else: - comment_usermacro_deleted = "Usermacro {0} deleted.".format(name) - comment_usermacro_notdeleted = "Unable to delete usermacro: {0}.".format(name) - comment_usermacro_notexists = "Usermacro {0} does not exist.".format(name) + comment_usermacro_deleted = "Usermacro {} deleted.".format(name) + comment_usermacro_notdeleted = "Unable to delete usermacro: {}.".format(name) + comment_usermacro_notexists = "Usermacro {} does not exist.".format(name) changes_usermacro_deleted = { name: { - "old": "Usermacro {0} exists.".format(name), - "new": "Usermacro {0} deleted.".format(name), + "old": "Usermacro {} exists.".format(name), + "new": "Usermacro {} deleted.".format(name), } } if hostid: @@ -276,7 +267,7 @@ def absent(name, hostid=None, **kwargs): ret["changes"] = changes_usermacro_deleted else: ret["result"] = False - ret["comment"] = comment_usermacro_notdeleted + six.text_type( + ret["comment"] = comment_usermacro_notdeleted + str( usermacro_delete["error"] ) diff --git a/salt/states/zabbix_valuemap.py b/salt/states/zabbix_valuemap.py index b863b347758..f39b7d48baa 100644 --- a/salt/states/zabbix_valuemap.py +++ b/salt/states/zabbix_valuemap.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ .. versionadded:: 2017.7 @@ -6,19 +5,11 @@ Management of Zabbix Valuemap object over Zabbix API. :codeauthor: Jakub Sliva """ -from __future__ import absolute_import, unicode_literals import json import logging -try: - from salt.ext import six - from salt.exceptions import SaltException - - IMPORTS_OK = True -except ImportError: - IMPORTS_OK = False - +from salt.exceptions import SaltException log = logging.getLogger(__name__) @@ -28,7 +19,7 @@ def __virtual__(): Only make these states available if Zabbix module and run_query function is available and all 3rd party modules imported. """ - if "zabbix.run_query" in __salt__ and IMPORTS_OK: + if "zabbix.run_query" in __salt__: return True return False, "Import zabbix or other needed modules failed." @@ -64,8 +55,7 @@ def present(name, params, **kwargs): params["name"] = name input_params = __salt__["zabbix.substitute_params"](params, **kwargs) log.info( - "Zabbix Value map: input params: %s", - six.text_type(json.dumps(input_params, indent=4)), + "Zabbix Value map: input params: %s", str(json.dumps(input_params, indent=4)), ) search = {"output": "extend", "selectMappings": "extend", "filter": {"name": name}} @@ -73,7 +63,7 @@ def present(name, params, **kwargs): valuemap_get = __salt__["zabbix.run_query"]("valuemap.get", search, **kwargs) log.info( "Zabbix Value map: valuemap.get result: %s", - six.text_type(json.dumps(valuemap_get, indent=4)), + str(json.dumps(valuemap_get, indent=4)), ) existing_obj = ( @@ -86,11 +76,11 @@ def present(name, params, **kwargs): diff_params = __salt__["zabbix.compare_params"](input_params, existing_obj) log.info( "Zabbix Value map: input params: {%s", - six.text_type(json.dumps(input_params, indent=4)), + str(json.dumps(input_params, indent=4)), ) log.info( "Zabbix Value map: Object comparison result. Differences: %s", - six.text_type(diff_params), + str(diff_params), ) if diff_params: @@ -99,17 +89,17 @@ def present(name, params, **kwargs): ] log.info( "Zabbix Value map: update params: %s", - six.text_type(json.dumps(diff_params, indent=4)), + str(json.dumps(diff_params, indent=4)), ) if dry_run: ret["result"] = True - ret["comment"] = 'Zabbix Value map "{0}" would be fixed.'.format(name) + ret["comment"] = 'Zabbix Value map "{}" would be fixed.'.format(name) ret["changes"] = { name: { - "old": 'Zabbix Value map "{0}" differs ' - "in following parameters: {1}".format(name, diff_params), - "new": 'Zabbix Value map "{0}" would correspond to definition.'.format( + "old": 'Zabbix Value map "{}" differs ' + "in following parameters: {}".format(name, diff_params), + "new": 'Zabbix Value map "{}" would correspond to definition.'.format( name ), } @@ -120,16 +110,16 @@ def present(name, params, **kwargs): ) log.info( "Zabbix Value map: valuemap.update result: %s", - six.text_type(valuemap_update), + str(valuemap_update), ) if valuemap_update: ret["result"] = True - ret["comment"] = 'Zabbix Value map "{0}" updated.'.format(name) + ret["comment"] = 'Zabbix Value map "{}" updated.'.format(name) ret["changes"] = { name: { - "old": 'Zabbix Value map "{0}" differed ' - "in following parameters: {1}".format(name, diff_params), - "new": 'Zabbix Value map "{0}" fixed.'.format(name), + "old": 'Zabbix Value map "{}" differed ' + "in following parameters: {}".format(name, diff_params), + "new": 'Zabbix Value map "{}" fixed.'.format(name), } } @@ -137,18 +127,18 @@ def present(name, params, **kwargs): ret["result"] = True ret[ "comment" - ] = 'Zabbix Value map "{0}" already exists and corresponds to a definition.'.format( + ] = 'Zabbix Value map "{}" already exists and corresponds to a definition.'.format( name ) else: if dry_run: ret["result"] = True - ret["comment"] = 'Zabbix Value map "{0}" would be created.'.format(name) + ret["comment"] = 'Zabbix Value map "{}" would be created.'.format(name) ret["changes"] = { name: { - "old": 'Zabbix Value map "{0}" does not exist.'.format(name), - "new": 'Zabbix Value map "{0}" would be created ' + "old": 'Zabbix Value map "{}" does not exist.'.format(name), + "new": 'Zabbix Value map "{}" would be created ' "according definition.".format(name), } } @@ -158,17 +148,16 @@ def present(name, params, **kwargs): "valuemap.create", input_params, **kwargs ) log.info( - "Zabbix Value map: valuemap.create result: %s", - six.text_type(valuemap_create), + "Zabbix Value map: valuemap.create result: %s", str(valuemap_create), ) if valuemap_create: ret["result"] = True - ret["comment"] = 'Zabbix Value map "{0}" created.'.format(name) + ret["comment"] = 'Zabbix Value map "{}" created.'.format(name) ret["changes"] = { name: { - "old": 'Zabbix Value map "{0}" did not exist.'.format(name), - "new": 'Zabbix Value map "{0}" created according definition.'.format( + "old": 'Zabbix Value map "{}" did not exist.'.format(name), + "new": 'Zabbix Value map "{}" created according definition.'.format( name ), } @@ -204,15 +193,15 @@ def absent(name, **kwargs): if not object_id: ret["result"] = True - ret["comment"] = 'Zabbix Value map "{0}" does not exist.'.format(name) + ret["comment"] = 'Zabbix Value map "{}" does not exist.'.format(name) else: if dry_run: ret["result"] = True - ret["comment"] = 'Zabbix Value map "{0}" would be deleted.'.format(name) + ret["comment"] = 'Zabbix Value map "{}" would be deleted.'.format(name) ret["changes"] = { name: { - "old": 'Zabbix Value map "{0}" exists.'.format(name), - "new": 'Zabbix Value map "{0}" would be deleted.'.format(name), + "old": 'Zabbix Value map "{}" exists.'.format(name), + "new": 'Zabbix Value map "{}" would be deleted.'.format(name), } } else: @@ -222,11 +211,11 @@ def absent(name, **kwargs): if valuemap_delete: ret["result"] = True - ret["comment"] = 'Zabbix Value map "{0}" deleted.'.format(name) + ret["comment"] = 'Zabbix Value map "{}" deleted.'.format(name) ret["changes"] = { name: { - "old": 'Zabbix Value map "{0}" existed.'.format(name), - "new": 'Zabbix Value map "{0}" deleted.'.format(name), + "old": 'Zabbix Value map "{}" existed.'.format(name), + "new": 'Zabbix Value map "{}" deleted.'.format(name), } } diff --git a/salt/states/zcbuildout.py b/salt/states/zcbuildout.py index 2678eb5fc9a..2f8da7b8d70 100644 --- a/salt/states/zcbuildout.py +++ b/salt/states/zcbuildout.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of zc.buildout ========================= @@ -35,15 +34,10 @@ Available Functions - onlyif: /bin/test_else_installed """ -from __future__ import absolute_import, print_function, unicode_literals -# Import python libs import logging import sys -# Import salt libs -from salt.ext.six import string_types - # Define the module's virtual name __virtualname__ = "buildout" log = logging.getLogger(__name__) @@ -87,11 +81,11 @@ def _ret_status( out = exec_status.get("out", "") if not quiet: if out: - if isinstance(out, string_types): + if isinstance(out, str): comment += "\n" + out outlog = exec_status.get("outlog", None) if outlog: - if isinstance(outlog, string_types): + if isinstance(outlog, str): comment += "\n" + outlog return { "changes": changes, diff --git a/salt/states/zenoss.py b/salt/states/zenoss.py index f7762367577..0a05c67af23 100644 --- a/salt/states/zenoss.py +++ b/salt/states/zenoss.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ State to manage monitoring in Zenoss. @@ -18,7 +17,6 @@ Allows for setting a state of minions in Zenoss using the Zenoss API. Currently - prod_state: 1000 """ -from __future__ import absolute_import, print_function, unicode_literals import logging @@ -57,32 +55,30 @@ def monitored(name, device_class=None, collector="localhost", prod_state=None): if device: ret["result"] = True ret["changes"] = None - ret["comment"] = "{0} is already monitored".format(name) + ret["comment"] = "{} is already monitored".format(name) # if prod_state is set, ensure it matches with the current state if prod_state is not None and device["productionState"] != prod_state: if __opts__["test"]: ret[ "comment" - ] = "{0} is already monitored but prodState will be updated".format( - name - ) + ] = "{} is already monitored but prodState will be updated".format(name) ret["result"] = None else: __salt__["zenoss.set_prod_state"](prod_state, name) ret[ "comment" - ] = "{0} is already monitored but prodState was updated".format(name) + ] = "{} is already monitored but prodState was updated".format(name) ret["changes"] = { - "old": "prodState == {0}".format(device["productionState"]), - "new": "prodState == {0}".format(prod_state), + "old": "prodState == {}".format(device["productionState"]), + "new": "prodState == {}".format(prod_state), } return ret # Device not yet in Zenoss if __opts__["test"]: - ret["comment"] = 'The state of "{0}" will be changed.'.format(name) + ret["comment"] = 'The state of "{}" will be changed.'.format(name) ret["changes"] = {"old": "monitored == False", "new": "monitored == True"} ret["result"] = None return ret @@ -91,9 +87,9 @@ def monitored(name, device_class=None, collector="localhost", prod_state=None): if __salt__["zenoss.add_device"](name, device_class, collector, prod_state): ret["result"] = True ret["changes"] = {"old": "monitored == False", "new": "monitored == True"} - ret["comment"] = "{0} has been added to Zenoss".format(name) + ret["comment"] = "{} has been added to Zenoss".format(name) else: ret["result"] = False ret["changes"] = None - ret["comment"] = "Unable to add {0} to Zenoss".format(name) + ret["comment"] = "Unable to add {} to Zenoss".format(name) return ret diff --git a/salt/states/zk_concurrency.py b/salt/states/zk_concurrency.py index 14b0259e99b..13927a385e9 100644 --- a/salt/states/zk_concurrency.py +++ b/salt/states/zk_concurrency.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Control concurrency of steps within state execution using zookeeper =================================================================== @@ -46,8 +45,6 @@ This example would allow the file state to change, but would limit the concurrency of the trafficserver service restart to 4. """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals # TODO: use depends decorator to make these per function deps, instead of all or nothing REQUIRED_FUNCS = ( @@ -161,7 +158,7 @@ def unlock( if unlocked: ret["result"] = True else: - ret["comment"] = "Unable to find lease for path {0}".format(name) + ret["comment"] = "Unable to find lease for path {}".format(name) return ret @@ -199,7 +196,7 @@ def min_party( ) if not isinstance(nodes, list): raise Exception( - "Error from zk_concurrency.party_members, return was not a list: {0}".format( + "Error from zk_concurrency.party_members, return was not a list: {}".format( nodes ) ) @@ -209,18 +206,18 @@ def min_party( if num_nodes >= min_nodes or blocking: ret["result"] = None if __opts__["test"] else True if not blocking: - ret["comment"] = "Currently {0} nodes, which is >= {1}".format( + ret["comment"] = "Currently {} nodes, which is >= {}".format( num_nodes, min_nodes ) else: ret[ "comment" - ] = "Blocked until {0} nodes were available. Unblocked after {1} nodes became available".format( + ] = "Blocked until {} nodes were available. Unblocked after {} nodes became available".format( min_nodes, num_nodes ) else: ret["result"] = False - ret["comment"] = "Currently {0} nodes, which is < {1}".format( + ret["comment"] = "Currently {} nodes, which is < {}".format( num_nodes, min_nodes ) diff --git a/salt/states/zone.py b/salt/states/zone.py index f7e54af3b31..4e03f8aab11 100644 --- a/salt/states/zone.py +++ b/salt/states/zone.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Management of Solaris Zones @@ -109,12 +108,9 @@ Or we can remove the limit altogether! - property: cpu-shares """ -from __future__ import absolute_import, print_function, unicode_literals -# Import Python libs import logging -# Import Salt libs import salt.utils.args import salt.utils.atomicfile import salt.utils.files @@ -142,7 +138,7 @@ def __virtual__(): else: return ( False, - "{0} state module can only be loaded on Solaris platforms".format( + "{} state module can only be loaded on Solaris platforms".format( __virtualname__ ), ) @@ -181,19 +177,17 @@ def property_present(name, property, value): if ret["result"]: ret["changes"][property] = _parse_value(value) if ret["comment"] == "": - ret["comment"] = "The property {0} is was updated to {1}.".format( + ret["comment"] = "The property {} is was updated to {}.".format( property, value ) elif ret["comment"] == "": if ret["comment"] == "": - ret[ - "comment" - ] = "The property {0} is was not updated to {1}!".format( + ret["comment"] = "The property {} is was not updated to {}!".format( property, value ) else: ret["result"] = True - ret["comment"] = "The property {0} is already set to {1}.".format( + ret["comment"] = "The property {} is already set to {}.".format( property, value ) else: @@ -201,7 +195,7 @@ def property_present(name, property, value): ret["result"] = False ret[ "comment" - ] = "The zone {0} is not in the configured, installed, or booted state.".format( + ] = "The zone {} is not in the configured, installed, or booted state.".format( name ) @@ -244,21 +238,21 @@ def property_absent(name, property): elif zonecfg[property] != zonecfg_new[property]: ret["changes"][property] = zonecfg_new[property] if ret["comment"] == "": - ret["comment"] = "The property {0} was cleared!".format(property) + ret["comment"] = "The property {} was cleared!".format(property) elif ret["comment"] == "": if ret["comment"] == "": - ret["comment"] = "The property {0} did not get cleared!".format( + ret["comment"] = "The property {} did not get cleared!".format( property ) else: ret["result"] = True - ret["comment"] = "The property {0} does not exist!".format(property) + ret["comment"] = "The property {} does not exist!".format(property) else: ## zone does not exist ret["result"] = False ret[ "comment" - ] = "The zone {0} is not in the configured, installed, or booted state.".format( + ] = "The zone {} is not in the configured, installed, or booted state.".format( name ) @@ -323,11 +317,11 @@ def resource_present( ): ret["result"] = True if resource_selector_property: - ret["comment"] = "the {0} resource {1} is up to date.".format( + ret["comment"] = "the {} resource {} is up to date.".format( resource_type, resource_selector_value, ) else: - ret["comment"] = "the {0} resource is up to date.".format( + ret["comment"] = "the {} resource is up to date.".format( resource_type, ) @@ -341,7 +335,7 @@ def resource_present( ) # note: something odd with ncpus property, we fix it here for now if key == "ncpus" and key in kwargs: - kwargs[key] = "{0:.2f}".format(float(kwargs[key])) + kwargs[key] = "{:.2f}".format(float(kwargs[key])) if key not in resource: ret["result"] = None @@ -380,26 +374,26 @@ def resource_present( if resource_selector_property: ret[ "comment" - ] = "The {0} resource {1} was updated.".format( + ] = "The {} resource {} was updated.".format( resource_type, resource_selector_value, ) else: ret[ "comment" - ] = "The {0} resource was updated.".format( + ] = "The {} resource was updated.".format( resource_type, ) elif ret["comment"] == "": if resource_selector_property: ret[ "comment" - ] = "The {0} resource {1} was not updated.".format( + ] = "The {} resource {} was not updated.".format( resource_type, resource_selector_value, ) else: ret[ "comment" - ] = "The {0} resource was not updated.".format( + ] = "The {} resource was not updated.".format( resource_type, ) if ret["result"] is None: @@ -427,11 +421,11 @@ def resource_present( else: ret["changes"][resource_type][key] = _parse_value(kwargs[key]) if ret["comment"] == "": - ret["comment"] = "The {0} resource {1} was added.".format( + ret["comment"] = "The {} resource {} was added.".format( resource_type, resource_selector_value, ) elif ret["comment"] == "": - ret["comment"] = "The {0} resource {1} was not added.".format( + ret["comment"] = "The {} resource {} was not added.".format( resource_type, resource_selector_value, ) else: @@ -439,7 +433,7 @@ def resource_present( ret["result"] = False ret[ "comment" - ] = "The zone {0} is not in the configured, installed, or booted state.".format( + ] = "The zone {} is not in the configured, installed, or booted state.".format( name ) @@ -497,13 +491,13 @@ def resource_absent( if zonecfg_res["status"]: ret["changes"][resource_type] = "removed" if ret["comment"] == "": - ret["comment"] = "The {0} resource was removed.".format( + ret["comment"] = "The {} resource was removed.".format( resource_type, ) elif "messages" in zonecfg_res: ret["comment"] = zonecfg_res["message"] else: - ret["comment"] = "The {0} resource was not removed.".format( + ret["comment"] = "The {} resource was not removed.".format( resource_type, ) elif resource[resource_selector_property] == resource_selector_value: @@ -520,20 +514,20 @@ def resource_absent( resource_selector_value ] = "removed" if ret["comment"] == "": - ret["comment"] = "The {0} resource {1} was removed.".format( + ret["comment"] = "The {} resource {} was removed.".format( resource_type, resource_selector_value, ) elif "messages" in zonecfg_res: ret["comment"] = zonecfg_res["message"] else: - ret["comment"] = "The {0} resource {1} was not removed.".format( + ret["comment"] = "The {} resource {} was not removed.".format( resource_type, resource_selector_value, ) # resource already absent if ret["result"] is None: ret["result"] = True - ret["comment"] = "The {0} resource {1} was absent.".format( + ret["comment"] = "The {} resource {} was absent.".format( resource_type, resource_selector_value, ) else: @@ -541,7 +535,7 @@ def resource_absent( ret["result"] = False ret[ "comment" - ] = "The zone {0} is not in the configured, installed, or booted state.".format( + ] = "The zone {} is not in the configured, installed, or booted state.".format( name ) @@ -566,7 +560,7 @@ def booted(name, single=False): if zones[name]["state"] == "running": ## zone is running ret["result"] = True - ret["comment"] = "Zone {0} already booted".format(name) + ret["comment"] = "Zone {} already booted".format(name) else: ## try and boot the zone if not __opts__["test"]: @@ -574,20 +568,20 @@ def booted(name, single=False): if __opts__["test"] or zoneadm_res["status"]: ret["result"] = True ret["changes"][name] = "booted" - ret["comment"] = "Zone {0} booted".format(name) + ret["comment"] = "Zone {} booted".format(name) else: ret["result"] = False - ret["comment"] = "Failed to boot {0}".format(name) + ret["comment"] = "Failed to boot {}".format(name) else: ## zone does not exist ret["comment"] = [] ret["comment"].append( - "The zone {0} is not in the installed or booted state.".format(name) + "The zone {} is not in the installed or booted state.".format(name) ) for zone in zones: if zones[zone]["uuid"] == name: ret["comment"].append( - "The zone {0} has a uuid of {1}, please use the zone name instead!".format( + "The zone {} has a uuid of {}, please use the zone name instead!".format( zone, name, ) ) @@ -616,7 +610,7 @@ def halted(name, graceful=True): if zones[name]["state"] != "running": ## zone is not running ret["result"] = True - ret["comment"] = "Zone {0} already halted".format(name) + ret["comment"] = "Zone {} already halted".format(name) else: ## try and halt the zone if not __opts__["test"]: @@ -628,20 +622,18 @@ def halted(name, graceful=True): if __opts__["test"] or zoneadm_res["status"]: ret["result"] = True ret["changes"][name] = "halted" - ret["comment"] = "Zone {0} halted".format(name) + ret["comment"] = "Zone {} halted".format(name) else: ret["result"] = False - ret["comment"] = "Failed to halt {0}".format(name) + ret["comment"] = "Failed to halt {}".format(name) else: ## zone does not exist ret["comment"] = [] - ret["comment"].append( - "The zone {0} is not in the installed state.".format(name) - ) + ret["comment"].append("The zone {} is not in the installed state.".format(name)) for zone in zones: if zones[zone]["uuid"] == name: ret["comment"].append( - "The zone {0} has a uuid of {1}, please use the zone name instead!".format( + "The zone {} has a uuid of {}, please use the zone name instead!".format( zone, name, ) ) @@ -672,7 +664,7 @@ def export(name, path, replace=False): if __opts__["test"]: ## pretend we did the correct thing ret["result"] = True - ret["comment"] = "Zone configartion for {0} exported to {1}".format( + ret["comment"] = "Zone configartion for {} exported to {}".format( name, path, ) ret["changes"][name] = "exported" @@ -681,7 +673,7 @@ def export(name, path, replace=False): ret["changes"] = {} ret[ "comment" - ] = "File {0} exists, zone configuration for {1} not exported.".format( + ] = "File {} exists, zone configuration for {} not exported.".format( path, name, ) else: @@ -698,14 +690,14 @@ def export(name, path, replace=False): ret["result"] = False ret[ "comment" - ] = "Unable to export zone configuration for {0} to {1}!".format( + ] = "Unable to export zone configuration for {} to {}!".format( name, path, ) else: ret["result"] = True ret[ "comment" - ] = "Zone configuration for {0} was exported to {1}.".format( + ] = "Zone configuration for {} was exported to {}.".format( name, path, ) ret["changes"][name] = "exported" @@ -715,7 +707,7 @@ def export(name, path, replace=False): ret["result"] = True ret[ "comment" - ] = "Zone configuration for {0} was already exported to {1}.".format( + ] = "Zone configuration for {} was already exported to {}.".format( name, path ) if __salt__["file.file_exists"](cfg_tmp): @@ -730,14 +722,14 @@ def export(name, path, replace=False): ret["result"] = False ret[ "comment" - ] = "Unable to be re-export zone configuration for {0} to {1}!".format( + ] = "Unable to be re-export zone configuration for {} to {}!".format( name, path, ) else: ret["result"] = True ret[ "comment" - ] = "Zone configuration for {0} was re-exported to {1}.".format( + ] = "Zone configuration for {} was re-exported to {}.".format( name, path, ) ret["changes"][name] = "exported" @@ -745,7 +737,7 @@ def export(name, path, replace=False): ret["result"] = False ret[ "comment" - ] = "Zone configuration for {0} is different from the one exported to {1}!".format( + ] = "Zone configuration for {} is different from the one exported to {}!".format( name, path ) if __salt__["file.file_exists"](cfg_tmp): @@ -753,11 +745,11 @@ def export(name, path, replace=False): else: ## zone does not exist ret["comment"] = [] - ret["comment"].append("The zone {0} does not exist.".format(name)) + ret["comment"].append("The zone {} does not exist.".format(name)) for zone in zones: if zones[zone]["uuid"] == name: ret["comment"].append( - "The zone {0} has a uuid of {1}, please use the zone name instead!".format( + "The zone {} has a uuid of {}, please use the zone name instead!".format( name, path, ) ) @@ -801,7 +793,7 @@ def import_(name, path, mode="import", nodataset=False, brand_opts=None): if name not in zones: if __opts__["test"]: ret["result"] = True - ret["comment"] = "Zone {0} was imported from {1}.".format(name, path,) + ret["comment"] = "Zone {} was imported from {}.".format(name, path,) ret["changes"][name] = "imported" else: if __salt__["file.file_exists"](path): @@ -810,27 +802,23 @@ def import_(name, path, mode="import", nodataset=False, brand_opts=None): ret["result"] = False ret[ "comment" - ] = "Unable to import zone configuration for {0}!".format(name) + ] = "Unable to import zone configuration for {}!".format(name) else: ret["result"] = True ret["changes"][name] = "imported" - ret["comment"] = "Zone {0} was imported from {1}.".format( - name, path, - ) + ret["comment"] = "Zone {} was imported from {}.".format(name, path,) if mode.lower() == "attach": res_attach = __salt__["zoneadm.attach"](name, False, brand_opts) ret["result"] = res_attach["status"] if res_attach["status"]: ret["changes"][name] = "attached" - ret["comment"] = "Zone {0} was attached from {1}.".format( + ret["comment"] = "Zone {} was attached from {}.".format( name, path, ) else: ret["comment"] = [] ret["comment"].append( - "Failed to attach zone {0} from {1}!".format( - name, path, - ) + "Failed to attach zone {} from {}!".format(name, path,) ) if "message" in res_attach: ret["comment"].append(res_attach["message"]) @@ -842,15 +830,13 @@ def import_(name, path, mode="import", nodataset=False, brand_opts=None): ret["result"] = res_install["status"] if res_install["status"]: ret["changes"][name] = "installed" - ret["comment"] = "Zone {0} was installed from {1}.".format( + ret["comment"] = "Zone {} was installed from {}.".format( name, path, ) else: ret["comment"] = [] ret["comment"].append( - "Failed to install zone {0} from {1}!".format( - name, path, - ) + "Failed to install zone {} from {}!".format(name, path,) ) if "message" in res_install: ret["comment"].append(res_install["message"]) @@ -859,11 +845,11 @@ def import_(name, path, mode="import", nodataset=False, brand_opts=None): ret["result"] = False ret[ "comment" - ] = "The file {0} does not exists, unable to import!".format(path) + ] = "The file {} does not exists, unable to import!".format(path) else: ## zone exist ret["result"] = True - ret["comment"] = "Zone {0} already exists, not importing configuration.".format( + ret["comment"] = "Zone {} already exists, not importing configuration.".format( name ) @@ -927,7 +913,7 @@ def present(name, brand, zonepath, properties=None, resources=None): if __opts__["test"]: ret["result"] = None ret["comment"].append( - "Cannot determine of changes would happen to the zone {0}.".format(name) + "Cannot determine of changes would happen to the zone {}.".format(name) ) ## create zone if needed @@ -942,7 +928,7 @@ def present(name, brand, zonepath, properties=None, resources=None): if res_create["status"]: ret["result"] = True ret["changes"][name] = "created" - ret["comment"].append("The zone {0} was created.".format(name)) + ret["comment"].append("The zone {} was created.".format(name)) if not __opts__["test"]: ret["result"] = True @@ -1056,7 +1042,7 @@ def absent(name, uninstall=False): if __opts__["test"]: ret["result"] = True ret["changes"][name] = "removed" - ret["comment"] = "Zone {0} was removed.".format(name) + ret["comment"] = "Zone {} was removed.".format(name) else: ret["result"] = True if uninstall and zones[name]["state"] in ["running", "installed"]: @@ -1065,10 +1051,10 @@ def absent(name, uninstall=False): ret["result"] = res_uninstall["status"] if ret["result"]: ret["changes"][name] = "uninstalled" - ret["comment"] = "The zone {0} was uninstalled.".format(name) + ret["comment"] = "The zone {} was uninstalled.".format(name) else: ret["comment"] = [] - ret["comment"].append("Failed to uninstall zone {0}!".format(name)) + ret["comment"].append("Failed to uninstall zone {}!".format(name)) if "message" in res_uninstall: ret["comment"].append(res_uninstall["message"]) ret["comment"] = "\n".join(ret["comment"]) @@ -1077,10 +1063,10 @@ def absent(name, uninstall=False): ret["result"] = res_detach["status"] if ret["result"]: ret["changes"][name] = "detached" - ret["comment"] = "The zone {0} was detached.".format(name) + ret["comment"] = "The zone {} was detached.".format(name) else: ret["comment"] = [] - ret["comment"].append("Failed to detach zone {0}!".format(name)) + ret["comment"].append("Failed to detach zone {}!".format(name)) if "message" in res_detach: ret["comment"].append(res_detach["message"]) ret["comment"] = "\n".join(ret["comment"]) @@ -1089,16 +1075,16 @@ def absent(name, uninstall=False): ret["result"] = res_delete["status"] if ret["result"]: ret["changes"][name] = "deleted" - ret["comment"] = "The zone {0} was delete.".format(name) + ret["comment"] = "The zone {} was delete.".format(name) else: ret["comment"] = [] - ret["comment"].append("Failed to delete zone {0}!".format(name)) + ret["comment"].append("Failed to delete zone {}!".format(name)) if "message" in res_delete: ret["comment"].append(res_delete["message"]) ret["comment"] = "\n".join(ret["comment"]) else: ret["result"] = True - ret["comment"] = "Zone {0} does not exist.".format(name) + ret["comment"] = "Zone {} does not exist.".format(name) return ret @@ -1125,19 +1111,19 @@ def attached(name, force=False): ret["result"] = res_attach["status"] if ret["result"]: ret["changes"][name] = "attached" - ret["comment"] = "The zone {0} was attached.".format(name) + ret["comment"] = "The zone {} was attached.".format(name) else: ret["comment"] = [] - ret["comment"].append("Failed to attach zone {0}!".format(name)) + ret["comment"].append("Failed to attach zone {}!".format(name)) if "message" in res_attach: ret["comment"].append(res_attach["message"]) ret["comment"] = "\n".join(ret["comment"]) else: ret["result"] = True - ret["comment"] = "zone {0} already attached.".format(name) + ret["comment"] = "zone {} already attached.".format(name) else: ret["result"] = False - ret["comment"] = "zone {0} is not configured!".format(name) + ret["comment"] = "zone {} is not configured!".format(name) return ret @@ -1162,20 +1148,20 @@ def detached(name): ret["result"] = res_detach["status"] if ret["result"]: ret["changes"][name] = "detached" - ret["comment"] = "The zone {0} was detached.".format(name) + ret["comment"] = "The zone {} was detached.".format(name) else: ret["comment"] = [] - ret["comment"].append("Failed to detach zone {0}!".format(name)) + ret["comment"].append("Failed to detach zone {}!".format(name)) if "message" in res_detach: ret["comment"].append(res_detach["message"]) ret["comment"] = "\n".join(ret["comment"]) else: ret["result"] = True - ret["comment"] = "zone {0} already detached.".format(name) + ret["comment"] = "zone {} already detached.".format(name) else: ## note: a non existing zone is not attached, we do not consider this a failure ret["result"] = True - ret["comment"] = "zone {0} is not configured!".format(name) + ret["comment"] = "zone {} is not configured!".format(name) return ret @@ -1204,19 +1190,19 @@ def installed(name, nodataset=False, brand_opts=None): ret["result"] = res_install["status"] if ret["result"]: ret["changes"][name] = "installed" - ret["comment"] = "The zone {0} was installed.".format(name) + ret["comment"] = "The zone {} was installed.".format(name) else: ret["comment"] = [] - ret["comment"].append("Failed to install zone {0}!".format(name)) + ret["comment"].append("Failed to install zone {}!".format(name)) if "message" in res_install: ret["comment"].append(res_install["message"]) ret["comment"] = "\n".join(ret["comment"]) else: ret["result"] = True - ret["comment"] = "zone {0} already installed.".format(name) + ret["comment"] = "zone {} already installed.".format(name) else: ret["result"] = False - ret["comment"] = "zone {0} is not configured!".format(name) + ret["comment"] = "zone {} is not configured!".format(name) return ret @@ -1241,20 +1227,20 @@ def uninstalled(name): ret["result"] = res_uninstall["status"] if ret["result"]: ret["changes"][name] = "uninstalled" - ret["comment"] = "The zone {0} was uninstalled.".format(name) + ret["comment"] = "The zone {} was uninstalled.".format(name) else: ret["comment"] = [] - ret["comment"].append("Failed to uninstall zone {0}!".format(name)) + ret["comment"].append("Failed to uninstall zone {}!".format(name)) if "message" in res_uninstall: ret["comment"].append(res_uninstall["message"]) ret["comment"] = "\n".join(ret["comment"]) else: ret["result"] = True - ret["comment"] = "zone {0} already uninstalled.".format(name) + ret["comment"] = "zone {} already uninstalled.".format(name) else: ## note: a non existing zone is not installed, we do not consider this a failure ret["result"] = True - ret["comment"] = "zone {0} is not configured!".format(name) + ret["comment"] = "zone {} is not configured!".format(name) return ret diff --git a/salt/states/zookeeper.py b/salt/states/zookeeper.py index 525bf65b782..d912b0b11f2 100644 --- a/salt/states/zookeeper.py +++ b/salt/states/zookeeper.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ :depends: kazoo :configuration: See :py:mod:`salt.modules.zookeeper` for setup instructions. @@ -26,8 +25,6 @@ The following options can be included in the acl dictionary: :type all: bool """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals __virtualname__ = "zookeeper" @@ -135,7 +132,7 @@ def present( ret = { "name": name, "result": False, - "comment": "Failed to setup znode {0}".format(name), + "comment": "Failed to setup znode {}".format(name), "changes": {}, } connkwargs = { @@ -157,13 +154,13 @@ def present( ret["result"] = True ret[ "comment" - ] = "Znode {0} is already set to the correct value with the correct acls".format( + ] = "Znode {} is already set to the correct value with the correct acls".format( name ) return ret elif __opts__["test"] is True: ret["result"] = None - ret["comment"] = "Znode {0} is will be updated".format(name) + ret["comment"] = "Znode {} is will be updated".format(name) ret["changes"]["old"] = {} ret["changes"]["new"] = {} if value != cur_value: @@ -191,12 +188,12 @@ def present( ret["changes"] = changes if value_result and acl_result: ret["result"] = True - ret["comment"] = "Znode {0} successfully updated".format(name) + ret["comment"] = "Znode {} successfully updated".format(name) return ret if __opts__["test"] is True: ret["result"] = None - ret["comment"] = "{0} is will be created".format(name) + ret["comment"] = "{} is will be created".format(name) ret["changes"]["old"] = {} ret["changes"]["new"] = {} ret["changes"]["new"]["acls"] = chk_acls @@ -221,7 +218,7 @@ def present( ret["changes"] = changes if value_result and acl_result: ret["result"] = True - ret["comment"] = "Znode {0} successfully created".format(name) + ret["comment"] = "Znode {} successfully created".format(name) return ret @@ -279,7 +276,7 @@ def absent( ret = { "name": name, "result": False, - "comment": "Failed to delete znode {0}".format(name), + "comment": "Failed to delete znode {}".format(name), "changes": {}, } connkwargs = { @@ -293,7 +290,7 @@ def absent( if __salt__["zookeeper.exists"](name, **connkwargs) is False: ret["result"] = True - ret["comment"] = "Znode {0} does not exist".format(name) + ret["comment"] = "Znode {} does not exist".format(name) return ret changes = {} @@ -304,7 +301,7 @@ def absent( if __opts__["test"] is True: ret["result"] = None - ret["comment"] = "Znode {0} will be removed".format(name) + ret["comment"] = "Znode {} will be removed".format(name) ret["changes"]["old"] = changes return ret @@ -312,7 +309,7 @@ def absent( if __salt__["zookeeper.exists"](name, **connkwargs) is False: ret["result"] = True - ret["comment"] = "Znode {0} has been removed".format(name) + ret["comment"] = "Znode {} has been removed".format(name) ret["changes"]["old"] = changes return ret @@ -376,7 +373,7 @@ def acls( ret = { "name": name, "result": False, - "comment": "Failed to set acls on znode {0}".format(name), + "comment": "Failed to set acls on znode {}".format(name), "changes": {}, } connkwargs = { @@ -398,12 +395,12 @@ def acls( cur_acls = __salt__["zookeeper.get_acls"](name, **connkwargs) if _check_acls(cur_acls, chk_acls): ret["result"] = True - ret["comment"] = "Znode {0} acls already set".format(name) + ret["comment"] = "Znode {} acls already set".format(name) return ret if __opts__["test"] is True: ret["result"] = None - ret["comment"] = "Znode {0} acls will be updated".format(name) + ret["comment"] = "Znode {} acls will be updated".format(name) ret["changes"]["old"] = cur_acls ret["changes"]["new"] = chk_acls return ret @@ -414,7 +411,7 @@ def acls( ret["changes"] = {"old": cur_acls, "new": new_acls} if _check_acls(new_acls, chk_acls): ret["result"] = True - ret["comment"] = "Znode {0} acls updated".format(name) + ret["comment"] = "Znode {} acls updated".format(name) return ret - ret["comment"] = "Znode {0} acls failed to update".format(name) + ret["comment"] = "Znode {} acls failed to update".format(name) return ret diff --git a/salt/states/zpool.py b/salt/states/zpool.py index c5b3dc5122b..cadf877c6ff 100644 --- a/salt/states/zpool.py +++ b/salt/states/zpool.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ States for managing zpools @@ -69,14 +68,10 @@ States for managing zpools Filesystem properties are also not updated, this should be managed by the zfs state module. """ -from __future__ import absolute_import, print_function, unicode_literals import logging - -# Import Python libs import os -# Import Salt libs from salt.utils.odict import OrderedDict log = logging.getLogger(__name__) @@ -297,11 +292,11 @@ def present( if __opts__["test"]: if __salt__["zpool.exists"](name): ret["result"] = True - ret["comment"] = "storage pool {0} is {1}".format(name, "uptodate") + ret["comment"] = "storage pool {} is {}".format(name, "uptodate") else: ret["result"] = None ret["changes"][name] = "imported" if config["import"] else "created" - ret["comment"] = "storage pool {0} would have been {1}".format( + ret["comment"] = "storage pool {} would have been {}".format( name, ret["changes"][name] ) @@ -339,7 +334,7 @@ def present( ret["result"] = False if ret["comment"] == "": ret["comment"] = "The following properties were not updated:" - ret["comment"] = "{0} {1}".format(ret["comment"], prop) + ret["comment"] = "{} {}".format(ret["comment"], prop) if ret["result"]: ret["comment"] = ( @@ -357,7 +352,7 @@ def present( ret["result"] = mod_res["imported"] if ret["result"]: ret["changes"][name] = "imported" - ret["comment"] = "storage pool {0} was imported".format(name) + ret["comment"] = "storage pool {} was imported".format(name) # create pool if not ret["result"] and vdevs: @@ -374,17 +369,17 @@ def present( ret["result"] = mod_res["created"] if ret["result"]: ret["changes"][name] = "created" - ret["comment"] = "storage pool {0} was created".format(name) + ret["comment"] = "storage pool {} was created".format(name) elif "error" in mod_res: ret["comment"] = mod_res["error"] else: - ret["comment"] = "could not create storage pool {0}".format(name) + ret["comment"] = "could not create storage pool {}".format(name) # give up, we cannot import the pool and we do not have a layout to create it if not ret["result"] and not vdevs: ret[ "comment" - ] = "storage pool {0} was not imported, no (valid) layout specified for creation".format( + ] = "storage pool {} was not imported, no (valid) layout specified for creation".format( name ) @@ -430,15 +425,13 @@ def absent(name, export=False, force=False): if ret["result"]: # update the changes and comment ret["changes"][name] = "exported" if export else "destroyed" - ret["comment"] = "storage pool {0} was {1}".format( - name, ret["changes"][name] - ) + ret["comment"] = "storage pool {} was {}".format(name, ret["changes"][name]) elif "error" in mod_res: ret["comment"] = mod_res["error"] else: # we are looking good ret["result"] = True - ret["comment"] = "storage pool {0} is absent".format(name) + ret["comment"] = "storage pool {} is absent".format(name) return ret diff --git a/tests/__init__.py b/tests/__init__.py index 40a96afc6ff..e69de29bb2d 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/tests/buildpackage.py b/tests/buildpackage.py index 6b85b961dae..914f724d76e 100644 --- a/tests/buildpackage.py +++ b/tests/buildpackage.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # Maintainer: Erik Johnson (https://github.com/terminalmage) # # WARNING: This script will recursively remove the build and artifact @@ -10,7 +9,6 @@ # pylint: disable=file-perms,resource-leakage -from __future__ import absolute_import, print_function import errno import glob @@ -131,21 +129,21 @@ def _init(): if not opts.platform: problems.append("Platform ('os' grain) required") if not os.path.isdir(opts.source_dir): - problems.append("Source directory {0} not found".format(opts.source_dir)) + problems.append("Source directory {} not found".format(opts.source_dir)) try: shutil.rmtree(opts.build_dir) except OSError as exc: if exc.errno not in (errno.ENOENT, errno.ENOTDIR): problems.append( "Unable to remove pre-existing destination " - "directory {0}: {1}".format(opts.build_dir, exc) + "directory {}: {}".format(opts.build_dir, exc) ) finally: try: os.makedirs(opts.build_dir) except OSError as exc: problems.append( - "Unable to create destination directory {0}: {1}".format( + "Unable to create destination directory {}: {}".format( opts.build_dir, exc ) ) @@ -155,14 +153,14 @@ def _init(): if exc.errno not in (errno.ENOENT, errno.ENOTDIR): problems.append( "Unable to remove pre-existing artifact directory " - "{0}: {1}".format(opts.artifact_dir, exc) + "{}: {}".format(opts.artifact_dir, exc) ) finally: try: os.makedirs(opts.artifact_dir) except OSError as exc: problems.append( - "Unable to create artifact directory {0}: {1}".format( + "Unable to create artifact directory {}: {}".format( opts.artifact_dir, exc ) ) @@ -194,14 +192,14 @@ def _move(src, dst): def _run_command(args): - log.info("Running command: {0}".format(args)) + log.info("Running command: {}".format(args)) proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = proc.communicate() if stdout: - log.debug("Command output: \n{0}".format(stdout)) + log.debug("Command output: \n{}".format(stdout)) if stderr: log.error(stderr) - log.info("Return code: {0}".format(proc.returncode)) + log.info("Return code: {}".format(proc.returncode)) return stdout, stderr, proc.returncode @@ -214,7 +212,7 @@ def _make_sdist(opts, python_bin="python"): glob.iglob(os.path.join(opts.source_dir, "dist", "salt-*.tar.gz")), key=os.path.getctime, ) - log.info("sdist is located at {0}".format(sdist_path)) + log.info("sdist is located at {}".format(sdist_path)) return sdist_path else: _abort("Failed to create sdist") @@ -230,20 +228,20 @@ def build_centos(opts): log.info("Building CentOS RPM") log.info("Detecting major release") try: - with open("/etc/redhat-release", "r") as fp_: + with open("/etc/redhat-release") as fp_: redhat_release = fp_.read().strip() major_release = int(redhat_release.split()[2].split(".")[0]) except (ValueError, IndexError): _abort( "Unable to determine major release from /etc/redhat-release " - "contents: '{0}'".format(redhat_release) + "contents: '{}'".format(redhat_release) ) - except IOError as exc: - _abort("{0}".format(exc)) + except OSError as exc: + _abort("{}".format(exc)) - log.info("major_release: {0}".format(major_release)) + log.info("major_release: {}".format(major_release)) - define_opts = ["--define", "_topdir {0}".format(os.path.join(opts.build_dir))] + define_opts = ["--define", "_topdir {}".format(os.path.join(opts.build_dir))] build_reqs = ["rpm-build"] if major_release == 5: python_bin = "python26" @@ -256,7 +254,7 @@ def build_centos(opts): elif major_release == 7: build_reqs.extend(["python-devel", "systemd-units"]) else: - _abort("Unsupported major release: {0}".format(major_release)) + _abort("Unsupported major release: {}".format(major_release)) # Install build deps _run_command(["yum", "-y", "install"] + build_reqs) @@ -274,7 +272,7 @@ def build_centos(opts): try: base, offset, oid = tarball_re.match(os.path.basename(sdist)).groups() except AttributeError: - _abort("Unable to extract version info from sdist filename '{0}'".format(sdist)) + _abort("Unable to extract version info from sdist filename '{}'".format(sdist)) if offset is None: salt_pkgver = salt_srcver = base @@ -282,8 +280,8 @@ def build_centos(opts): salt_pkgver = ".".join((base, offset, oid)) salt_srcver = "-".join((base, offset, oid)) - log.info("salt_pkgver: {0}".format(salt_pkgver)) - log.info("salt_srcver: {0}".format(salt_srcver)) + log.info("salt_pkgver: {}".format(salt_pkgver)) + log.info("salt_srcver: {}".format(salt_srcver)) # Setup build environment for build_dir in "BUILD BUILDROOT RPMS SOURCES SPECS SRPMS".split(): @@ -293,7 +291,7 @@ def build_centos(opts): except OSError: pass if not os.path.isdir(path): - _abort("Unable to make directory: {0}".format(path)) + _abort("Unable to make directory: {}".format(path)) # Get sources into place build_sources_path = os.path.join(opts.build_dir, "SOURCES") @@ -316,14 +314,14 @@ def build_centos(opts): # Prepare SPEC file spec_path = os.path.join(opts.build_dir, "SPECS", "salt.spec") - with open(opts.spec_file, "r") as spec: + with open(opts.spec_file) as spec: spec_lines = spec.read().splitlines() with open(spec_path, "w") as fp_: for line in spec_lines: if line.startswith("%global srcver "): - line = "%global srcver {0}".format(salt_srcver) + line = "%global srcver {}".format(salt_srcver) elif line.startswith("Version: "): - line = "Version: {0}".format(salt_pkgver) + line = "Version: {}".format(salt_pkgver) fp_.write(line + "\n") # Do the thing @@ -340,13 +338,13 @@ def build_centos(opts): opts.build_dir, "RPMS", "noarch", - "salt-*{0}*.noarch.rpm".format(salt_pkgver), + "salt-*{}*.noarch.rpm".format(salt_pkgver), ) ) packages.extend( glob.glob( os.path.join( - opts.build_dir, "SRPMS", "salt-{0}*.src.rpm".format(salt_pkgver) + opts.build_dir, "SRPMS", "salt-{}*.src.rpm".format(salt_pkgver) ) ) ) @@ -359,7 +357,7 @@ if __name__ == "__main__": opts = _init() print( - "Starting {0} build. Progress will be logged to {1}.".format( + "Starting {} build. Progress will be logged to {}.".format( opts.platform, opts.log_file ) ) @@ -380,7 +378,7 @@ if __name__ == "__main__": ) if opts.log_level not in LOG_LEVELS: log.error( - "Invalid log level '{0}', falling back to 'warning'".format(opts.log_level) + "Invalid log level '{}', falling back to 'warning'".format(opts.log_level) ) # Build for the specified platform @@ -389,12 +387,12 @@ if __name__ == "__main__": elif opts.platform.lower() == "centos": artifacts = build_centos(opts) else: - _abort("Unsupported platform '{0}'".format(opts.platform)) + _abort("Unsupported platform '{}'".format(opts.platform)) - msg = "Build complete. Artifacts will be stored in {0}".format(opts.artifact_dir) + msg = "Build complete. Artifacts will be stored in {}".format(opts.artifact_dir) log.info(msg) print(msg) # pylint: disable=C0325 for artifact in artifacts: shutil.copy(artifact, opts.artifact_dir) - log.info("Copied {0} to artifact directory".format(artifact)) + log.info("Copied {} to artifact directory".format(artifact)) log.info("Done!") diff --git a/tests/committer_parser.py b/tests/committer_parser.py index 5633d1c3944..e32cf20b8a3 100644 --- a/tests/committer_parser.py +++ b/tests/committer_parser.py @@ -1,5 +1,4 @@ #!/usr/bin/python -# -*- coding: utf-8 -*- # # committer_parser.py # @@ -13,8 +12,6 @@ To use this commit parser script pipe git log into the stdin: """ # pylint: disable=resource-leakage -# Import python libs -from __future__ import absolute_import, print_function import datetime import email.utils @@ -83,7 +80,7 @@ def parse_gitlog(filename=None): if len(line) < 2 and new_commit: new_commit = False - key = "{0}-{1}".format(d.year, str(d.month).zfill(2)) + key = "{}-{}".format(d.year, str(d.month).zfill(2)) if key not in results: results[key] = [] @@ -113,15 +110,15 @@ def counts_by_contributor(commits_by_contributor, results): output = "" dates = sorted(results.keys()) for d in dates: - output += "\t{0}".format(d) + output += "\t{}".format(d) output += "\n" for email in sorted(commits_by_contributor.keys()): - output += "'{0}".format(email) + output += "'{}".format(email) for d in dates: if d in commits_by_contributor[email]: - output += "\t{0}".format(commits_by_contributor[email][d]) + output += "\t{}".format(commits_by_contributor[email][d]) else: output += "\t" output += "\n" @@ -132,7 +129,7 @@ def count_results(results, commits): result_str = "" print("Date\tContributors\tCommits") for k in sorted(results.keys()): - result_str += "{0}\t{1}\t{2}".format(k, len(results[k]), commits[k]) + result_str += "{}\t{}\t{}".format(k, len(results[k]), commits[k]) result_str += "\n" return result_str diff --git a/tests/eventlisten.py b/tests/eventlisten.py index e2e4b66b11a..03154d79e62 100644 --- a/tests/eventlisten.py +++ b/tests/eventlisten.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - """ Use this script to dump the event data out to the terminal. It needs to know what the sock_dir is. @@ -7,20 +5,14 @@ what the sock_dir is. This script is a generic tool to test event output """ -# Import Python libs -from __future__ import absolute_import, print_function import optparse import os import pprint import time -# Import Salt libs import salt.utils.event -# Import 3rd-party libs -from salt.ext import six - def parse(): """ @@ -74,7 +66,7 @@ def parse(): opts = {} - for k, v in six.iteritems(options.__dict__): + for k, v in options.__dict__.items(): if v is not None: opts[k] = v @@ -106,7 +98,7 @@ def check_access_and_print_warning(sock_dir): else: print( "WARNING: Events will not be reported" - " (not able to access {0})".format(sock_dir) + " (not able to access {})".format(sock_dir) ) @@ -132,23 +124,20 @@ def listen(opts): if opts["func_count"]: data = ret.get("data", False) if data: - if ( - "id" in six.iterkeys(data) - and data.get("id", False) not in found_minions - ): + if "id" in data.keys() and data.get("id", False) not in found_minions: if data["fun"] == opts["func_count"]: jid_counter += 1 found_minions.append(data["id"]) print( - "Reply received from [{0}]. Total replies now: [{1}].".format( + "Reply received from [{}]. Total replies now: [{}].".format( ret["data"]["id"], jid_counter ) ) continue else: - print("Event fired at {0}".format(time.asctime())) + print("Event fired at {}".format(time.asctime())) print("*" * 25) - print("Tag: {0}".format(ret["tag"])) + print("Tag: {}".format(ret["tag"])) print("Data:") pprint.pprint(ret["data"]) diff --git a/tests/integration/client/__init__.py b/tests/integration/client/__init__.py index 40a96afc6ff..e69de29bb2d 100644 --- a/tests/integration/client/__init__.py +++ b/tests/integration/client/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/tests/integration/cloud/__init__.py b/tests/integration/cloud/__init__.py index 40a96afc6ff..e69de29bb2d 100644 --- a/tests/integration/cloud/__init__.py +++ b/tests/integration/cloud/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/tests/integration/cloud/clouds/__init__.py b/tests/integration/cloud/clouds/__init__.py index 40a96afc6ff..e69de29bb2d 100644 --- a/tests/integration/cloud/clouds/__init__.py +++ b/tests/integration/cloud/clouds/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/tests/integration/cloud/clouds/test_dimensiondata.py b/tests/integration/cloud/clouds/test_dimensiondata.py index 86e466d78a5..56ac83042c3 100644 --- a/tests/integration/cloud/clouds/test_dimensiondata.py +++ b/tests/integration/cloud/clouds/test_dimensiondata.py @@ -1,12 +1,8 @@ -# -*- coding: utf-8 -*- """ Integration tests for the Dimension Data cloud provider """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals -# Import Salt Testing Libs from tests.integration.cloud.helpers.cloud_test_base import TIMEOUT, CloudTest @@ -22,14 +18,14 @@ class DimensionDataTest(CloudTest): """ Tests the return of running the --list-images command for the dimensiondata cloud provider """ - image_list = self.run_cloud("--list-images {0}".format(self.PROVIDER)) + image_list = self.run_cloud("--list-images {}".format(self.PROVIDER)) self.assertIn("Ubuntu 14.04 2 CPU", [i.strip() for i in image_list]) def test_list_locations(self): """ Tests the return of running the --list-locations command for the dimensiondata cloud provider """ - _list_locations = self.run_cloud("--list-locations {0}".format(self.PROVIDER)) + _list_locations = self.run_cloud("--list-locations {}".format(self.PROVIDER)) self.assertIn( "Australia - Melbourne MCP2", [i.strip() for i in _list_locations] ) @@ -38,7 +34,7 @@ class DimensionDataTest(CloudTest): """ Tests the return of running the --list-sizes command for the dimensiondata cloud provider """ - _list_sizes = self.run_cloud("--list-sizes {0}".format(self.PROVIDER)) + _list_sizes = self.run_cloud("--list-sizes {}".format(self.PROVIDER)) self.assertIn("default", [i.strip() for i in _list_sizes]) def test_instance(self): @@ -47,7 +43,7 @@ class DimensionDataTest(CloudTest): """ # check if instance with salt installed returned ret_val = self.run_cloud( - "-p dimensiondata-test {0}".format(self.instance_name), timeout=TIMEOUT + "-p dimensiondata-test {}".format(self.instance_name), timeout=TIMEOUT ) self.assertInstanceExists(ret_val) diff --git a/tests/integration/cloud/clouds/test_ec2.py b/tests/integration/cloud/clouds/test_ec2.py index a8a2192d6b6..0a3e3f9881b 100644 --- a/tests/integration/cloud/clouds/test_ec2.py +++ b/tests/integration/cloud/clouds/test_ec2.py @@ -1,9 +1,7 @@ -# -*- coding: utf-8 -*- """ :codeauthor: Nicole Thomas """ -from __future__ import absolute_import, print_function, unicode_literals import os @@ -67,7 +65,7 @@ class EC2Test(CloudTest): "securitygroup or subnetid missing for {} config".format(self.PROVIDER) ) - super(EC2Test, self).setUp() + super().setUp() def override_profile_config(self, name, data): conf_path = os.path.join( @@ -115,7 +113,7 @@ class EC2Test(CloudTest): """ # create the instance ret_val = self.run_cloud( - "-p ec2-test {0} --no-deploy".format(self.instance_name), timeout=TIMEOUT + "-p ec2-test {} --no-deploy".format(self.instance_name), timeout=TIMEOUT ) # check if instance returned self.assertInstanceExists(ret_val) @@ -123,7 +121,7 @@ class EC2Test(CloudTest): changed_name = self.instance_name + "-changed" rename_result = self.run_cloud( - "-a rename {0} newname={1} --assume-yes".format( + "-a rename {} newname={} --assume-yes".format( self.instance_name, changed_name ), timeout=TIMEOUT, diff --git a/tests/integration/cloud/clouds/test_gce.py b/tests/integration/cloud/clouds/test_gce.py index f28506a010e..affa0134fc5 100644 --- a/tests/integration/cloud/clouds/test_gce.py +++ b/tests/integration/cloud/clouds/test_gce.py @@ -1,13 +1,9 @@ -# -*- coding: utf-8 -*- """ :codeauthor: Nicole Thomas :codeauthor: Tomas Sirny """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals -# Import Salt Testing Libs from tests.integration.cloud.helpers.cloud_test_base import TIMEOUT, CloudTest @@ -30,7 +26,7 @@ class GCETest(CloudTest): # create the instance ret_str = self.run_cloud( - "-p gce-test {0}".format(self.instance_name), timeout=TIMEOUT + "-p gce-test {}".format(self.instance_name), timeout=TIMEOUT ) # check if instance returned with salt installed @@ -44,7 +40,7 @@ class GCETest(CloudTest): # create the instance ret_str = self.run_cloud( - "-p gce-test-extra {0}".format(self.instance_name), timeout=TIMEOUT + "-p gce-test-extra {}".format(self.instance_name), timeout=TIMEOUT ) # check if instance returned with salt installed diff --git a/tests/integration/cloud/clouds/test_gogrid.py b/tests/integration/cloud/clouds/test_gogrid.py index cebe3743f25..7c08a700fe0 100644 --- a/tests/integration/cloud/clouds/test_gogrid.py +++ b/tests/integration/cloud/clouds/test_gogrid.py @@ -1,15 +1,10 @@ -# -*- coding: utf-8 -*- """ :codeauthor: Nicole Thomas """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals # Create the cloud instance name to be used throughout the tests from tests.integration.cloud.helpers.cloud_test_base import TIMEOUT, CloudTest - -# Import Salt Testing Libs from tests.support.unit import skipIf @@ -28,7 +23,7 @@ class GoGridTest(CloudTest): """ # check if instance with salt installed returned ret_str = self.run_cloud( - "-p gogrid-test {0}".format(self.instance_name), timeout=TIMEOUT + "-p gogrid-test {}".format(self.instance_name), timeout=TIMEOUT ) self.assertInstanceExists(ret_str) diff --git a/tests/integration/cloud/clouds/test_linode.py b/tests/integration/cloud/clouds/test_linode.py index af0e0f6bc80..7b0919cb2f1 100644 --- a/tests/integration/cloud/clouds/test_linode.py +++ b/tests/integration/cloud/clouds/test_linode.py @@ -2,7 +2,6 @@ :codeauthor: Nicole Thomas """ -# Import Python Libs # Create the cloud instance name to be used throughout the tests from tests.integration.cloud.helpers.cloud_test_base import TIMEOUT, CloudTest diff --git a/tests/integration/cloud/clouds/test_oneandone.py b/tests/integration/cloud/clouds/test_oneandone.py index 36d1e93029d..b5ff2da02e5 100644 --- a/tests/integration/cloud/clouds/test_oneandone.py +++ b/tests/integration/cloud/clouds/test_oneandone.py @@ -1,16 +1,11 @@ -# -*- coding: utf-8 -*- """ :codeauthor: :email:`Amel Ajdinovic ` """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals -# Import Salt Testing Libs from tests.integration.cloud.helpers.cloud_test_base import TIMEOUT, CloudTest from tests.support.unit import skipIf -# Import Third-Party Libs try: from oneandone.client import OneAndOneService # pylint: disable=unused-import @@ -32,7 +27,7 @@ class OneAndOneTest(CloudTest): """ Tests the return of running the --list-images command for 1and1 """ - image_list = self.run_cloud("--list-images {0}".format(self.PROVIDER_NAME)) + image_list = self.run_cloud("--list-images {}".format(self.PROVIDER_NAME)) self.assertIn("coreOSimage", [i.strip() for i in image_list]) def test_instance(self): @@ -41,7 +36,7 @@ class OneAndOneTest(CloudTest): """ # check if instance with salt installed returned ret_str = self.run_cloud( - "-p oneandone-test {0}".format(self.instance_name), timeout=TIMEOUT + "-p oneandone-test {}".format(self.instance_name), timeout=TIMEOUT ) self.assertInstanceExists(ret_str) diff --git a/tests/integration/cloud/clouds/test_profitbricks.py b/tests/integration/cloud/clouds/test_profitbricks.py index 8be5d9a4562..a2759cf44a0 100644 --- a/tests/integration/cloud/clouds/test_profitbricks.py +++ b/tests/integration/cloud/clouds/test_profitbricks.py @@ -1,15 +1,9 @@ -# -*- coding: utf-8 -*- """ :codeauthor: Ethan Devenport """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals -# Import Third-Party Libs from tests.integration.cloud.helpers.cloud_test_base import TIMEOUT, CloudTest - -# Import Salt Testing Libs from tests.support.unit import skipIf try: @@ -31,7 +25,7 @@ class ProfitBricksTest(CloudTest): REQUIRED_PROVIDER_CONFIG_ITEMS = ("username", "password", "datacenter_id") def setUp(self): - super(ProfitBricksTest, self).setUp() + super().setUp() username = self.provider_config.get("username") password = self.provider_config.get("password") @@ -40,7 +34,7 @@ class ProfitBricksTest(CloudTest): self.skipTest( "Conf items are missing that must be provided to run these tests: username, password" - "\nCheck tests/integration/files/conf/cloud.providers.d/{0}.conf".format( + "\nCheck tests/integration/files/conf/cloud.providers.d/{}.conf".format( self.PROVIDER ) ) @@ -49,7 +43,7 @@ class ProfitBricksTest(CloudTest): """ Tests the return of running the --list-images command for ProfitBricks """ - list_images = self.run_cloud("--list-images {0}".format(self.PROVIDER)) + list_images = self.run_cloud("--list-images {}".format(self.PROVIDER)) self.assertIn( "Ubuntu-16.04-LTS-server-2017-10-01", [i.strip() for i in list_images] ) @@ -59,7 +53,7 @@ class ProfitBricksTest(CloudTest): Tests the return of running the -f list_images command for ProfitBricks """ - cmd = "-f list_images {0}".format(self.PROVIDER) + cmd = "-f list_images {}".format(self.PROVIDER) list_images = self.run_cloud(cmd) self.assertIn("- ubuntu:latest", [i.strip() for i in list_images]) @@ -67,7 +61,7 @@ class ProfitBricksTest(CloudTest): """ Tests the return of running the --list_sizes command for ProfitBricks """ - list_sizes = self.run_cloud("--list-sizes {0}".format(self.PROVIDER)) + list_sizes = self.run_cloud("--list-sizes {}".format(self.PROVIDER)) self.assertIn("Micro Instance:", [i.strip() for i in list_sizes]) def test_list_datacenters(self): @@ -75,7 +69,7 @@ class ProfitBricksTest(CloudTest): Tests the return of running the -f list_datacenters command for ProfitBricks """ - cmd = "-f list_datacenters {0}".format(self.PROVIDER) + cmd = "-f list_datacenters {}".format(self.PROVIDER) list_datacenters = self.run_cloud(cmd) self.assertIn( self.provider_config["datacenter_id"], [i.strip() for i in list_datacenters] @@ -85,7 +79,7 @@ class ProfitBricksTest(CloudTest): """ Tests the return of running the -f list_nodes command for ProfitBricks """ - list_nodes = self.run_cloud("-f list_nodes {0}".format(self.PROVIDER)) + list_nodes = self.run_cloud("-f list_nodes {}".format(self.PROVIDER)) self.assertIn("state:", [i.strip() for i in list_nodes]) self.assertIn("name:", [i.strip() for i in list_nodes]) @@ -95,7 +89,7 @@ class ProfitBricksTest(CloudTest): Tests the return of running the -f list_nodes_full command for ProfitBricks """ - cmd = "-f list_nodes_full {0}".format(self.PROVIDER) + cmd = "-f list_nodes_full {}".format(self.PROVIDER) list_nodes = self.run_cloud(cmd) self.assertIn("state:", [i.strip() for i in list_nodes]) @@ -106,7 +100,7 @@ class ProfitBricksTest(CloudTest): Tests the return of running the --list-locations command for ProfitBricks """ - cmd = "--list-locations {0}".format(self.PROVIDER) + cmd = "--list-locations {}".format(self.PROVIDER) list_locations = self.run_cloud(cmd) self.assertIn("de/fkb", [i.strip() for i in list_locations]) @@ -123,7 +117,7 @@ class ProfitBricksTest(CloudTest): """ # check if instance with salt installed returned ret_str = self.run_cloud( - "-p profitbricks-test {0}".format(self.instance_name), timeout=TIMEOUT + "-p profitbricks-test {}".format(self.instance_name), timeout=TIMEOUT ) self.assertInstanceExists(ret_str) diff --git a/tests/integration/cloud/clouds/test_virtualbox.py b/tests/integration/cloud/clouds/test_virtualbox.py index 87fcd8f4d7b..6871c52b584 100644 --- a/tests/integration/cloud/clouds/test_virtualbox.py +++ b/tests/integration/cloud/clouds/test_virtualbox.py @@ -1,19 +1,12 @@ -# -*- coding: utf-8 -*- # This code assumes vboxapi.py from VirtualBox distribution # being in PYTHONPATH, or installed system-wide -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals import logging import os import socket from salt.config import cloud_providers_config, vm_profiles_config - -# Import Salt Libs -from salt.ext import six -from salt.ext.six.moves import range from salt.utils.virtualbox import ( HAS_LIBS, XPCOM_ATTRIBUTES, @@ -41,8 +34,6 @@ from tests.integration.cloud.helpers.virtualbox import ( VirtualboxTestCase, ) from tests.support.runtests import RUNTIME_VARS - -# Import Salt Testing Libs from tests.support.unit import TestCase, skipIf log = logging.getLogger(__name__) @@ -72,7 +63,7 @@ class VirtualboxProviderTest(VirtualboxCloudTestCase): @rtype: dict """ output = self.run_cloud( - "-d {0} --assume-yes --log-level=debug".format(machine_name) + "-d {} --assume-yes --log-level=debug".format(machine_name) ) return output.get(CONFIG_NAME, {}).get(PROVIDER_NAME, {}) @@ -80,7 +71,7 @@ class VirtualboxProviderTest(VirtualboxCloudTestCase): """ Sets up the test requirements """ - super(VirtualboxProviderTest, self).setUp() + super().setUp() # check if appropriate cloud provider and profile files are present profile_str = "virtualbox-config" @@ -109,7 +100,7 @@ class VirtualboxProviderTest(VirtualboxCloudTestCase): profile = profiles.get(PROFILE_NAME) if not profile: self.skipTest( - "Profile {0} was not found. Check {1}.conf files " + "Profile {} was not found. Check {}.conf files " "in tests/integration/files/conf/cloud.profiles.d/ to run these tests.".format( PROFILE_NAME, PROVIDER_NAME ) @@ -118,9 +109,9 @@ class VirtualboxProviderTest(VirtualboxCloudTestCase): if base_box_name != BASE_BOX_NAME: self.skipTest( - "Profile {0} does not have a base box to clone from. Check {1}.conf files " + "Profile {} does not have a base box to clone from. Check {}.conf files " "in tests/integration/files/conf/cloud.profiles.d/ to run these tests." - 'And add a "clone_from: {2}" to the profile'.format( + 'And add a "clone_from: {}" to the profile'.format( PROFILE_NAME, PROVIDER_NAME, BASE_BOX_NAME ) ) @@ -138,7 +129,7 @@ class VirtualboxProviderTest(VirtualboxCloudTestCase): Simply create a machine and make sure it was created """ machines = self.run_cloud( - "-p {0} {1} --log-level=debug".format(PROFILE_NAME, INSTANCE_NAME) + "-p {} {} --log-level=debug".format(PROFILE_NAME, INSTANCE_NAME) ) self.assertIn(INSTANCE_NAME, machines.keys()) @@ -151,11 +142,8 @@ class VirtualboxProviderTest(VirtualboxCloudTestCase): expected_attributes = MINIMAL_MACHINE_ATTRIBUTES names = machines.keys() self.assertGreaterEqual(len(names), 1, "No machines found") - for name, machine in six.iteritems(machines): - if six.PY3: - self.assertCountEqual(expected_attributes, machine.keys()) - else: - self.assertItemsEqual(expected_attributes, machine.keys()) + for name, machine in machines.items(): + self.assertCountEqual(expected_attributes, machine.keys()) self.assertIn(BASE_BOX_NAME, names) @@ -168,7 +156,7 @@ class VirtualboxProviderTest(VirtualboxCloudTestCase): names = machines.keys() self.assertGreaterEqual(len(names), 1, "No machines found") - for name, machine in six.iteritems(machines): + for name, machine in machines.items(): self.assertGreaterEqual( len(machine.keys()), expected_minimal_attribute_count ) @@ -185,11 +173,8 @@ class VirtualboxProviderTest(VirtualboxCloudTestCase): names = machines.keys() self.assertGreaterEqual(len(names), 1, "No machines found") - for name, machine in six.iteritems(machines): - if six.PY3: - self.assertCountEqual(expected_attributes, machine.keys()) - else: - self.assertItemsEqual(expected_attributes, machine.keys()) + for name, machine in machines.items(): + self.assertCountEqual(expected_attributes, machine.keys()) self.assertIn(BASE_BOX_NAME, names) @@ -222,7 +207,7 @@ class VirtualboxProviderTest(VirtualboxCloudTestCase): @skipIf( HAS_LIBS and vb_machine_exists(BOOTABLE_BASE_BOX_NAME) is False, - "Bootable VM '{0}' not found. Cannot run tests.".format(BOOTABLE_BASE_BOX_NAME), + "Bootable VM '{}' not found. Cannot run tests.".format(BOOTABLE_BASE_BOX_NAME), ) class VirtualboxProviderHeavyTests(VirtualboxCloudTestCase): """ @@ -243,7 +228,7 @@ class VirtualboxProviderHeavyTests(VirtualboxCloudTestCase): try: socket.inet_pton(socket.AF_INET6, ip_str) except Exception: # pylint: disable=broad-except - self.fail("{0} is not a valid IP address".format(ip_str)) + self.fail("{} is not a valid IP address".format(ip_str)) def setUp(self): """ @@ -276,7 +261,7 @@ class VirtualboxProviderHeavyTests(VirtualboxCloudTestCase): profile = profiles.get(DEPLOY_PROFILE_NAME) if not profile: self.skipTest( - "Profile {0} was not found. Check {1}.conf files " + "Profile {} was not found. Check {}.conf files " "in tests/integration/files/conf/cloud.profiles.d/ to run these tests.".format( DEPLOY_PROFILE_NAME, PROVIDER_NAME ) @@ -285,9 +270,9 @@ class VirtualboxProviderHeavyTests(VirtualboxCloudTestCase): if base_box_name != BOOTABLE_BASE_BOX_NAME: self.skipTest( - "Profile {0} does not have a base box to clone from. Check {1}.conf files " + "Profile {} does not have a base box to clone from. Check {}.conf files " "in tests/integration/files/conf/cloud.profiles.d/ to run these tests." - 'And add a "clone_from: {2}" to the profile'.format( + 'And add a "clone_from: {}" to the profile'.format( PROFILE_NAME, PROVIDER_NAME, BOOTABLE_BASE_BOX_NAME ) ) @@ -307,7 +292,7 @@ class VirtualboxProviderHeavyTests(VirtualboxCloudTestCase): def test_deploy(self): machines = self.run_cloud( - "-p {0} {1} --log-level=debug".format(DEPLOY_PROFILE_NAME, INSTANCE_NAME) + "-p {} {} --log-level=debug".format(DEPLOY_PROFILE_NAME, INSTANCE_NAME) ) self.assertIn(INSTANCE_NAME, machines.keys()) machine = machines[INSTANCE_NAME] @@ -396,7 +381,7 @@ class CloneVirtualboxTests(VirtualboxTestCase): @skipIf( HAS_LIBS and vb_machine_exists(BOOTABLE_BASE_BOX_NAME) is False, - "Bootable VM '{0}' not found. Cannot run tests.".format(BOOTABLE_BASE_BOX_NAME), + "Bootable VM '{}' not found. Cannot run tests.".format(BOOTABLE_BASE_BOX_NAME), ) class BootVirtualboxTests(VirtualboxTestCase): def test_start_stop(self): @@ -411,16 +396,16 @@ class BootVirtualboxTests(VirtualboxTestCase): class XpcomConversionTests(TestCase): @classmethod def _mock_xpcom_object(cls, interface_name=None, attributes=None): - class XPCOM(object): + class XPCOM: def __str__(self): - return "' (implementing {0})>".format( + return "' (implementing {})>".format( interface_name ) o = XPCOM() if attributes and isinstance(attributes, dict): - for key, value in six.iteritems(attributes): + for key, value in attributes.items(): setattr(o, key, value) return o @@ -458,9 +443,9 @@ class XpcomConversionTests(TestCase): expected_extras = { "extra": "extra", } - expected_machine = dict( - [(attribute, attribute) for attribute in XPCOM_ATTRIBUTES[interface]] - ) + expected_machine = { + attribute: attribute for attribute in XPCOM_ATTRIBUTES[interface] + } expected_machine.update(expected_extras) imachine = XpcomConversionTests._mock_xpcom_object( diff --git a/tests/integration/cloud/clouds/test_vultrpy.py b/tests/integration/cloud/clouds/test_vultrpy.py index fd3a9a4736e..7eea2fb7943 100644 --- a/tests/integration/cloud/clouds/test_vultrpy.py +++ b/tests/integration/cloud/clouds/test_vultrpy.py @@ -1,14 +1,10 @@ -# -*- coding: utf-8 -*- """ Integration tests for Vultr """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals import time -# Import Salt Testing Libs from tests.integration.cloud.helpers.cloud_test_base import TIMEOUT, CloudTest from tests.support.unit import skipIf @@ -25,7 +21,7 @@ class VultrTest(CloudTest): """ Tests the return of running the --list-images command for Vultr """ - image_list = self.run_cloud("--list-images {0}".format(self.PROVIDER)) + image_list = self.run_cloud("--list-images {}".format(self.PROVIDER)) self.assertIn("Debian 10 x64 (buster)", [i.strip() for i in image_list]) @@ -33,14 +29,14 @@ class VultrTest(CloudTest): """ Tests the return of running the --list-locations command for Vultr """ - location_list = self.run_cloud("--list-locations {0}".format(self.PROVIDER)) + location_list = self.run_cloud("--list-locations {}".format(self.PROVIDER)) self.assertIn("New Jersey", [i.strip() for i in location_list]) def test_list_sizes(self): """ Tests the return of running the --list-sizes command for Vultr """ - size_list = self.run_cloud("--list-sizes {0}".format(self.PROVIDER)) + size_list = self.run_cloud("--list-sizes {}".format(self.PROVIDER)) self.assertIn( "2048 MB RAM,64 GB SSD,2.00 TB BW", [i.strip() for i in size_list] ) @@ -92,7 +88,7 @@ class VultrTest(CloudTest): """ # check if instance with salt installed returned ret_val = self.run_cloud( - "-p vultr-test {0}".format(self.instance_name), timeout=TIMEOUT + 300 + "-p vultr-test {}".format(self.instance_name), timeout=TIMEOUT + 300 ) self.assertInstanceExists(ret_val) diff --git a/tests/integration/cloud/helpers/__init__.py b/tests/integration/cloud/helpers/__init__.py index 3505c84b075..1edbe1f9e07 100644 --- a/tests/integration/cloud/helpers/__init__.py +++ b/tests/integration/cloud/helpers/__init__.py @@ -1,11 +1,6 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals - import random import string -from salt.ext.six.moves import range - def random_name(size=6): """ diff --git a/tests/integration/cloud/helpers/virtualbox.py b/tests/integration/cloud/helpers/virtualbox.py index eb68c5bef37..4f03f2be802 100644 --- a/tests/integration/cloud/helpers/virtualbox.py +++ b/tests/integration/cloud/helpers/virtualbox.py @@ -1,7 +1,3 @@ -# -*- coding: utf-8 -*- - -from __future__ import absolute_import, print_function, unicode_literals - import logging import salt.utils.json @@ -98,12 +94,11 @@ class VirtualboxCloudTestCase(ShellCase): # Args converted in the form of key1='value1' ... keyN='valueN' if kw_function_args: args = [ - "{0}='{1}'".format(key, value) - for key, value in kw_function_args.items() + "{}='{}'".format(key, value) for key, value in kw_function_args.items() ] output = self.run_cloud( - "-f {0} {1} {2}".format(function, CONFIG_NAME, " ".join(args)), **kwargs + "-f {} {} {}".format(function, CONFIG_NAME, " ".join(args)), **kwargs ) return output.get(CONFIG_NAME, {}).get(PROVIDER_NAME, {}) @@ -120,6 +115,6 @@ class VirtualboxCloudTestCase(ShellCase): """ output = self.run_cloud( - "-a {0} {1} --assume-yes".format(action, instance_name), **kwargs + "-a {} {} --assume-yes".format(action, instance_name), **kwargs ) return output.get(CONFIG_NAME, {}).get(PROVIDER_NAME, {}) diff --git a/tests/integration/doc/__init__.py b/tests/integration/doc/__init__.py index 40a96afc6ff..e69de29bb2d 100644 --- a/tests/integration/doc/__init__.py +++ b/tests/integration/doc/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/tests/integration/executors/__init__.py b/tests/integration/executors/__init__.py index 40a96afc6ff..e69de29bb2d 100644 --- a/tests/integration/executors/__init__.py +++ b/tests/integration/executors/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/tests/integration/externalapi/__init__.py b/tests/integration/externalapi/__init__.py index 40a96afc6ff..e69de29bb2d 100644 --- a/tests/integration/externalapi/__init__.py +++ b/tests/integration/externalapi/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/tests/integration/externalapi/test_venafiapi.py b/tests/integration/externalapi/test_venafiapi.py index fa43d917dfc..6bbbac60f2f 100644 --- a/tests/integration/externalapi/test_venafiapi.py +++ b/tests/integration/externalapi/test_venafiapi.py @@ -12,8 +12,6 @@ from cryptography import x509 from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization from cryptography.x509.oid import NameOID -from salt.ext.six import text_type -from salt.ext.six.moves import range from tests.support.case import ShellCase @@ -48,7 +46,7 @@ class VenafiTest(ShellCase): cn = "{}.example.com".format(name) # Provide python27 compatibility - if not isinstance(cn, text_type): + if not isinstance(cn, str): cn = cn.decode() ret = self.run_run_plus( @@ -128,7 +126,7 @@ xlAKgaU6i03jOm5+sww5L2YVMi1eeBN+kx7o94ogpRemC/EUidvl1PUJ6+e7an9V cn = "test-csr-32313131.venafi.example.com" # Provide python27 compatibility - if not isinstance(cn, text_type): + if not isinstance(cn, str): cn = cn.decode() ret = self.run_run_plus( diff --git a/tests/integration/files/extension_modules/pillar/ext_pillar_opts.py b/tests/integration/files/extension_modules/pillar/ext_pillar_opts.py index 8d4aefbed1f..19d4d4e9420 100644 --- a/tests/integration/files/extension_modules/pillar/ext_pillar_opts.py +++ b/tests/integration/files/extension_modules/pillar/ext_pillar_opts.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ External pillar module for testing the contents of __opts__ as seen by external pillar modules. @@ -7,8 +6,6 @@ Returns a hash of the name of the pillar module as defined in _virtual__ with the value __opts__ """ -# Import python libs -from __future__ import absolute_import import logging diff --git a/tests/integration/files/extension_modules/tops/master_tops_test.py b/tests/integration/files/extension_modules/tops/master_tops_test.py index f26b9954b46..f1878877eee 100644 --- a/tests/integration/files/extension_modules/tops/master_tops_test.py +++ b/tests/integration/files/extension_modules/tops/master_tops_test.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function, unicode_literals - import logging log = logging.getLogger(__name__) diff --git a/tests/integration/files/file/base/_executors/arg.py b/tests/integration/files/file/base/_executors/arg.py index 8465f1b81df..310d132c2b1 100644 --- a/tests/integration/files/file/base/_executors/arg.py +++ b/tests/integration/files/file/base/_executors/arg.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- - - def __virtual__(): return True diff --git a/tests/integration/files/file/base/_grains/custom_grain2.py b/tests/integration/files/file/base/_grains/custom_grain2.py index bbf7ca5cefa..b58a81394a8 100644 --- a/tests/integration/files/file/base/_grains/custom_grain2.py +++ b/tests/integration/files/file/base/_grains/custom_grain2.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- - - def myfunction(): grains = {} grains["a_custom"] = {"k2": "v2"} diff --git a/tests/integration/files/file/base/_grains/custom_grains.py b/tests/integration/files/file/base/_grains/custom_grains.py index e015e086933..394ea587783 100644 --- a/tests/integration/files/file/base/_grains/custom_grains.py +++ b/tests/integration/files/file/base/_grains/custom_grains.py @@ -1,5 +1,2 @@ -# -*- coding: utf-8 -*- - - def test(grains): return {"custom_grain_test": "itworked" if "os" in grains else "itdidntwork"} diff --git a/tests/integration/files/file/base/_grains/matcher_grain.py b/tests/integration/files/file/base/_grains/matcher_grain.py index ef4f8c887c2..2b6de9f9996 100644 --- a/tests/integration/files/file/base/_grains/matcher_grain.py +++ b/tests/integration/files/file/base/_grains/matcher_grain.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- - - def myfunction(): grains = {} grains["match"] = "maker" diff --git a/tests/integration/files/file/base/_modules/depends_versioned.py b/tests/integration/files/file/base/_modules/depends_versioned.py index 5119da583f1..9b41a6030dd 100644 --- a/tests/integration/files/file/base/_modules/depends_versioned.py +++ b/tests/integration/files/file/base/_modules/depends_versioned.py @@ -1,3 +1 @@ -# -*- coding: utf-8 -*- - __version__ = 1.8 diff --git a/tests/integration/files/file/base/_modules/depends_versionless.py b/tests/integration/files/file/base/_modules/depends_versionless.py index 59bd7b845e4..2ae28399f5f 100644 --- a/tests/integration/files/file/base/_modules/depends_versionless.py +++ b/tests/integration/files/file/base/_modules/depends_versionless.py @@ -1,3 +1 @@ -# -*- coding: utf-8 -*- - pass diff --git a/tests/integration/files/file/base/_modules/override_test.py b/tests/integration/files/file/base/_modules/override_test.py index e688608de71..7b08dc7fe5a 100644 --- a/tests/integration/files/file/base/_modules/override_test.py +++ b/tests/integration/files/file/base/_modules/override_test.py @@ -1,8 +1,6 @@ -# -*- coding: utf-8 -*- """ Module for running arbitrary tests """ -from __future__ import absolute_import __virtualname__ = "test" diff --git a/tests/integration/files/file/base/_modules/runtests_decorators.py b/tests/integration/files/file/base/_modules/runtests_decorators.py index 164f8f457da..fdb4528e643 100644 --- a/tests/integration/files/file/base/_modules/runtests_decorators.py +++ b/tests/integration/files/file/base/_modules/runtests_decorators.py @@ -1,12 +1,6 @@ -# -*- coding: utf-8 -*- - -# Import Python libs -from __future__ import absolute_import - import os import time -# Import Salt libs import salt.utils.decorators from tests.support.runtests import RUNTIME_VARS @@ -16,9 +10,9 @@ EXIT_CODE_CMD = os.path.join(RUNTIME_VARS.BASE_FILES, "exit_code.cmd") def _exit_code(code): if os.name == "nt": - return "cmd /c {0} {1}".format(EXIT_CODE_CMD, code) + return "cmd /c {} {}".format(EXIT_CODE_CMD, code) else: - return "/usr/bin/env sh {0} {1}".format(EXIT_CODE_SH, code) + return "/usr/bin/env sh {} {}".format(EXIT_CODE_SH, code) def _fallbackfunc(): diff --git a/tests/integration/files/file/base/_modules/salttest.py b/tests/integration/files/file/base/_modules/salttest.py index 5cb0b1aab97..273cd25f668 100644 --- a/tests/integration/files/file/base/_modules/salttest.py +++ b/tests/integration/files/file/base/_modules/salttest.py @@ -1,11 +1,7 @@ -# -*- coding: utf-8 -*- """ Module for running arbitrary tests """ -# Import Python libs -from __future__ import absolute_import - def jinja_error(): """ diff --git a/tests/integration/files/file/base/_runners/runtests_helpers.py b/tests/integration/files/file/base/_runners/runtests_helpers.py index 3c4cf3cfdd8..3bc8e587aba 100644 --- a/tests/integration/files/file/base/_runners/runtests_helpers.py +++ b/tests/integration/files/file/base/_runners/runtests_helpers.py @@ -1,11 +1,7 @@ -# -*- coding: utf-8 -*- """ Runner functions for integration tests """ -# Import python libs -from __future__ import absolute_import - def failure(): __context__["retcode"] = 1 diff --git a/tests/integration/files/file/base/_states/salttest.py b/tests/integration/files/file/base/_states/salttest.py index 766d76a9ced..596e7121315 100644 --- a/tests/integration/files/file/base/_states/salttest.py +++ b/tests/integration/files/file/base/_states/salttest.py @@ -1,7 +1,5 @@ #!/usr/bin/env python -# -*- coding: utf-8 -*- -from __future__ import absolute_import __docformat__ = "restructuredtext en" diff --git a/tests/integration/files/file/base/_wheel/runtests_helpers.py b/tests/integration/files/file/base/_wheel/runtests_helpers.py index 3fc7c47a3fd..21fba9648f1 100644 --- a/tests/integration/files/file/base/_wheel/runtests_helpers.py +++ b/tests/integration/files/file/base/_wheel/runtests_helpers.py @@ -1,11 +1,7 @@ -# -*- coding: utf-8 -*- """ Wheel functions for integration tests """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals - def failure(): __context__["retcode"] = 1 diff --git a/tests/integration/files/file/base/script.py b/tests/integration/files/file/base/script.py index 0dbde454780..d1b98c720e4 100644 --- a/tests/integration/files/file/base/script.py +++ b/tests/integration/files/file/base/script.py @@ -1,7 +1,5 @@ #!/usr/bin/env python -# -*- coding: utf-8 -*- -from __future__ import absolute_import import sys diff --git a/tests/integration/files/returners/noop_returner.py b/tests/integration/files/returners/noop_returner.py index 4f09ca9e9cb..0201e5076b9 100644 --- a/tests/integration/files/returners/noop_returner.py +++ b/tests/integration/files/returners/noop_returner.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ noop_returner ~~~~~~~~~~~~~ @@ -6,12 +5,9 @@ noop_returner A returner that does nothing which is used to test the salt-master `event_return` functionality """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import logging -# Import Salt libs import salt.utils.jid log = logging.getLogger(__name__) diff --git a/tests/integration/fileserver/__init__.py b/tests/integration/fileserver/__init__.py index 40a96afc6ff..e69de29bb2d 100644 --- a/tests/integration/fileserver/__init__.py +++ b/tests/integration/fileserver/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/tests/integration/grains/__init__.py b/tests/integration/grains/__init__.py index 40a96afc6ff..e69de29bb2d 100644 --- a/tests/integration/grains/__init__.py +++ b/tests/integration/grains/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/tests/integration/loader/__init__.py b/tests/integration/loader/__init__.py index 40a96afc6ff..e69de29bb2d 100644 --- a/tests/integration/loader/__init__.py +++ b/tests/integration/loader/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/tests/integration/master/__init__.py b/tests/integration/master/__init__.py index 40a96afc6ff..e69de29bb2d 100644 --- a/tests/integration/master/__init__.py +++ b/tests/integration/master/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/tests/integration/minion/__init__.py b/tests/integration/minion/__init__.py index 40a96afc6ff..e69de29bb2d 100644 --- a/tests/integration/minion/__init__.py +++ b/tests/integration/minion/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/tests/integration/minion/test_minion_cache.py b/tests/integration/minion/test_minion_cache.py index 4009a2ece96..28120906e16 100644 --- a/tests/integration/minion/test_minion_cache.py +++ b/tests/integration/minion/test_minion_cache.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, unicode_literals - import os import salt.loader diff --git a/tests/integration/modules/__init__.py b/tests/integration/modules/__init__.py index 40a96afc6ff..e69de29bb2d 100644 --- a/tests/integration/modules/__init__.py +++ b/tests/integration/modules/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/tests/integration/modules/test_boto_iam.py b/tests/integration/modules/test_boto_iam.py index 340aab4e335..f0119aecbfc 100644 --- a/tests/integration/modules/test_boto_iam.py +++ b/tests/integration/modules/test_boto_iam.py @@ -1,16 +1,11 @@ -# -*- coding: utf-8 -*- """ Validate the boto_iam module """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals -# Import Salt Testing libs from tests.support.case import ModuleCase from tests.support.unit import skipIf -# Import 3rd-party libs try: import boto diff --git a/tests/integration/modules/test_boto_sns.py b/tests/integration/modules/test_boto_sns.py index 4a997c9d906..d45614a9b31 100644 --- a/tests/integration/modules/test_boto_sns.py +++ b/tests/integration/modules/test_boto_sns.py @@ -1,18 +1,13 @@ -# -*- coding: utf-8 -*- """ Validate the boto_sns module """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import re -# Import Salt Testing libs from tests.support.case import ModuleCase from tests.support.unit import skipIf -# Import 3rd-party libs try: import boto @@ -104,7 +99,7 @@ class BotoSNSTest(ModuleCase): ) def _get_arn(self, name): - return "arn:aws:sns:us-east-1:{0}:{1}".format(self.account_id, name) + return "arn:aws:sns:us-east-1:{}:{}".format(self.account_id, name) @property def account_id(self): diff --git a/tests/integration/modules/test_gentoolkitmod.py b/tests/integration/modules/test_gentoolkitmod.py index 920c4bc7ad0..a32615cf0ed 100644 --- a/tests/integration/modules/test_gentoolkitmod.py +++ b/tests/integration/modules/test_gentoolkitmod.py @@ -1,7 +1,3 @@ -# -*- coding: utf-8 -*- - -from __future__ import absolute_import, print_function, unicode_literals - import pytest from tests.support.case import ModuleCase @@ -12,7 +8,7 @@ class GentoolkitModuleTest(ModuleCase): """ Set up test environment """ - super(GentoolkitModuleTest, self).setUp() + super().setUp() ret_grain = self.run_function("grains.item", ["os"]) if ret_grain["os"] not in "Gentoo": self.skipTest("For Gentoo only") diff --git a/tests/integration/modules/test_supervisord.py b/tests/integration/modules/test_supervisord.py index 245b92c9e3d..c4edeea487b 100644 --- a/tests/integration/modules/test_supervisord.py +++ b/tests/integration/modules/test_supervisord.py @@ -1,21 +1,13 @@ -# -*- coding: utf-8 -*- - # Import python -from __future__ import absolute_import, print_function, unicode_literals import os import subprocess import time -# Import salt libs import salt.utils.path - -# Import 3rd-party libs from salt.ext import six from salt.modules.virtualenv_mod import KNOWN_BINARY_NAMES from tests.support.case import ModuleCase - -# Import Salt Testing libs from tests.support.runtests import RUNTIME_VARS from tests.support.unit import skipIf @@ -31,7 +23,7 @@ class SupervisordModuleTest(ModuleCase): """ def setUp(self): - super(SupervisordModuleTest, self).setUp() + super().setUp() self.venv_test_dir = os.path.join(RUNTIME_VARS.TMP, "supervisortests") self.venv_dir = os.path.join(self.venv_test_dir, "venv") diff --git a/tests/integration/modules/test_sysctl.py b/tests/integration/modules/test_sysctl.py index 3d5b7945d59..30475aae8ea 100644 --- a/tests/integration/modules/test_sysctl.py +++ b/tests/integration/modules/test_sysctl.py @@ -1,18 +1,12 @@ -# -*- coding: utf-8 -*- - -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals - import sys -# Import Salt Testing libs from tests.support.case import ModuleCase from tests.support.unit import skipIf class SysctlModuleTest(ModuleCase): def setUp(self): - super(SysctlModuleTest, self).setUp() + super().setUp() ret = self.run_function("cmd.has_exec", ["sysctl"]) if not ret: self.skipTest("sysctl not found") diff --git a/tests/integration/modules/test_tls.py b/tests/integration/modules/test_tls.py index 8ef8d2944ca..76442bd4bc5 100644 --- a/tests/integration/modules/test_tls.py +++ b/tests/integration/modules/test_tls.py @@ -1,10 +1,8 @@ -# -*- coding: utf-8 -*- """ :codeauthor: Wayne Werner """ # Import the future -from __future__ import absolute_import, print_function, unicode_literals import os import tempfile diff --git a/tests/integration/modules/test_win_ip.py b/tests/integration/modules/test_win_ip.py index 251b1bcc222..8402acc9d10 100644 --- a/tests/integration/modules/test_win_ip.py +++ b/tests/integration/modules/test_win_ip.py @@ -1,14 +1,6 @@ -# -*- coding: utf-8 -*- - -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - import re -# Import Salt libs import salt.utils.platform - -# Import Salt Testing libs from tests.support.case import ModuleCase from tests.support.unit import skipIf diff --git a/tests/integration/netapi/__init__.py b/tests/integration/netapi/__init__.py index 40a96afc6ff..e69de29bb2d 100644 --- a/tests/integration/netapi/__init__.py +++ b/tests/integration/netapi/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/tests/integration/netapi/rest_tornado/__init__.py b/tests/integration/netapi/rest_tornado/__init__.py index 40a96afc6ff..e69de29bb2d 100644 --- a/tests/integration/netapi/rest_tornado/__init__.py +++ b/tests/integration/netapi/rest_tornado/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/tests/integration/output/__init__.py b/tests/integration/output/__init__.py index 40a96afc6ff..e69de29bb2d 100644 --- a/tests/integration/output/__init__.py +++ b/tests/integration/output/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/tests/integration/pillar/__init__.py b/tests/integration/pillar/__init__.py index 40a96afc6ff..e69de29bb2d 100644 --- a/tests/integration/pillar/__init__.py +++ b/tests/integration/pillar/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/tests/integration/renderers/__init__.py b/tests/integration/renderers/__init__.py index 40a96afc6ff..e69de29bb2d 100644 --- a/tests/integration/renderers/__init__.py +++ b/tests/integration/renderers/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/tests/integration/returners/__init__.py b/tests/integration/returners/__init__.py index 40a96afc6ff..e69de29bb2d 100644 --- a/tests/integration/returners/__init__.py +++ b/tests/integration/returners/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/tests/integration/returners/test_appoptics_return.py b/tests/integration/returners/test_appoptics_return.py index 6f9316d7bee..87f333028d6 100644 --- a/tests/integration/returners/test_appoptics_return.py +++ b/tests/integration/returners/test_appoptics_return.py @@ -1,16 +1,10 @@ -# -*- coding: utf-8 -*- """ Tests for the appoptics returner """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import logging -# Import salt libs from salt.returners import appoptics_return - -# Import Salt Testing libs from tests.support.case import ShellCase log = logging.getLogger(__name__) diff --git a/tests/integration/returners/test_librato_return.py b/tests/integration/returners/test_librato_return.py index 5a35ad12e6f..ecabc00dc82 100644 --- a/tests/integration/returners/test_librato_return.py +++ b/tests/integration/returners/test_librato_return.py @@ -1,8 +1,6 @@ -# -*- coding: utf-8 -*- """ Tests for the librato returner """ -from __future__ import absolute_import, print_function, unicode_literals import logging diff --git a/tests/integration/runners/__init__.py b/tests/integration/runners/__init__.py index 40a96afc6ff..e69de29bb2d 100644 --- a/tests/integration/runners/__init__.py +++ b/tests/integration/runners/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/tests/integration/sdb/__init__.py b/tests/integration/sdb/__init__.py index 40a96afc6ff..e69de29bb2d 100644 --- a/tests/integration/sdb/__init__.py +++ b/tests/integration/sdb/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/tests/integration/spm/__init__.py b/tests/integration/spm/__init__.py index 40a96afc6ff..e69de29bb2d 100644 --- a/tests/integration/spm/__init__.py +++ b/tests/integration/spm/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/tests/integration/ssh/__init__.py b/tests/integration/ssh/__init__.py index 40a96afc6ff..e69de29bb2d 100644 --- a/tests/integration/ssh/__init__.py +++ b/tests/integration/ssh/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/tests/integration/states/__init__.py b/tests/integration/states/__init__.py index 40a96afc6ff..e69de29bb2d 100644 --- a/tests/integration/states/__init__.py +++ b/tests/integration/states/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/tests/integration/states/test_boto_sns.py b/tests/integration/states/test_boto_sns.py index ef8103bea42..4d733361534 100644 --- a/tests/integration/states/test_boto_sns.py +++ b/tests/integration/states/test_boto_sns.py @@ -1,19 +1,14 @@ -# -*- coding: utf-8 -*- """ Tests for the boto_sns state """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import re -# Import Salt Testing libs from tests.support.case import ModuleCase from tests.support.mixins import SaltReturnAssertsMixin from tests.support.unit import skipIf -# Import 3rd-party libs try: import boto @@ -50,7 +45,7 @@ class BotoSNSTest(ModuleCase, SaltReturnAssertsMixin): self.assertSaltTrueReturn(ret) self.assertInSaltReturn(self.topic_name, ret, "name") self.assertInSaltComment( - "AWS SNS topic {0} created.".format(self.topic_name), ret + "AWS SNS topic {} created.".format(self.topic_name), ret ) self.assertSaltStateChangesEqual( ret, {"old": None, "new": {"topic": self.topic_name, "subscriptions": []}} @@ -92,13 +87,13 @@ class BotoSNSTest(ModuleCase, SaltReturnAssertsMixin): }, ) self.assertInSaltComment( - "AWS SNS subscription https:https://www.example.com/sns/endpoint set on topic {0}.".format( + "AWS SNS subscription https:https://www.example.com/sns/endpoint set on topic {}.".format( self.topic_name ), ret, ) self.assertInSaltComment( - "AWS SNS subscription https:https://www.example.com/sns/endpoint-2 set on topic {0}.".format( + "AWS SNS subscription https:https://www.example.com/sns/endpoint-2 set on topic {}.".format( self.topic_name ), ret, @@ -138,10 +133,10 @@ class BotoSNSTest(ModuleCase, SaltReturnAssertsMixin): self.assertSaltTrueReturn(ret) self.assertInSaltReturn(self.topic_name, ret, "name") self.assertInSaltComment( - "AWS SNS topic {0} present.".format(self.topic_name), ret + "AWS SNS topic {} present.".format(self.topic_name), ret ) self.assertInSaltComment( - "AWS SNS subscription https:https://www.example.com/sns/endpoint already set on topic {0}.".format( + "AWS SNS subscription https:https://www.example.com/sns/endpoint already set on topic {}.".format( self.topic_name ), ret, @@ -176,7 +171,7 @@ class BotoSNSTest(ModuleCase, SaltReturnAssertsMixin): }, ) self.assertInSaltComment( - "AWS SNS subscription https:https://www.example.com/sns/endpoint set on topic {0}.".format( + "AWS SNS subscription https:https://www.example.com/sns/endpoint set on topic {}.".format( self.topic_name ), ret, @@ -224,7 +219,7 @@ class BotoSNSTest(ModuleCase, SaltReturnAssertsMixin): }, ) self.assertInSaltComment( - "AWS SNS subscription https:https://www.example.com/sns/endpoint-2 set on topic {0}.".format( + "AWS SNS subscription https:https://www.example.com/sns/endpoint-2 set on topic {}.".format( self.topic_name ), ret, @@ -244,7 +239,7 @@ class BotoSNSTest(ModuleCase, SaltReturnAssertsMixin): self.assertSaltNoneReturn(ret) self.assertInSaltReturn(self.topic_name, ret, "name") self.assertInSaltComment( - "AWS SNS topic {0} is set to be created.".format(self.topic_name), ret + "AWS SNS topic {} is set to be created.".format(self.topic_name), ret ) self.assertSaltStateChangesEqual(ret, {}) ret = self.run_function("boto_sns.exists", name=self.topic_name) @@ -266,7 +261,7 @@ class BotoSNSTest(ModuleCase, SaltReturnAssertsMixin): self.assertSaltNoneReturn(ret) self.assertSaltStateChangesEqual(ret, {}) self.assertInSaltComment( - "AWS SNS subscription https:https://www.example.com/sns/endpoint to be set on topic {0}.".format( + "AWS SNS subscription https:https://www.example.com/sns/endpoint to be set on topic {}.".format( self.topic_name ), ret, @@ -281,7 +276,7 @@ class BotoSNSTest(ModuleCase, SaltReturnAssertsMixin): self.assertSaltTrueReturn(ret) self.assertInSaltReturn(self.topic_name, ret, "name") self.assertInSaltComment( - "AWS SNS topic {0} does not exist.".format(self.topic_name), ret + "AWS SNS topic {} does not exist.".format(self.topic_name), ret ) self.assertSaltStateChangesEqual(ret, {}) @@ -291,7 +286,7 @@ class BotoSNSTest(ModuleCase, SaltReturnAssertsMixin): self.assertSaltTrueReturn(ret) self.assertInSaltReturn(self.topic_name, ret, "name") self.assertInSaltComment( - "AWS SNS topic {0} does not exist.".format(self.topic_name), ret + "AWS SNS topic {} does not exist.".format(self.topic_name), ret ) self.assertSaltStateChangesEqual( ret, {"new": None, "old": {"topic": self.topic_name}} @@ -303,7 +298,7 @@ class BotoSNSTest(ModuleCase, SaltReturnAssertsMixin): self.assertSaltNoneReturn(ret) self.assertInSaltReturn(self.topic_name, ret, "name") self.assertInSaltComment( - "AWS SNS topic {0} is set to be removed.".format(self.topic_name), ret + "AWS SNS topic {} is set to be removed.".format(self.topic_name), ret ) self.assertSaltStateChangesEqual(ret, {}) ret = self.run_function("boto_sns.exists", name=self.topic_name) @@ -320,7 +315,7 @@ class BotoSNSTest(ModuleCase, SaltReturnAssertsMixin): except AssertionError: continue raise self.failureException( - "Subscription {0} not found in topic {1} subscriptions: {2}".format( + "Subscription {} not found in topic {} subscriptions: {}".format( subscription, topic_name, ret ) ) diff --git a/tests/integration/states/test_compiler.py b/tests/integration/states/test_compiler.py index 4fda01033a3..f0544c2310c 100644 --- a/tests/integration/states/test_compiler.py +++ b/tests/integration/states/test_compiler.py @@ -1,18 +1,11 @@ -# -*- coding: utf-8 -*- """ tests for host state """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals -# Import Salt libs import salt.utils.platform - -# Import Salt Testing libs from tests.support.case import ModuleCase -# Import 3rd-Party libs HAS_LSB_RELEASE = True try: import lsb_release diff --git a/tests/integration/states/test_handle_iorder.py b/tests/integration/states/test_handle_iorder.py index d2c1bcaa8c0..39a5e88fe32 100644 --- a/tests/integration/states/test_handle_iorder.py +++ b/tests/integration/states/test_handle_iorder.py @@ -1,12 +1,8 @@ -# -*- coding: utf-8 -*- """ tests for host state """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals -# Import Salt Testing libs from tests.support.case import ModuleCase diff --git a/tests/integration/states/test_supervisord.py b/tests/integration/states/test_supervisord.py index 183f726a598..ce6fe68a67d 100644 --- a/tests/integration/states/test_supervisord.py +++ b/tests/integration/states/test_supervisord.py @@ -1,31 +1,21 @@ -# -*- coding: utf-8 -*- - """ Tests for the supervisord state """ # Import python lins -from __future__ import absolute_import, print_function, unicode_literals import os import subprocess import time -# Import salt libs import salt.utils.path - -# Import 3rd-party libs -from salt.ext import six from salt.modules.virtualenv_mod import KNOWN_BINARY_NAMES from tests.support.case import ModuleCase from tests.support.mixins import SaltReturnAssertsMixin - -# Import Salt Testing libs from tests.support.runtests import RUNTIME_VARS from tests.support.unit import skipIf -@skipIf(six.PY3, "supervisor does not work under python 3") @skipIf( salt.utils.path.which_bin(KNOWN_BINARY_NAMES) is None, "virtualenv not installed" ) @@ -36,7 +26,7 @@ class SupervisordTest(ModuleCase, SaltReturnAssertsMixin): """ def setUp(self): - super(SupervisordTest, self).setUp() + super().setUp() self.venv_test_dir = os.path.join(RUNTIME_VARS.TMP, "supervisortests") self.venv_dir = os.path.join(self.venv_test_dir, "venv") diff --git a/tests/integration/utils/__init__.py b/tests/integration/utils/__init__.py index a656be2a221..39529355b9b 100644 --- a/tests/integration/utils/__init__.py +++ b/tests/integration/utils/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Some utils functions to be used throughout the integration test files. """ diff --git a/tests/kitchen/__init__.py b/tests/kitchen/__init__.py index 40a96afc6ff..e69de29bb2d 100644 --- a/tests/kitchen/__init__.py +++ b/tests/kitchen/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/tests/kitchen/test_kitchen.py b/tests/kitchen/test_kitchen.py index d0e57be211d..2815a4ac159 100644 --- a/tests/kitchen/test_kitchen.py +++ b/tests/kitchen/test_kitchen.py @@ -1,11 +1,9 @@ -# -*- coding: utf-8 -*- """ Test wrapper for running all KitchenSalt tests All directories in 'tests/kitchen/' will be treated as a separate test under the KitchenTestCase. """ -from __future__ import absolute_import import os @@ -35,7 +33,7 @@ class KitchenTestCase(TestCase): cls.env = { "KITCHEN_YAML": os.path.join(CURRENT_DIR, ".kitchen.yml"), "SALT_SDIST_PATH": os.path.join( - cls.topdir, "dist", "salt-{0}.tar.gz".format(setup.__version__) + cls.topdir, "dist", "salt-{}.tar.gz".format(setup.__version__) ), } @@ -60,7 +58,7 @@ def func_builder(testdir): if "TESTS_XML_OUTPUT_DIR" in os.environ: self.env[ "TESTS_JUNIT_XML_PATH" - ] = "{0}/kitchen.tests.{1}.$KITCHEN_SUITE.$KITCHEN_PLATFORM.xml".format( + ] = "{}/kitchen.tests.{}.$KITCHEN_SUITE.$KITCHEN_PLATFORM.xml".format( os.environ.get("TESTS_XML_OUTPUT_DIR"), self.testdir, ) self.assertEqual( @@ -86,4 +84,4 @@ def func_builder(testdir): for testdir in os.listdir(os.path.join(CURRENT_DIR, "tests")): - setattr(KitchenTestCase, "test_kitchen_{0}".format(testdir), func_builder(testdir)) + setattr(KitchenTestCase, "test_kitchen_{}".format(testdir), func_builder(testdir)) diff --git a/tests/kitchen/tests/wordpress/tests/conftest.py b/tests/kitchen/tests/wordpress/tests/conftest.py index c94f18d8fb7..e70050c1187 100644 --- a/tests/kitchen/tests/wordpress/tests/conftest.py +++ b/tests/kitchen/tests/wordpress/tests/conftest.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import import functools import os import pytest @@ -26,7 +24,7 @@ def salt(): if 'windows' in os.environ.get('KITCHEN_INSTANCE'): tmpconf = r'c:\Users\vagrant\AppData\Local\Temp\kitchen\etc\salt' else: - test_host.run('sudo chown -R {0} /tmp/kitchen'.format(os.environ.get('KITCHEN_USERNAME'))) + test_host.run('sudo chown -R {} /tmp/kitchen'.format(os.environ.get('KITCHEN_USERNAME'))) tmpconf = '/tmp/kitchen/etc/salt' return functools.partial(test_host.salt, config=tmpconf) diff --git a/tests/kitchen/tests/wordpress/tests/salt/test_wordpress.py b/tests/kitchen/tests/wordpress/tests/salt/test_wordpress.py index 9c24718250d..6aa12304584 100644 --- a/tests/kitchen/tests/wordpress/tests/salt/test_wordpress.py +++ b/tests/kitchen/tests/wordpress/tests/salt/test_wordpress.py @@ -5,5 +5,5 @@ def test_server(host_ip, http_port): ''' Test that wordpress was setup on the minion correctly and returns a 200 after being installed ''' - resp = requests.get('http://{0}:{1}'.format(host_ip, http_port), headers={'Host': 'blog.manfred.io'}) + resp = requests.get('http://{}:{}'.format(host_ip, http_port), headers={'Host': 'blog.manfred.io'}) assert resp.status_code == 200 diff --git a/tests/minionswarm.py b/tests/minionswarm.py index 2feee0d5ff6..055873517e3 100644 --- a/tests/minionswarm.py +++ b/tests/minionswarm.py @@ -1,13 +1,10 @@ #!/usr/bin/env python -# -*- coding: utf-8 -*- """ The minionswarm script will start a group of salt minions with different ids on a single system to test scale capabilities """ # pylint: disable=resource-leakage -# Import Python Libs -from __future__ import absolute_import, print_function import hashlib import optparse @@ -21,16 +18,11 @@ import tempfile import time import uuid -# Import salt libs import salt import salt.utils.files import salt.utils.yaml import tests.support.runtests -# Import third party libs -from salt.ext import six -from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin - OSES = [ "Arch", "Ubuntu", @@ -174,13 +166,13 @@ def parse(): opts = {} - for key, val in six.iteritems(options.__dict__): + for key, val in options.__dict__.items(): opts[key] = val return opts -class Swarm(object): +class Swarm: """ Create a swarm of minions """ @@ -217,7 +209,7 @@ class Swarm(object): if not os.path.exists(path): os.makedirs(path) - print("Creating shared pki keys for the swarm on: {0}".format(path)) + print("Creating shared pki keys for the swarm on: {}".format(path)) subprocess.call( "salt-key -c {0} --gen-keys minion --gen-keys-dir {0} " "--log-file {1} --user {2}".format( @@ -239,7 +231,7 @@ class Swarm(object): minions.start_minions() print("Starting minions...") # self.start_minions() - print("All {0} minions have started.".format(self.opts["minions"])) + print("All {} minions have started.".format(self.opts["minions"])) print("Waiting for CTRL-C to properly shutdown minions...") while True: try: @@ -268,7 +260,7 @@ class Swarm(object): Clean up the config files """ for path in self.confs: - pidfile = "{0}.pid".format(path) + pidfile = "{}.pid".format(path) try: try: with salt.utils.files.fopen(pidfile) as fp_: @@ -280,7 +272,7 @@ class Swarm(object): os.remove(pidfile) if not self.opts["no_clean"]: shutil.rmtree(path) - except (OSError, IOError): + except OSError: pass @@ -295,9 +287,7 @@ class MinionSwarm(Swarm): """ self.prep_configs() for path in self.confs: - cmd = "salt-minion -c {0} --pid-file {1}".format( - path, "{0}.pid".format(path) - ) + cmd = "salt-minion -c {} --pid-file {}".format(path, "{}.pid".format(path)) if self.opts["foreground"]: cmd += " -l debug &" else: @@ -314,7 +304,7 @@ class MinionSwarm(Swarm): spath = os.path.join(self.opts["config_dir"], "minion") with salt.utils.files.fopen(spath) as conf: data = salt.utils.yaml.safe_load(conf) or {} - minion_id = "{0}-{1}".format(self.opts["name"], str(idx).zfill(self.zfill)) + minion_id = "{}-{}".format(self.opts["name"], str(idx).zfill(self.zfill)) dpath = os.path.join(self.swarm_root, minion_id) if not os.path.exists(dpath): @@ -382,7 +372,7 @@ class MasterSwarm(Swarm): """ def __init__(self, opts): - super(MasterSwarm, self).__init__(opts) + super().__init__(opts) self.conf = os.path.join(self.swarm_root, "master") def start(self): @@ -402,8 +392,8 @@ class MasterSwarm(Swarm): """ Do the master start """ - cmd = "salt-master -c {0} --pid-file {1}".format( - self.conf, "{0}.pid".format(self.conf) + cmd = "salt-master -c {} --pid-file {}".format( + self.conf, "{}.pid".format(self.conf) ) if self.opts["foreground"]: cmd += " -l debug &" diff --git a/tests/modparser.py b/tests/modparser.py index 081b0d29b79..978b3ad7836 100644 --- a/tests/modparser.py +++ b/tests/modparser.py @@ -1,7 +1,5 @@ -# -*- coding: utf-8 -*- #!/usr/bin/env python2 -from __future__ import absolute_import, print_function import modulefinder import os @@ -48,7 +46,7 @@ def mod_data(opts, full): try: finder.load_file(full) except ImportError as exc: - print("ImportError - {0} (Reason: {1})".format(full, exc), file=sys.stderr) + print("ImportError - {} (Reason: {})".format(full, exc), file=sys.stderr) return ret for name, mod in finder.modules.items(): basemod = name.split(".")[0] diff --git a/tests/packdump.py b/tests/packdump.py index eaff6bd8c5b..d25b5454e73 100644 --- a/tests/packdump.py +++ b/tests/packdump.py @@ -1,16 +1,12 @@ -# -*- coding: utf-8 -*- """ Simple script to dump the contents of msgpack files to the terminal """ # pylint: disable=resource-leakage -# Import python libs -from __future__ import absolute_import, print_function import os import pprint import sys -# Import Salt libs import salt.utils.msgpack diff --git a/tests/pytests/__init__.py b/tests/pytests/__init__.py index 40a96afc6ff..e69de29bb2d 100644 --- a/tests/pytests/__init__.py +++ b/tests/pytests/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/tests/pytests/integration/__init__.py b/tests/pytests/integration/__init__.py index 40a96afc6ff..e69de29bb2d 100644 --- a/tests/pytests/integration/__init__.py +++ b/tests/pytests/integration/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/tests/pytests/unit/__init__.py b/tests/pytests/unit/__init__.py index 40a96afc6ff..e69de29bb2d 100644 --- a/tests/pytests/unit/__init__.py +++ b/tests/pytests/unit/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/tests/pytests/unit/beacons/__init__.py b/tests/pytests/unit/beacons/__init__.py index 40a96afc6ff..e69de29bb2d 100644 --- a/tests/pytests/unit/beacons/__init__.py +++ b/tests/pytests/unit/beacons/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/tests/pytests/unit/modules/__init__.py b/tests/pytests/unit/modules/__init__.py index 40a96afc6ff..e69de29bb2d 100644 --- a/tests/pytests/unit/modules/__init__.py +++ b/tests/pytests/unit/modules/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/tests/pytests/unit/states/__init__.py b/tests/pytests/unit/states/__init__.py index 40a96afc6ff..e69de29bb2d 100644 --- a/tests/pytests/unit/states/__init__.py +++ b/tests/pytests/unit/states/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/tests/pytests/unit/test_pytest_pass_fail.py b/tests/pytests/unit/test_pytest_pass_fail.py index 729c5e2a35b..ff347484d6b 100644 --- a/tests/pytests/unit/test_pytest_pass_fail.py +++ b/tests/pytests/unit/test_pytest_pass_fail.py @@ -1,11 +1,9 @@ -# -*- coding: utf-8 -*- """ tests.unit.test_pytest_pass_fail ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Some tests to make sure our pytest usage doesn't break regular pytest behviour """ -from __future__ import absolute_import import pytest diff --git a/tests/pytests/unit/utils/test_stringutils.py b/tests/pytests/unit/utils/test_stringutils.py index b07939a52bf..fce145e8544 100644 --- a/tests/pytests/unit/utils/test_stringutils.py +++ b/tests/pytests/unit/utils/test_stringutils.py @@ -2,13 +2,13 @@ Tests for stringutils utility file. """ +import builtins import re import sys import textwrap import pytest import salt.utils.stringutils -from salt.ext.six.moves import builtins, range # pylint: disable=redefined-builtin from tests.support.mock import patch from tests.support.unit import LOREM_IPSUM diff --git a/tests/salt-tcpdump.py b/tests/salt-tcpdump.py index bfd48e1a7dd..9b37c5b64b1 100644 --- a/tests/salt-tcpdump.py +++ b/tests/salt-tcpdump.py @@ -1,5 +1,4 @@ #!/usr/bin/python -# -*- coding: utf-8 -*- """ Author: Volker Schwicking, vs@heg.com @@ -34,8 +33,6 @@ For Port 4506 tcpdump "tcp[tcpflags] & tcp-syn != 0" and port 4506 and "tcp[tcpflags] & tcp-ack == 0" """ # pylint: disable=resource-leakage -# Import Python Libs -from __future__ import absolute_import, print_function import argparse # pylint: disable=minimum-python-version import socket @@ -46,7 +43,7 @@ from struct import unpack import pcapy # pylint: disable=import-error,3rd-party-module-not-gated -class ArgParser(object): +class ArgParser: """ Simple Argument-Parser class """ @@ -99,7 +96,7 @@ class ArgParser(object): return self.main_parser.parse_args() -class PCAPParser(object): +class PCAPParser: """ parses a network packet on given device and returns source, target, source_port and dest_port @@ -226,7 +223,7 @@ class PCAPParser(object): return source_port, dest_port, tcp_flags, data -class SaltNetstat(object): +class SaltNetstat: """ Reads /proc/net/tcp and returns all connections """ @@ -235,7 +232,7 @@ class SaltNetstat(object): """ Read the table of tcp connections & remove header """ - with open("/proc/net/tcp", "r") as tcp_f: + with open("/proc/net/tcp") as tcp_f: content = tcp_f.readlines() content.pop(0) return content @@ -363,7 +360,7 @@ def main(): # the ports we want to monitor ports = [4505, 4506] - print("Sniffing device {0}".format(args["iface"])) + print("Sniffing device {}".format(args["iface"])) stat = { "4506/new": 0, @@ -379,12 +376,12 @@ def main(): if args["only_ip"]: print( "IPs making new connections " - "(ports:{0}, interval:{1})".format(ports, args["ival"]) + "(ports:{}, interval:{})".format(ports, args["ival"]) ) else: print( "Salt-Master Network Status " - "(ports:{0}, interval:{1})".format(ports, args["ival"]) + "(ports:{}, interval:{})".format(ports, args["ival"]) ) try: while 1: @@ -425,17 +422,17 @@ def main(): # prevent printing within the same second if r_time != s_time: if args["only_ip"]: - msg = "IPs/4505: {0}, IPs/4506: {1}".format( + msg = "IPs/4505: {}, IPs/4506: {}".format( len(ips_auth), len(ips_push) ) else: - msg = "4505=>[ est: {0}, ".format(stat["4505/est"]) - msg += "new: {0}/s, ".format(stat["4505/new"] / args["ival"]) - msg += "fin: {0}/s ] ".format(stat["4505/fin"] / args["ival"]) + msg = "4505=>[ est: {}, ".format(stat["4505/est"]) + msg += "new: {}/s, ".format(stat["4505/new"] / args["ival"]) + msg += "fin: {}/s ] ".format(stat["4505/fin"] / args["ival"]) - msg += " 4506=>[ est: {0}, ".format(stat["4506/est"]) - msg += "new: {0}/s, ".format(stat["4506/new"] / args["ival"]) - msg += "fin: {0}/s ]".format(stat["4506/fin"] / args["ival"]) + msg += " 4506=>[ est: {}, ".format(stat["4506/est"]) + msg += "new: {}/s, ".format(stat["4506/new"] / args["ival"]) + msg += "fin: {}/s ]".format(stat["4506/fin"] / args["ival"]) print(msg) diff --git a/tests/saltsh.py b/tests/saltsh.py index 91e0d7d8883..b88625c4379 100644 --- a/tests/saltsh.py +++ b/tests/saltsh.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -# -*- coding: utf-8 -*- '''\ Welcome to the Salt repl which exposes the execution environment of a minion in a pre-configured Python shell @@ -22,20 +21,16 @@ completion behavior can be customized via the ~/.inputrc file. ''' # pylint: disable=file-perms -# Import python libs -from __future__ import absolute_import import atexit +import builtins import os import pprint # pylint: disable=unused-import import readline import sys from code import InteractiveConsole -# Import 3rd party libs import jinja2 - -# Import salt libs import salt.client import salt.config import salt.loader @@ -46,7 +41,6 @@ import salt.runner # pylint: disable=unused-import # These are imported to be available in the spawned shell import salt.utils.yaml -from salt.ext.six.moves import builtins # pylint: disable=import-error # pylint: enable=unused-import diff --git a/tests/support/__init__.py b/tests/support/__init__.py index 40a96afc6ff..e69de29bb2d 100644 --- a/tests/support/__init__.py +++ b/tests/support/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/tests/support/copyartifacts.py b/tests/support/copyartifacts.py index bf6f315956e..790d4f0d7fb 100644 --- a/tests/support/copyartifacts.py +++ b/tests/support/copyartifacts.py @@ -1,8 +1,6 @@ -# -*- coding: utf-8 -*- """ Script for copying back xml junit files from tests """ -from __future__ import absolute_import, print_function import argparse # pylint: disable=minimum-python-version import os @@ -12,7 +10,7 @@ import paramiko import salt.utils.yaml -class DownloadArtifacts(object): +class DownloadArtifacts: def __init__(self, instance, artifacts): self.instance = instance self.artifacts = artifacts @@ -62,11 +60,11 @@ class DownloadArtifacts(object): self._do_download(remote, os.path.join(local, os.path.basename(remote))) def _do_download(self, remote, local): - print("Copying from {0} to {1}".format(remote, local)) + print("Copying from {} to {}".format(remote, local)) try: self.sftpclient.get(remote, local) - except IOError: - print("Failed to copy: {0}".format(remote)) + except OSError: + print("Failed to copy: {}".format(remote)) if __name__ == "__main__": diff --git a/tests/support/ext/__init__.py b/tests/support/ext/__init__.py index 40a96afc6ff..e69de29bb2d 100644 --- a/tests/support/ext/__init__.py +++ b/tests/support/ext/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/tests/support/ext/console.py b/tests/support/ext/console.py index 888f0521fcc..41e2dd466a0 100644 --- a/tests/support/ext/console.py +++ b/tests/support/ext/console.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # vim: sw=4 ts=4 fenc=utf-8 """ getTerminalSize() @@ -7,8 +6,6 @@ getTerminalSize() - taken from http://stackoverflow.com/questions/566746/how-to-get-console-window-width-in-python """ -# Import python libs -from __future__ import absolute_import, print_function import ctypes import fcntl @@ -118,4 +115,4 @@ def _getTerminalSize_linux(): if __name__ == "__main__": sizex, sizey = getTerminalSize() - print("width = {0} height = {1}".format(sizex, sizey)) + print("width = {} height = {}".format(sizex, sizey)) diff --git a/tests/support/generate-names-file-from-failed-test-reports.py b/tests/support/generate-names-file-from-failed-test-reports.py index 480485db074..3eef9c5b467 100644 --- a/tests/support/generate-names-file-from-failed-test-reports.py +++ b/tests/support/generate-names-file-from-failed-test-reports.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ tests.support.generate-from-names-from-failed-test-reports ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -7,7 +6,6 @@ PyTest's --last-failed where PyTest only runs last failed tests. """ # pylint: disable=resource-leakage -from __future__ import absolute_import, print_function, unicode_literals import argparse import glob diff --git a/tests/support/kernelpkg.py b/tests/support/kernelpkg.py index dba75613104..6f948c0eb48 100644 --- a/tests/support/kernelpkg.py +++ b/tests/support/kernelpkg.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ :synopsis: Base class for kernelpkg modules :platform: Linux @@ -7,7 +6,6 @@ """ # pylint: disable=invalid-name,no-member -from __future__ import absolute_import, print_function, unicode_literals # Salt testing libs try: @@ -17,7 +15,7 @@ except ImportError: pass -class KernelPkgTestCase(object): +class KernelPkgTestCase: """ Test cases shared by all kernelpkg virtual modules """ diff --git a/tests/support/mixins.py b/tests/support/mixins.py index 7f71b54f912..5c92bcd7867 100644 --- a/tests/support/mixins.py +++ b/tests/support/mixins.py @@ -15,6 +15,7 @@ import logging import multiprocessing import os import pprint +import queue import subprocess import tempfile import time @@ -30,9 +31,6 @@ import salt.utils.process import salt.utils.stringutils import salt.utils.yaml import salt.version -from salt.ext import six -from salt.ext.six.moves import zip -from salt.ext.six.moves.queue import Empty from salt.utils.immutabletypes import freeze from salt.utils.verify import verify_env from saltfactories.utils import random_string @@ -414,9 +412,9 @@ class LoaderModuleMockMixin(metaclass=_FixLoaderModuleMockMixinMroOrder): class XMLEqualityMixin: def assertEqualXML(self, e1, e2): - if six.PY3 and isinstance(e1, bytes): + if isinstance(e1, bytes): e1 = e1.decode("utf-8") - if six.PY3 and isinstance(e2, bytes): + if isinstance(e2, bytes): e2 = e2.decode("utf-8") if isinstance(e1, str): e1 = etree.XML(e1) @@ -655,7 +653,7 @@ class SaltMinionEventAssertsMixin: while True: try: event = self.q.get(False) - except Empty: + except queue.Empty: time.sleep(sleep_time) if time.time() - start >= timeout: break diff --git a/tests/support/pytest/__init__.py b/tests/support/pytest/__init__.py index 40a96afc6ff..e69de29bb2d 100644 --- a/tests/support/pytest/__init__.py +++ b/tests/support/pytest/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/tests/support/sminion.py b/tests/support/sminion.py index 286a9629f24..abf45fd7bde 100644 --- a/tests/support/sminion.py +++ b/tests/support/sminion.py @@ -1,11 +1,9 @@ -# -*- coding: utf-8 -*- """ tests.support.sminion ~~~~~~~~~~~~~~~~~~~~~ SMinion's support functions """ -from __future__ import absolute_import, print_function, unicode_literals import fnmatch import hashlib diff --git a/tests/support/win_installer.py b/tests/support/win_installer.py index 76619f05f5f..55feb13caa7 100644 --- a/tests/support/win_installer.py +++ b/tests/support/win_installer.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ :copyright: Copyright 2013-2017 by the SaltStack Team, see AUTHORS for more details. :license: Apache 2.0, see LICENSE for more details. @@ -9,7 +8,6 @@ Fetches the binary Windows installer """ -from __future__ import absolute_import import hashlib diff --git a/tests/support/xmlunit.py b/tests/support/xmlunit.py index ffc08bf4e50..d3c7a1a7c56 100644 --- a/tests/support/xmlunit.py +++ b/tests/support/xmlunit.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ :codeauthor: Pedro Algarvio (pedro@algarvio.me) :copyright: Copyright 2014 by the SaltStack Team, see AUTHORS for more details. @@ -12,8 +11,6 @@ """ # pylint: disable=wrong-import-order,wrong-import-position -# Import python libs -from __future__ import absolute_import import io import logging @@ -34,7 +31,7 @@ try: """ def __init__(self, first, second): - super(_DuplicateWriter, self).__init__() + super().__init__() self._first = first self._second = second @@ -96,7 +93,7 @@ try: except ImportError: HAS_XMLRUNNER = False - class XMLTestRunner(object): + class XMLTestRunner: """ This is a dumb class just so we don't break projects at import time """ diff --git a/tests/support/zfs.py b/tests/support/zfs.py index ae378ea0fdb..9fcdafc51d4 100644 --- a/tests/support/zfs.py +++ b/tests/support/zfs.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ tests.support.zfs ~~~~~~~~~~~~~~~~~ @@ -6,17 +5,12 @@ ZFS related unit test data structures """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals -# Import salt libs import salt.utils.zfs - -# Import Salt tests libs from tests.support.mock import MagicMock, patch -class ZFSMockData(object): +class ZFSMockData: def __init__(self): # property_map mocks self.pmap_exec_zpool = { diff --git a/tests/unit/__init__.py b/tests/unit/__init__.py index 40a96afc6ff..e69de29bb2d 100644 --- a/tests/unit/__init__.py +++ b/tests/unit/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/tests/unit/modules/__init__.py b/tests/unit/modules/__init__.py index 40a96afc6ff..e69de29bb2d 100644 --- a/tests/unit/modules/__init__.py +++ b/tests/unit/modules/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/tests/unit/modules/inspectlib/__init__.py b/tests/unit/modules/inspectlib/__init__.py index 40a96afc6ff..e69de29bb2d 100644 --- a/tests/unit/modules/inspectlib/__init__.py +++ b/tests/unit/modules/inspectlib/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/tests/unit/modules/inspectlib/test_collector.py b/tests/unit/modules/inspectlib/test_collector.py index 3d767af0dbb..3d638d4ff1a 100644 --- a/tests/unit/modules/inspectlib/test_collector.py +++ b/tests/unit/modules/inspectlib/test_collector.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Copyright 2016 SUSE LLC # @@ -16,17 +15,12 @@ """ :codeauthor: Bo Maryniuk """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals import os -# Import salt libs from salt.modules.inspectlib.collector import Inspector from tests.support.helpers import no_symlinks from tests.support.mock import MagicMock, patch - -# Import Salt Testing Libs from tests.support.unit import TestCase, skipIf diff --git a/tests/unit/modules/nxos/__init__.py b/tests/unit/modules/nxos/__init__.py index 40a96afc6ff..e69de29bb2d 100644 --- a/tests/unit/modules/nxos/__init__.py +++ b/tests/unit/modules/nxos/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/tests/unit/modules/nxos/nxos_config.py b/tests/unit/modules/nxos/nxos_config.py index 2dd59d9a508..caddb798018 100644 --- a/tests/unit/modules/nxos/nxos_config.py +++ b/tests/unit/modules/nxos/nxos_config.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - template_engine_file_str = "no feature ospf" config_result = [["no feature ospf"], [{}]] diff --git a/tests/unit/modules/nxos/nxos_grains.py b/tests/unit/modules/nxos/nxos_grains.py index 6e4ab62f06e..0192ac25e51 100644 --- a/tests/unit/modules/nxos/nxos_grains.py +++ b/tests/unit/modules/nxos/nxos_grains.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - n9k_grains = { "nxos": { "software": { diff --git a/tests/unit/modules/nxos/nxos_n36k.py b/tests/unit/modules/nxos/nxos_n36k.py index ce7d7c0df51..a956e46ed49 100644 --- a/tests/unit/modules/nxos/nxos_n36k.py +++ b/tests/unit/modules/nxos/nxos_n36k.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ :codeauthor: Thomas Stoner """ @@ -16,10 +15,6 @@ # 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. - - -from __future__ import absolute_import - from tests.unit.modules.nxos.nxos_platform import NXOSPlatform diff --git a/tests/unit/modules/nxos/nxos_n3k.py b/tests/unit/modules/nxos/nxos_n3k.py index 3bea55773fa..c0e81e54503 100644 --- a/tests/unit/modules/nxos/nxos_n3k.py +++ b/tests/unit/modules/nxos/nxos_n3k.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ :codeauthor: Thomas Stoner """ @@ -16,10 +15,6 @@ # 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. - - -from __future__ import absolute_import - from tests.unit.modules.nxos.nxos_platform import NXOSPlatform diff --git a/tests/unit/modules/nxos/nxos_n5k.py b/tests/unit/modules/nxos/nxos_n5k.py index d49190c6564..43d8739c399 100644 --- a/tests/unit/modules/nxos/nxos_n5k.py +++ b/tests/unit/modules/nxos/nxos_n5k.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ :codeauthor: Thomas Stoner """ @@ -16,10 +15,6 @@ # 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. - - -from __future__ import absolute_import - from tests.unit.modules.nxos.nxos_platform import NXOSPlatform diff --git a/tests/unit/modules/nxos/nxos_n7k.py b/tests/unit/modules/nxos/nxos_n7k.py index 49e5255e995..1c94f73caab 100644 --- a/tests/unit/modules/nxos/nxos_n7k.py +++ b/tests/unit/modules/nxos/nxos_n7k.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ :codeauthor: Thomas Stoner """ @@ -16,10 +15,6 @@ # 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. - - -from __future__ import absolute_import - from tests.unit.modules.nxos.nxos_platform import NXOSPlatform diff --git a/tests/unit/modules/nxos/nxos_n93k.py b/tests/unit/modules/nxos/nxos_n93k.py index 21182c7a634..da78a369524 100644 --- a/tests/unit/modules/nxos/nxos_n93k.py +++ b/tests/unit/modules/nxos/nxos_n93k.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ :codeauthor: Thomas Stoner """ @@ -16,10 +15,6 @@ # 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. - - -from __future__ import absolute_import - from tests.unit.modules.nxos.nxos_platform import NXOSPlatform diff --git a/tests/unit/modules/nxos/nxos_n93klxc.py b/tests/unit/modules/nxos/nxos_n93klxc.py index 757a5f6abe1..2b9f5c0a2fb 100644 --- a/tests/unit/modules/nxos/nxos_n93klxc.py +++ b/tests/unit/modules/nxos/nxos_n93klxc.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ :codeauthor: Thomas Stoner """ @@ -16,10 +15,6 @@ # 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. - - -from __future__ import absolute_import - from tests.unit.modules.nxos.nxos_platform import NXOSPlatform diff --git a/tests/unit/modules/nxos/nxos_n95k.py b/tests/unit/modules/nxos/nxos_n95k.py index 96c0af5e5a8..31f99303ee0 100644 --- a/tests/unit/modules/nxos/nxos_n95k.py +++ b/tests/unit/modules/nxos/nxos_n95k.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ :codeauthor: Thomas Stoner """ @@ -16,10 +15,6 @@ # 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. - - -from __future__ import absolute_import - from tests.unit.modules.nxos.nxos_platform import NXOSPlatform # pylint: disable-msg=C0103 diff --git a/tests/unit/modules/nxos/nxos_platform.py b/tests/unit/modules/nxos/nxos_platform.py index f1a1f22e2f4..a238d8ee14b 100644 --- a/tests/unit/modules/nxos/nxos_platform.py +++ b/tests/unit/modules/nxos/nxos_platform.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ :codeauthor: Thomas Stoner """ @@ -16,10 +15,6 @@ # 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. - - -from __future__ import absolute_import - import re from string import Template @@ -29,7 +24,7 @@ from string import Template # pylint: disable-msg=C0301 -class NXOSPlatform(object): +class NXOSPlatform: """ Cisco Systems Base Platform Unit Test Object """ diff --git a/tests/unit/modules/nxos/nxos_show_cmd_output.py b/tests/unit/modules/nxos/nxos_show_cmd_output.py index 0486d04491d..748402fd77c 100644 --- a/tests/unit/modules/nxos/nxos_show_cmd_output.py +++ b/tests/unit/modules/nxos/nxos_show_cmd_output.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - n9k_show_ver = """ Cisco Nexus Operating System (NX-OS) Software TAC support: http://www.cisco.com/tac diff --git a/tests/unit/modules/nxos/nxos_show_run.py b/tests/unit/modules/nxos/nxos_show_run.py index 654c91462f1..79edff46cba 100644 --- a/tests/unit/modules/nxos/nxos_show_run.py +++ b/tests/unit/modules/nxos/nxos_show_run.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - n9k_running_config = """ !Command: show running-config !Running configuration last done at: Wed Nov 27 18:54:15 2019 diff --git a/tests/unit/modules/test_boto3_elasticsearch.py b/tests/unit/modules/test_boto3_elasticsearch.py index 346ea4f8934..9e568c14446 100644 --- a/tests/unit/modules/test_boto3_elasticsearch.py +++ b/tests/unit/modules/test_boto3_elasticsearch.py @@ -10,7 +10,6 @@ import textwrap import salt.loader import salt.modules.boto3_elasticsearch as boto3_elasticsearch -from salt.ext.six.moves import range from salt.utils.versions import LooseVersion from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, patch diff --git a/tests/unit/modules/test_boto_cloudtrail.py b/tests/unit/modules/test_boto_cloudtrail.py index 43ee95e2b31..406dd23b703 100644 --- a/tests/unit/modules/test_boto_cloudtrail.py +++ b/tests/unit/modules/test_boto_cloudtrail.py @@ -1,25 +1,15 @@ -# -*- coding: utf-8 -*- - -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - import logging import random import string -# Import Salt libs import salt.config import salt.loader import salt.modules.boto_cloudtrail as boto_cloudtrail -from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin from salt.utils.versions import LooseVersion - -# Import Salt Testing libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, patch from tests.support.unit import TestCase, skipIf -# Import 3rd-party libs # pylint: disable=import-error,no-name-in-module,unused-import try: import boto @@ -98,7 +88,7 @@ if _has_required_boto(): @skipIf( _has_required_boto() is False, "The boto3 module must be greater than" - " or equal to version {0}".format(required_boto3_version), + " or equal to version {}".format(required_boto3_version), ) class BotoCloudTrailTestCaseBase(TestCase, LoaderModuleMockMixin): conn = None @@ -111,7 +101,7 @@ class BotoCloudTrailTestCaseBase(TestCase, LoaderModuleMockMixin): return {boto_cloudtrail: {"__utils__": utils}} def setUp(self): - super(BotoCloudTrailTestCaseBase, self).setUp() + super().setUp() boto_cloudtrail.__init__(self.opts) del self.opts @@ -134,7 +124,7 @@ class BotoCloudTrailTestCaseBase(TestCase, LoaderModuleMockMixin): session_instance.client.return_value = self.conn -class BotoCloudTrailTestCaseMixin(object): +class BotoCloudTrailTestCaseMixin: pass diff --git a/tests/unit/modules/test_boto_cloudwatch_event.py b/tests/unit/modules/test_boto_cloudwatch_event.py index 1b2a4927f59..0cd885a4a1c 100644 --- a/tests/unit/modules/test_boto_cloudwatch_event.py +++ b/tests/unit/modules/test_boto_cloudwatch_event.py @@ -1,24 +1,14 @@ -# -*- coding: utf-8 -*- - -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - import logging import random import string -# Import Salt libs import salt.config import salt.loader import salt.modules.boto_cloudwatch_event as boto_cloudwatch_event -from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin - -# Import Salt Testing libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, patch from tests.support.unit import TestCase, skipIf -# Import 3rd-party libs # pylint: disable=import-error,no-name-in-module,unused-import try: import boto @@ -96,7 +86,7 @@ class BotoCloudWatchEventTestCaseBase(TestCase, LoaderModuleMockMixin): return {boto_cloudwatch_event: {"__utils__": utils}} def setUp(self): - super(BotoCloudWatchEventTestCaseBase, self).setUp() + super().setUp() boto_cloudwatch_event.__init__(self.opts) del self.opts @@ -119,7 +109,7 @@ class BotoCloudWatchEventTestCaseBase(TestCase, LoaderModuleMockMixin): session_instance.client.return_value = self.conn -class BotoCloudWatchEventTestCaseMixin(object): +class BotoCloudWatchEventTestCaseMixin: pass diff --git a/tests/unit/modules/test_boto_cognitoidentity.py b/tests/unit/modules/test_boto_cognitoidentity.py index bca2acd846d..16d0b2184d6 100644 --- a/tests/unit/modules/test_boto_cognitoidentity.py +++ b/tests/unit/modules/test_boto_cognitoidentity.py @@ -5,7 +5,6 @@ import string import salt.config import salt.loader import salt.modules.boto_cognitoidentity as boto_cognitoidentity -from salt.ext.six.moves import range # pylint: disable=import-error from salt.utils.versions import LooseVersion from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, patch diff --git a/tests/unit/modules/test_boto_elasticsearch_domain.py b/tests/unit/modules/test_boto_elasticsearch_domain.py index 3cb3d1a1221..8e709f57d71 100644 --- a/tests/unit/modules/test_boto_elasticsearch_domain.py +++ b/tests/unit/modules/test_boto_elasticsearch_domain.py @@ -5,7 +5,6 @@ import string import salt.loader import salt.modules.boto_elasticsearch_domain as boto_elasticsearch_domain -from salt.ext.six.moves import range from salt.utils.versions import LooseVersion from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, patch diff --git a/tests/unit/modules/test_boto_elb.py b/tests/unit/modules/test_boto_elb.py index 9389386ae1e..790d36e269d 100644 --- a/tests/unit/modules/test_boto_elb.py +++ b/tests/unit/modules/test_boto_elb.py @@ -8,7 +8,6 @@ import salt.config import salt.loader import salt.modules.boto_elb as boto_elb import salt.utils.versions -from salt.ext import six from tests.support.mixins import LoaderModuleMockMixin from tests.support.runtests import RUNTIME_VARS from tests.support.unit import TestCase, skipIf @@ -96,9 +95,7 @@ def _has_required_moto(): ) if moto_version < salt.utils.versions.LooseVersion(required_moto): return False - elif six.PY3 and moto_version < salt.utils.versions.LooseVersion( - required_moto_py3 - ): + elif moto_version < salt.utils.versions.LooseVersion(required_moto_py3): return False return True diff --git a/tests/unit/modules/test_boto_iot.py b/tests/unit/modules/test_boto_iot.py index b075adb462a..b0a518e4cf7 100644 --- a/tests/unit/modules/test_boto_iot.py +++ b/tests/unit/modules/test_boto_iot.py @@ -1,22 +1,11 @@ -# -*- coding: utf-8 -*- - -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - import logging import random import string -# Import Salt libs import salt.config import salt.loader import salt.modules.boto_iot as boto_iot - -# Import 3rd-party libs -from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin from salt.utils.versions import LooseVersion - -# Import Salt Testing libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, patch from tests.support.unit import TestCase, skipIf @@ -124,7 +113,7 @@ if _has_required_boto(): @skipIf( _has_required_boto() is False, "The boto3 module must be greater than" - " or equal to version {0}".format(required_boto3_version), + " or equal to version {}".format(required_boto3_version), ) class BotoIoTTestCaseBase(TestCase, LoaderModuleMockMixin): conn = None @@ -137,7 +126,7 @@ class BotoIoTTestCaseBase(TestCase, LoaderModuleMockMixin): return {boto_iot: {"__utils__": utils}} def setUp(self): - super(BotoIoTTestCaseBase, self).setUp() + super().setUp() boto_iot.__init__(self.opts) del self.opts @@ -160,7 +149,7 @@ class BotoIoTTestCaseBase(TestCase, LoaderModuleMockMixin): session_instance.client.return_value = self.conn -class BotoIoTTestCaseMixin(object): +class BotoIoTTestCaseMixin: pass @@ -834,9 +823,9 @@ class BotoIoTPolicyTestCase(BotoIoTTestCaseBase, BotoIoTTestCaseMixin): @skipIf( _has_required_boto() is False, "The boto3 module must be greater than" - " or equal to version {0}. The botocore" + " or equal to version {}. The botocore" " module must be greater than or equal to" - " version {1}.".format(required_boto3_version, required_botocore_version), + " version {}.".format(required_boto3_version, required_botocore_version), ) class BotoIoTTopicRuleTestCase(BotoIoTTestCaseBase, BotoIoTTestCaseMixin): """ diff --git a/tests/unit/modules/test_boto_lambda.py b/tests/unit/modules/test_boto_lambda.py index 6c9b6901649..954220a2f73 100644 --- a/tests/unit/modules/test_boto_lambda.py +++ b/tests/unit/modules/test_boto_lambda.py @@ -1,7 +1,3 @@ -# -*- coding: utf-8 -*- - -from __future__ import absolute_import, print_function, unicode_literals - import logging import os import random @@ -13,8 +9,6 @@ import salt.loader import salt.modules.boto_lambda as boto_lambda import salt.utils.stringutils from salt.exceptions import SaltInvocationError -from salt.ext import six -from salt.ext.six.moves import range from salt.utils.versions import LooseVersion from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, patch @@ -105,8 +99,8 @@ def _has_required_boto(): @skipIf( _has_required_boto() is False, ( - "The boto3 module must be greater than or equal to version {0}, " - "and botocore must be greater than or equal to {1}".format( + "The boto3 module must be greater than or equal to version {}, " + "and botocore must be greater than or equal to {}".format( required_boto3_version, required_botocore_version ) ), @@ -122,7 +116,7 @@ class BotoLambdaTestCaseBase(TestCase, LoaderModuleMockMixin): return {boto_lambda: {"__utils__": utils}} def setUp(self): - super(BotoLambdaTestCaseBase, self).setUp() + super().setUp() boto_lambda.__init__(self.opts) del self.opts # Set up MagicMock to replace the boto3 session @@ -144,14 +138,13 @@ class BotoLambdaTestCaseBase(TestCase, LoaderModuleMockMixin): self.addCleanup(delattr, self, "conn") -class TempZipFile(object): +class TempZipFile: def __enter__(self): with NamedTemporaryFile( suffix=".zip", prefix="salt_test_", delete=False ) as tmp: to_write = "###\n" - if six.PY3: - to_write = salt.utils.stringutils.to_bytes(to_write) + to_write = salt.utils.stringutils.to_bytes(to_write) tmp.write(to_write) self.zipfile = tmp.name return self.zipfile @@ -160,7 +153,7 @@ class TempZipFile(object): os.remove(self.zipfile) -class BotoLambdaTestCaseMixin(object): +class BotoLambdaTestCaseMixin: pass @@ -601,7 +594,7 @@ class BotoLambdaFunctionTestCase(BotoLambdaTestCaseBase, BotoLambdaTestCaseMixin @skipIf( _has_required_boto() is False, "The boto3 module must be greater than" - " or equal to version {0}".format(required_boto3_version), + " or equal to version {}".format(required_boto3_version), ) class BotoLambdaAliasTestCase(BotoLambdaTestCaseBase, BotoLambdaTestCaseMixin): """ @@ -777,7 +770,7 @@ class BotoLambdaAliasTestCase(BotoLambdaTestCaseBase, BotoLambdaTestCaseMixin): @skipIf( _has_required_boto() is False, "The boto3 module must be greater than" - " or equal to version {0}".format(required_boto3_version), + " or equal to version {}".format(required_boto3_version), ) class BotoLambdaEventSourceMappingTestCase( BotoLambdaTestCaseBase, BotoLambdaTestCaseMixin diff --git a/tests/unit/modules/test_boto_route53.py b/tests/unit/modules/test_boto_route53.py index e745f8f8c64..10e8168c071 100644 --- a/tests/unit/modules/test_boto_route53.py +++ b/tests/unit/modules/test_boto_route53.py @@ -1,27 +1,17 @@ -# -*- coding: utf-8 -*- - -# import Python Libs -from __future__ import absolute_import, print_function, unicode_literals - import logging import os.path from collections import namedtuple import pkg_resources # pylint: disable=3rd-party-module-not-gated -# Import Salt Libs import salt.config import salt.loader import salt.utils.versions -from salt.ext import six - -# Import Salt Testing Libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, patch from tests.support.runtests import RUNTIME_VARS from tests.support.unit import TestCase, skipIf -# import Python Third Party Libs # pylint: disable=import-error try: import salt.modules.boto_route53 as boto_route53 @@ -72,9 +62,7 @@ def _has_required_moto(): ) if moto_version < salt.utils.versions.LooseVersion(required_moto): return False - elif six.PY3 and moto_version < salt.utils.versions.LooseVersion( - required_moto_py3 - ): + elif moto_version < salt.utils.versions.LooseVersion(required_moto_py3): return False return True @@ -83,8 +71,8 @@ def _has_required_moto(): @skipIf(HAS_MOTO is False, "The moto module must be installed.") @skipIf( _has_required_moto() is False, - "The moto module must be >= to {0} for " - "PY2 or {1} for PY3.".format(required_moto, required_moto_py3), + "The moto module must be >= to {} for " + "PY2 or {} for PY3.".format(required_moto, required_moto_py3), ) class BotoRoute53TestCase(TestCase, LoaderModuleMockMixin): """ @@ -154,7 +142,7 @@ class BotoRoute53TestCase(TestCase, LoaderModuleMockMixin): self.assertEqual(healthcheck, expected) -class DummyConn(object): +class DummyConn: """ Simple object housing a mock to simulate Error conditions. Each keyword argument passed into this will be set as MagicMock with the keyword value @@ -162,7 +150,7 @@ class DummyConn(object): """ def __init__(self, **kwargs): - for key, val in six.iteritems(kwargs): + for key, val in kwargs.items(): setattr(self, key, MagicMock(side_effect=val)) diff --git a/tests/unit/modules/test_boto_s3_bucket.py b/tests/unit/modules/test_boto_s3_bucket.py index 2339b4a731e..662b9b47b79 100644 --- a/tests/unit/modules/test_boto_s3_bucket.py +++ b/tests/unit/modules/test_boto_s3_bucket.py @@ -1,23 +1,11 @@ -# -*- coding: utf-8 -*- - -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - import logging import random import string from copy import deepcopy -# Import Salt libs import salt.loader import salt.modules.boto_s3_bucket as boto_s3_bucket - -# Import 3rd-party libs -from salt.ext import six -from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin from salt.utils.versions import LooseVersion - -# Import Salt Testing libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, patch from tests.support.unit import TestCase, skipIf @@ -163,7 +151,7 @@ if _has_required_boto(): @skipIf( _has_required_boto() is False, "The boto3 module must be greater than" - " or equal to version {0}".format(required_boto3_version), + " or equal to version {}".format(required_boto3_version), ) class BotoS3BucketTestCaseBase(TestCase, LoaderModuleMockMixin): conn = None @@ -176,7 +164,7 @@ class BotoS3BucketTestCaseBase(TestCase, LoaderModuleMockMixin): return {boto_s3_bucket: {"__utils__": utils}} def setUp(self): - super(BotoS3BucketTestCaseBase, self).setUp() + super().setUp() boto_s3_bucket.__init__(self.opts) del self.opts # Set up MagicMock to replace the boto3 session @@ -198,7 +186,7 @@ class BotoS3BucketTestCaseBase(TestCase, LoaderModuleMockMixin): session_instance.client.return_value = self.conn -class BotoS3BucketTestCaseMixin(object): +class BotoS3BucketTestCaseMixin: pass @@ -300,7 +288,7 @@ class BotoS3BucketTestCase(BotoS3BucketTestCaseBase, BotoS3BucketTestCaseMixin): """ Tests describing parameters if bucket exists """ - for key, value in six.iteritems(config_ret): + for key, value in config_ret.items(): getattr(self.conn, key).return_value = deepcopy(value) result = boto_s3_bucket.describe(Bucket="mybucket", **conn_parameters) diff --git a/tests/unit/modules/test_boto_secgroup.py b/tests/unit/modules/test_boto_secgroup.py index 8a765278492..50b1b2cd244 100644 --- a/tests/unit/modules/test_boto_secgroup.py +++ b/tests/unit/modules/test_boto_secgroup.py @@ -8,7 +8,6 @@ import salt.loader import salt.modules.boto_secgroup as boto_secgroup # pylint: disable=import-error -from salt.ext.six.moves import range # pylint: disable=redefined-builtin from salt.utils.odict import OrderedDict from salt.utils.versions import LooseVersion from tests.support.mixins import LoaderModuleMockMixin diff --git a/tests/unit/modules/test_cron.py b/tests/unit/modules/test_cron.py index ae9eb24e054..2ab67d9e099 100644 --- a/tests/unit/modules/test_cron.py +++ b/tests/unit/modules/test_cron.py @@ -1,16 +1,11 @@ -# -*- coding: utf-8 -*- """ :codeauthor: Mike Place """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals +import builtins +import io -# Import Salt libs import salt.modules.cron as cron -from salt.ext.six.moves import StringIO, builtins, range - -# Import Salt Testing libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, call, mock_open, patch from tests.support.unit import TestCase @@ -48,7 +43,7 @@ STUB_AT_SIGN = """ L = "# Lines below here are managed by Salt, do not edit\n" -CRONTAB = StringIO() +CRONTAB = io.StringIO() def get_crontab(*args, **kw): @@ -881,7 +876,7 @@ class CronTestCase(TestCase, LoaderModuleMockMixin): (L + "# foo\n" "* * * * * ls\n"), ( L - + "# foo {0}:blah\n".format(cron.SALT_CRON_IDENTIFIER) + + "# foo {}:blah\n".format(cron.SALT_CRON_IDENTIFIER) + "* * * * * ls\n" ), ] diff --git a/tests/unit/modules/test_elasticsearch.py b/tests/unit/modules/test_elasticsearch.py index 5a6f1ef06ed..e6056eba13f 100644 --- a/tests/unit/modules/test_elasticsearch.py +++ b/tests/unit/modules/test_elasticsearch.py @@ -3,12 +3,8 @@ """ from salt.exceptions import CommandExecutionError, SaltInvocationError - -# Import Salt Libs from salt.modules import elasticsearch from tests.support.mock import MagicMock, patch - -# Import Salt Testing Libs from tests.support.unit import TestCase, skipIf # Import elasticsearch exceptions diff --git a/tests/unit/modules/test_freezer.py b/tests/unit/modules/test_freezer.py index f4fcbfdd7ab..436ec4b7446 100644 --- a/tests/unit/modules/test_freezer.py +++ b/tests/unit/modules/test_freezer.py @@ -1,17 +1,11 @@ -# -*- coding: utf-8 -*- - """ :maintainer: Alberto Planas :platform: Linux """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals import salt.modules.freezer as freezer from salt.exceptions import CommandExecutionError - -# Import Salt Testing Libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, patch from tests.support.unit import TestCase diff --git a/tests/unit/modules/test_heat.py b/tests/unit/modules/test_heat.py index 60eb6ccdebd..9520085bddf 100644 --- a/tests/unit/modules/test_heat.py +++ b/tests/unit/modules/test_heat.py @@ -1,26 +1,17 @@ -# -*- coding: utf-8 -*- - -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals - import os import salt.modules.file as file_ import salt.modules.heat as heat import salt.modules.win_file as win_file - -# Import Salt Libs import salt.utils.platform import salt.utils.win_dacl as dacl - -# Import Salt Testing Libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, patch from tests.support.runtests import RUNTIME_VARS from tests.support.unit import TestCase -class MockStacks(object): +class MockStacks: """ Mock stacks.StackManager """ @@ -57,7 +48,7 @@ class MockStacks(object): return self.mock_update -class MockClient(object): +class MockClient: """ Mock of Client class """ @@ -175,7 +166,7 @@ class HeatTestCase(TestCase, LoaderModuleMockMixin): ) assert ret == { "result": False, - "comment": "Can not open environment: {0}, ".format(env_file), + "comment": "Can not open environment: {}, ".format(env_file), } def test_heat_update_stack(self): diff --git a/tests/unit/modules/test_hosts.py b/tests/unit/modules/test_hosts.py index 545b9a7a8ba..1ebc9fa8252 100644 --- a/tests/unit/modules/test_hosts.py +++ b/tests/unit/modules/test_hosts.py @@ -2,13 +2,12 @@ :codeauthor: Jayesh Kariya """ +import io import salt.modules.hosts as hosts import salt.utils.data import salt.utils.platform import salt.utils.stringutils -from salt.ext import six -from salt.ext.six.moves import StringIO from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, mock_open, patch from tests.support.unit import TestCase @@ -144,7 +143,7 @@ class HostsTestCase(TestCase, LoaderModuleMockMixin): ) ] - class TmpStringIO(StringIO): + class TmpStringIO(io.StringIO): def __init__(self, fn, mode="r"): self.mode = mode initial_value = data[0] @@ -169,11 +168,11 @@ class HostsTestCase(TestCase, LoaderModuleMockMixin): # module if self.getvalue(): data[0] = self.getvalue() - StringIO.close(self) + io.StringIO.close(self) def read(self, *args): ret = super().read(*args) - if six.PY3 and "b" in self.mode: + if "b" in self.mode: return salt.utils.stringutils.to_bytes(ret) else: return ret @@ -196,7 +195,7 @@ class HostsTestCase(TestCase, LoaderModuleMockMixin): def readlines(self): ret = super().readlines() - if six.PY3 and "b" in self.mode: + if "b" in self.mode: return salt.utils.data.encode(ret) else: return ret diff --git a/tests/unit/modules/test_influxdb08mod.py b/tests/unit/modules/test_influxdb08mod.py index 311abdfa54f..d0a09254adf 100644 --- a/tests/unit/modules/test_influxdb08mod.py +++ b/tests/unit/modules/test_influxdb08mod.py @@ -1,23 +1,17 @@ -# -*- coding: utf-8 -*- """ :codeauthor: Rupesh Tare """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals -# Import Salt Libs import salt.modules.influxdb08mod as influx08 from tests.support.mock import MagicMock, patch - -# Import Salt Testing Libs from tests.support.unit import TestCase DB_LIST = ["A", "B", "C"] USER_LIST = [{"name": "A"}, {"name": "B"}] -class MockInfluxDBClient(object): +class MockInfluxDBClient: def get_list_database(self): return DB_LIST diff --git a/tests/unit/modules/test_jboss7.py b/tests/unit/modules/test_jboss7.py index 098096182a3..d13f9dbf9bb 100644 --- a/tests/unit/modules/test_jboss7.py +++ b/tests/unit/modules/test_jboss7.py @@ -1,14 +1,5 @@ -# -*- coding: utf-8 -*- - -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals - import salt.modules.jboss7 as jboss7 - -# Import salt libs from salt.utils.odict import OrderedDict - -# Import salt testing libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock from tests.support.unit import TestCase diff --git a/tests/unit/modules/test_jboss7_cli.py b/tests/unit/modules/test_jboss7_cli.py index 699337bbf4f..ff509dd7b1c 100644 --- a/tests/unit/modules/test_jboss7_cli.py +++ b/tests/unit/modules/test_jboss7_cli.py @@ -1,23 +1,13 @@ -# -*- coding: utf-8 -*- - -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - import re import salt.modules.jboss7_cli as jboss7_cli from salt.exceptions import CommandExecutionError - -# Import Salt libs -from salt.ext import six - -# Import Salt testing libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import patch from tests.support.unit import TestCase -class CmdMock(object): +class CmdMock: commands = [] command_response_func = None # if you want to test complete response object (with retcode, stdout and stderr) cli_commands = [] @@ -154,7 +144,7 @@ class JBoss7CliTestCase(TestCase, LoaderModuleMockMixin): assert False except CommandExecutionError as err: self.assertTrue( - six.text_type(err).startswith("Could not execute jboss-cli.sh script") + str(err).startswith("Could not execute jboss-cli.sh script") ) def test_handling_other_cmd_error(self): @@ -172,7 +162,7 @@ class JBoss7CliTestCase(TestCase, LoaderModuleMockMixin): # should throw an exception self.fail("An exception should be thrown") except CommandExecutionError as err: - self.assertTrue(six.text_type(err).startswith("Command execution failed")) + self.assertTrue(str(err).startswith("Command execution failed")) def test_matches_cli_output(self): text = """{ diff --git a/tests/unit/modules/test_kapacitor.py b/tests/unit/modules/test_kapacitor.py index 871a3dd0006..f770c7b05cb 100644 --- a/tests/unit/modules/test_kapacitor.py +++ b/tests/unit/modules/test_kapacitor.py @@ -1,14 +1,5 @@ -# -*- coding: utf-8 -*- - -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - import salt.modules.kapacitor as kapacitor - -# Import Salt libs import salt.utils.json - -# Import Salt testing libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import Mock, patch from tests.support.unit import TestCase diff --git a/tests/unit/modules/test_kernelpkg_linux_apt.py b/tests/unit/modules/test_kernelpkg_linux_apt.py index 788b08d184c..eba7f0a73a9 100644 --- a/tests/unit/modules/test_kernelpkg_linux_apt.py +++ b/tests/unit/modules/test_kernelpkg_linux_apt.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ :synopsis: Unit Tests for 'module.aptkernelpkg' :platform: Linux @@ -7,8 +6,6 @@ """ # pylint: disable=invalid-name,no-member -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals import re @@ -41,10 +38,10 @@ class AptKernelPkgTestCase(KernelPkgTestCase, TestCase, LoaderModuleMockMixin): @classmethod def setUpClass(cls): version = re.match(r"^(\d+\.\d+\.\d+)-(\d+)", cls.KERNEL_LIST[-1]) - cls.LATEST = "{0}.{1}".format(version.group(1), version.group(2)) + cls.LATEST = "{}.{}".format(version.group(1), version.group(2)) for kernel in cls.KERNEL_LIST: - pkg = "{0}-{1}".format( + pkg = "{}-{}".format( kernelpkg._package_prefix(), kernel ) # pylint: disable=protected-access cls.PACKAGE_DICT[pkg] = pkg @@ -68,7 +65,7 @@ class AptKernelPkgTestCase(KernelPkgTestCase, TestCase, LoaderModuleMockMixin): Test - Return return the latest installed kernel version """ PACKAGE_LIST = [ - "{0}-{1}".format(kernelpkg._package_prefix(), kernel) + "{}-{}".format(kernelpkg._package_prefix(), kernel) for kernel in self.KERNEL_LIST ] # pylint: disable=protected-access @@ -94,7 +91,7 @@ class AptKernelPkgTestCase(KernelPkgTestCase, TestCase, LoaderModuleMockMixin): ): result = self._kernelpkg.remove(release=self.KERNEL_LIST[0]) self.assertIn("removed", result) - target = "{0}-{1}".format( + target = "{}-{}".format( self._kernelpkg._package_prefix(), self.KERNEL_LIST[0] ) # pylint: disable=protected-access self.assertListEqual(result["removed"], [target]) diff --git a/tests/unit/modules/test_kernelpkg_linux_yum.py b/tests/unit/modules/test_kernelpkg_linux_yum.py index 1b2a9144fb0..becc95a8eb7 100644 --- a/tests/unit/modules/test_kernelpkg_linux_yum.py +++ b/tests/unit/modules/test_kernelpkg_linux_yum.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ :synopsis: Unit Tests for 'module.yumkernelpkg' :platform: Linux @@ -7,8 +6,6 @@ """ # pylint: disable=invalid-name,no-member -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals try: # Import Salt Testing Libs @@ -46,9 +43,7 @@ class YumKernelPkgTestCase(KernelPkgTestCase, TestCase, LoaderModuleMockMixin): "__grains__": { "os": self.OS_NAME, "osmajorrelease": self.OS_MAJORRELEASE, - "kernelrelease": "{0}.{1}".format( - self.KERNEL_LIST[0], self.OS_ARCH - ), + "kernelrelease": "{}.{}".format(self.KERNEL_LIST[0], self.OS_ARCH), }, "__salt__": { "pkg.normalize_name": pkg.normalize_name, @@ -92,7 +87,7 @@ class YumKernelPkgTestCase(KernelPkgTestCase, TestCase, LoaderModuleMockMixin): ): result = self._kernelpkg.remove(release=self.KERNEL_LIST[0]) self.assertIn("removed", result) - target = "{0}-{1}".format( + target = "{}-{}".format( self._kernelpkg._package_name(), self.KERNEL_LIST[0] ) # pylint: disable=protected-access self.assertListEqual(result["removed"], [target]) diff --git a/tests/unit/modules/test_kubernetesmod.py b/tests/unit/modules/test_kubernetesmod.py index a4b479a92a3..51ff0ec9292 100644 --- a/tests/unit/modules/test_kubernetesmod.py +++ b/tests/unit/modules/test_kubernetesmod.py @@ -1,11 +1,8 @@ -# -*- coding: utf-8 -*- """ :codeauthor: Jochen Breuer """ # pylint: disable=no-value-for-parameter -# Import Python Libs -from __future__ import absolute_import import os from contextlib import contextmanager @@ -13,8 +10,6 @@ from contextlib import contextmanager import salt.utils.files import salt.utils.platform from salt.modules import kubernetesmod as kubernetes - -# Import Salt Testing Libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import Mock, patch from tests.support.unit import TestCase, skipIf diff --git a/tests/unit/modules/test_linux_acl.py b/tests/unit/modules/test_linux_acl.py index 7ed937f2f31..35dadbedacf 100644 --- a/tests/unit/modules/test_linux_acl.py +++ b/tests/unit/modules/test_linux_acl.py @@ -1,13 +1,5 @@ -# -*- coding: utf-8 -*- - -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - -# Import salt libs import salt.modules.linux_acl as linux_acl from salt.exceptions import CommandExecutionError - -# Import Salt Testing libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, patch from tests.support.unit import TestCase @@ -23,7 +15,7 @@ class LinuxAclTestCase(TestCase, LoaderModuleMockMixin): self.file = "/tmp/file" self.quoted_file = '"/tmp/file"' self.files = ["/tmp/file1", "/tmp/file2", "/tmp/file3 with whitespaces"] - self.quoted_files = ['"{0}"'.format(f) for f in self.files] + self.quoted_files = ['"{}"'.format(f) for f in self.files] self.u_acl = ["u", "myuser", "rwx"] self.user_acl = ["user", "myuser", "rwx"] self.user_acl_cmd = "u:myuser:rwx" diff --git a/tests/unit/modules/test_localemod.py b/tests/unit/modules/test_localemod.py index b7a5955db63..fc9ffaec4c4 100644 --- a/tests/unit/modules/test_localemod.py +++ b/tests/unit/modules/test_localemod.py @@ -1,17 +1,10 @@ -# -*- coding: utf-8 -*- """ :codeauthor: Rupesh Tare """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals -# Import Salt Libs import salt.modules.localemod as localemod from salt.exceptions import CommandExecutionError -from salt.ext import six - -# Import Salt Testing Libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, Mock, patch from tests.support.unit import TestCase, skipIf @@ -173,7 +166,7 @@ class LocalemodTestCase(TestCase, LoaderModuleMockMixin): """ with pytest.raises(CommandExecutionError) as exc_info: localemod._localectl_status() - assert 'Unable to find "localectl"' in six.text_type(exc_info.value) + assert 'Unable to find "localectl"' in str(exc_info.value) assert not localemod.log.debug.called @patch("salt.utils.path.which", MagicMock(return_value="/usr/bin/localctl")) @@ -184,7 +177,7 @@ class LocalemodTestCase(TestCase, LoaderModuleMockMixin): def test_localectl_status_parser_empty(self): with pytest.raises(CommandExecutionError) as exc_info: localemod._localectl_status() - assert 'Unable to parse result of "localectl"' in six.text_type(exc_info.value) + assert 'Unable to parse result of "localectl"' in str(exc_info.value) @patch("salt.utils.path.which", MagicMock(return_value="/usr/bin/localctl")) @patch( @@ -194,7 +187,7 @@ class LocalemodTestCase(TestCase, LoaderModuleMockMixin): def test_localectl_status_parser_broken(self): with pytest.raises(CommandExecutionError) as exc_info: localemod._localectl_status() - assert 'Unable to parse result of "localectl"' in six.text_type(exc_info.value) + assert 'Unable to parse result of "localectl"' in str(exc_info.value) @patch("salt.utils.path.which", MagicMock(return_value="/usr/bin/localctl")) @patch( @@ -207,8 +200,8 @@ class LocalemodTestCase(TestCase, LoaderModuleMockMixin): for key in ["main", "cow_say"]: assert isinstance(out[key], dict) for in_key in out[key]: - assert isinstance(out[key][in_key], six.text_type) - assert isinstance(out["reason"]["data"], six.text_type) + assert isinstance(out[key][in_key], str) + assert isinstance(out["reason"]["data"], str) @patch("salt.utils.path.which", MagicMock(return_value="/usr/bin/localctl")) @patch( @@ -371,7 +364,7 @@ class LocalemodTestCase(TestCase, LoaderModuleMockMixin): """ with pytest.raises(CommandExecutionError) as exc_info: localemod.get_locale() - assert '"DrunkDragon" is unsupported' in six.text_type(exc_info.value) + assert '"DrunkDragon" is unsupported' in str(exc_info.value) @patch("salt.utils.path.which", MagicMock(return_value="/usr/bin/localctl")) @patch( @@ -504,7 +497,7 @@ class LocalemodTestCase(TestCase, LoaderModuleMockMixin): with pytest.raises(CommandExecutionError) as exc_info: localemod.set_locale(loc) assert not localemod._localectl_set.called - assert 'Cannot set locale: "update-locale" was not found.' in six.text_type( + assert 'Cannot set locale: "update-locale" was not found.' in str( exc_info.value ) @@ -608,7 +601,7 @@ class LocalemodTestCase(TestCase, LoaderModuleMockMixin): """ with pytest.raises(CommandExecutionError) as exc_info: localemod.set_locale("de_DE.utf8") - assert "Unsupported platform" in six.text_type(exc_info.value) + assert "Unsupported platform" in str(exc_info.value) @patch( "salt.utils.locales.normalize_locale", @@ -711,7 +704,7 @@ class LocalemodTestCase(TestCase, LoaderModuleMockMixin): localemod.gen_locale("de_DE.utf8") assert ( 'Command "locale-gen" or "localedef" was not found on this system.' - in six.text_type(exc_info.value) + in str(exc_info.value) ) def test_gen_locale_debian(self): diff --git a/tests/unit/modules/test_memcached.py b/tests/unit/modules/test_memcached.py index 203b0d0446f..b62986f2317 100644 --- a/tests/unit/modules/test_memcached.py +++ b/tests/unit/modules/test_memcached.py @@ -1,18 +1,11 @@ -# -*- coding: utf-8 -*- """ :codeauthor: Jayesh Kariya """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals -# Import Salt Libs import salt.modules.memcached as memcached from salt.exceptions import CommandExecutionError, SaltInvocationError -from salt.ext.six import integer_types from tests.support.mock import MagicMock, patch - -# Import Salt Testing Libs from tests.support.unit import TestCase @@ -28,7 +21,7 @@ class MemcachedTestCase(TestCase): Test if it gets memcached status """ - class MockMemcache(object): + class MockMemcache: """ Mock of memcache """ @@ -50,7 +43,7 @@ class MemcachedTestCase(TestCase): Test if it gets memcached status """ - class MockMemcache(object): + class MockMemcache: """ Mock of memcache """ @@ -74,7 +67,7 @@ class MemcachedTestCase(TestCase): Test if it retrieve value for a key """ - class MockMemcache(object): + class MockMemcache: """ Mock of memcache """ @@ -105,7 +98,7 @@ class MemcachedTestCase(TestCase): Test if it set a key on the memcached server """ - class MockMemcache(object): + class MockMemcache: """ Mock of memcache """ @@ -157,7 +150,7 @@ class MemcachedTestCase(TestCase): Test if it delete a key from memcache server """ - class MockMemcache(object): + class MockMemcache: """ Mock of memcache """ @@ -197,7 +190,7 @@ class MemcachedTestCase(TestCase): Test if it add a key from memcache server """ - class MockMemcache(object): + class MockMemcache: """ Mock of memcache """ @@ -249,7 +242,7 @@ class MemcachedTestCase(TestCase): Test if it replace a key from memcache server """ - class MockMemcache(object): + class MockMemcache: """ Mock of memcache """ @@ -301,7 +294,7 @@ class MemcachedTestCase(TestCase): Test if it increment the value of a key """ - class MockMemcache(object): + class MockMemcache: """ Mock of memcache """ @@ -328,7 +321,7 @@ class MemcachedTestCase(TestCase): Mock of incr method """ self.key = key - if not isinstance(delta, integer_types): + if not isinstance(delta, int): raise SaltInvocationError("Delta value must be an integer") return key @@ -346,7 +339,7 @@ class MemcachedTestCase(TestCase): Test if it increment the value of a key """ - class MockMemcache(object): + class MockMemcache: """ Mock of memcache """ @@ -378,7 +371,7 @@ class MemcachedTestCase(TestCase): Test if it increment the value of a key """ - class MockMemcache(object): + class MockMemcache: """ Mock of memcache """ @@ -412,7 +405,7 @@ class MemcachedTestCase(TestCase): Test if it decrement the value of a key """ - class MockMemcache(object): + class MockMemcache: """ Mock of memcache """ @@ -439,7 +432,7 @@ class MemcachedTestCase(TestCase): Mock of decr method """ self.key = key - if not isinstance(delta, integer_types): + if not isinstance(delta, int): raise SaltInvocationError("Delta value must be an integer") return key @@ -457,7 +450,7 @@ class MemcachedTestCase(TestCase): Test if it decrement the value of a key """ - class MockMemcache(object): + class MockMemcache: """ Mock of memcache """ @@ -489,7 +482,7 @@ class MemcachedTestCase(TestCase): Test if it decrement the value of a key """ - class MockMemcache(object): + class MockMemcache: """ Mock of memcache """ diff --git a/tests/unit/modules/test_netbox.py b/tests/unit/modules/test_netbox.py index 9654fefec13..3f51c50ff20 100644 --- a/tests/unit/modules/test_netbox.py +++ b/tests/unit/modules/test_netbox.py @@ -1,14 +1,9 @@ -# -*- coding: utf-8 -*- """ :codeauthor: :email:`Zach Moody ` """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals import salt.modules.netbox as netbox - -# Import Salt Testing Libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, call, patch from tests.support.unit import TestCase, skipIf diff --git a/tests/unit/modules/test_netscaler.py b/tests/unit/modules/test_netscaler.py index a7b0bf04e39..46b195ec297 100644 --- a/tests/unit/modules/test_netscaler.py +++ b/tests/unit/modules/test_netscaler.py @@ -1,15 +1,9 @@ -# -*- coding: utf-8 -*- """ :codeauthor: Jayesh Kariya """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals -# Import Salt Libs import salt.modules.netscaler as netscaler - -# Import Salt Testing Libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, patch from tests.support.unit import TestCase @@ -42,7 +36,7 @@ class MockNSNitroError(Exception): def __init__(self, message="error"): self._message = message - super(MockNSNitroError, self).__init__(self.message) + super().__init__(self.message) def _get_message(self): """ @@ -59,7 +53,7 @@ class MockNSNitroError(Exception): message = property(_get_message, _set_message) -class MockNSNitro(object): +class MockNSNitro: """ Mock NSNitro class """ @@ -84,7 +78,7 @@ class MockNSNitro(object): return True -class MockNSServiceGroup(object): +class MockNSServiceGroup: """ Mock NSServiceGroup class """ @@ -182,7 +176,7 @@ class MockNSServiceGroup(object): return bol -class MockNSServiceGroupServerBinding(object): +class MockNSServiceGroupServerBinding: """ Mock NSServiceGroupServerBinding class """ @@ -230,7 +224,7 @@ class MockNSServiceGroupServerBinding(object): return MockNSServiceGroupServerBinding() -class MockNSService(object): +class MockNSService: """ Mock NSService class """ @@ -280,7 +274,7 @@ class MockNSService(object): return "UP" -class MockNSServer(object): +class MockNSServer: """ Mock NSServer class """ @@ -364,7 +358,7 @@ class MockNSServer(object): return "ENABLED" -class MockNSLBVServer(object): +class MockNSLBVServer: """ Mock NSLBVServer class """ @@ -443,7 +437,7 @@ class MockNSLBVServer(object): return MockNSLBVServer() -class MockNSLBVServerServiceGroupBinding(object): +class MockNSLBVServerServiceGroupBinding: """ Mock NSLBVServerServiceGroupBinding class """ @@ -504,7 +498,7 @@ class MockNSLBVServerServiceGroupBinding(object): return MockNSLBVServerServiceGroupBinding() -class MockNSSSLVServerSSLCertKeyBinding(object): +class MockNSSSLVServerSSLCertKeyBinding: """ Mock NSSSLVServerSSLCertKeyBinding class """ diff --git a/tests/unit/modules/test_neutron.py b/tests/unit/modules/test_neutron.py index da174fdfb91..7fed7bcc121 100644 --- a/tests/unit/modules/test_neutron.py +++ b/tests/unit/modules/test_neutron.py @@ -1,21 +1,15 @@ -# -*- coding: utf-8 -*- """ :codeauthor: Jayesh Kariya """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals -# Import Salt Libs import salt.modules.neutron as neutron - -# Import Salt Testing Libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock from tests.support.unit import TestCase -class MockNeutron(object): +class MockNeutron: """ Mock of neutron """ diff --git a/tests/unit/modules/test_nginx.py b/tests/unit/modules/test_nginx.py index d6b359425b9..49387637033 100644 --- a/tests/unit/modules/test_nginx.py +++ b/tests/unit/modules/test_nginx.py @@ -1,12 +1,5 @@ -# -*- coding: utf-8 -*- - -# Import Pytohn libs -from __future__ import absolute_import, print_function, unicode_literals - # Import Salt Module import salt.modules.nginx as nginx - -# Import Salt Testing libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import Mock, patch from tests.support.unit import TestCase @@ -17,7 +10,7 @@ server accepts handled requests Reading: 0 Writing: 7 Waiting: 0""" -class MockUrllibStatus(object): +class MockUrllibStatus: """Mock of urllib2 call for Nginx status""" def read(self): diff --git a/tests/unit/modules/test_nova.py b/tests/unit/modules/test_nova.py index d21e173cbe6..192d377c105 100644 --- a/tests/unit/modules/test_nova.py +++ b/tests/unit/modules/test_nova.py @@ -1,15 +1,9 @@ -# -*- coding: utf-8 -*- """ :codeauthor: Rahul Handay """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals -# Import Salt Libs import salt.modules.nova as nova - -# Import Salt Testing Libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, patch from tests.support.unit import TestCase diff --git a/tests/unit/modules/test_nxos.py b/tests/unit/modules/test_nxos.py index e93ba0a1f05..6e2c356f6ef 100644 --- a/tests/unit/modules/test_nxos.py +++ b/tests/unit/modules/test_nxos.py @@ -1,8 +1,6 @@ -# -*- coding: utf-8 -*- """ :codeauthor: Mike Wiebe <@mikewiebe> """ -from __future__ import absolute_import, print_function, unicode_literals import salt.modules.cp as cp_module import salt.modules.file as file_module diff --git a/tests/unit/modules/test_nxos_upgrade.py b/tests/unit/modules/test_nxos_upgrade.py index 832dab32624..59197a83a72 100644 --- a/tests/unit/modules/test_nxos_upgrade.py +++ b/tests/unit/modules/test_nxos_upgrade.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ :codeauthor: Thomas Stoner """ @@ -16,16 +15,8 @@ # 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. - - -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals - -# Import Salt Libs import salt.modules.nxos_upgrade as nxos_upgrade from salt.exceptions import CommandExecutionError, NxosError - -# Import Salt Testing Libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, patch from tests.support.unit import TestCase @@ -54,7 +45,7 @@ class NxosUpgradeTestCase(TestCase, LoaderModuleMockMixin): """ Assert platform upgrade condition and display appropriate chassis & images upon assertion failure """ - assert bool(condition), "{0}: Upgrade {1} -> {2}".format( + assert bool(condition), "{}: Upgrade {} -> {}".format( platform.chassis, platform.cimage, platform.nimage ) diff --git a/tests/unit/modules/test_openstack_config.py b/tests/unit/modules/test_openstack_config.py index d0d1cb5a408..56976992c21 100644 --- a/tests/unit/modules/test_openstack_config.py +++ b/tests/unit/modules/test_openstack_config.py @@ -1,16 +1,10 @@ -# -*- coding: utf-8 -*- """ :codeauthor: Jayesh Kariya """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals -# Import Salt Libs import salt.modules.openstack_config as openstack_config from salt.exceptions import CommandExecutionError - -# Import Salt Testing Libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, patch from tests.support.unit import TestCase diff --git a/tests/unit/modules/test_parted_partition.py b/tests/unit/modules/test_parted_partition.py index 3fff6acee8c..073d29ba38d 100644 --- a/tests/unit/modules/test_parted_partition.py +++ b/tests/unit/modules/test_parted_partition.py @@ -6,14 +6,9 @@ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ -# Import Python libs import salt.modules.parted_partition as parted - -# Import Salt libs from salt.exceptions import CommandExecutionError - -# Import Salt Testing libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, patch from tests.support.unit import TestCase diff --git a/tests/unit/modules/test_snapper.py b/tests/unit/modules/test_snapper.py index b5d6d27eff8..07c81ef6993 100644 --- a/tests/unit/modules/test_snapper.py +++ b/tests/unit/modules/test_snapper.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Unit tests for the Snapper module @@ -6,18 +5,11 @@ Unit tests for the Snapper module :codeauthor: Pablo Suárez Hernández """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import sys import salt.modules.snapper as snapper from salt.exceptions import CommandExecutionError - -# Import Salt libs -from salt.ext import six - -# Import Salt Testing libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, mock_open, patch from tests.support.unit import TestCase, skipIf @@ -398,28 +390,12 @@ class SnapperTestCase(TestCase, LoaderModuleMockMixin): "salt.modules.snapper.snapper.ListConfigs", MagicMock(return_value=DBUS_RET["ListConfigs"]), ): - if six.PY3: - self.assertCountEqual(snapper.status(), MODULE_RET["GETFILES"]) - self.assertCountEqual( - snapper.status(num_pre="42", num_post=43), MODULE_RET["GETFILES"] - ) - self.assertCountEqual( - snapper.status(num_pre=42), MODULE_RET["GETFILES"] - ) - self.assertCountEqual( - snapper.status(num_post=43), MODULE_RET["GETFILES"] - ) - else: - self.assertItemsEqual(snapper.status(), MODULE_RET["GETFILES"]) - self.assertItemsEqual( - snapper.status(num_pre="42", num_post=43), MODULE_RET["GETFILES"] - ) - self.assertItemsEqual( - snapper.status(num_pre=42), MODULE_RET["GETFILES"] - ) - self.assertItemsEqual( - snapper.status(num_post=43), MODULE_RET["GETFILES"] - ) + self.assertCountEqual(snapper.status(), MODULE_RET["GETFILES"]) + self.assertCountEqual( + snapper.status(num_pre="42", num_post=43), MODULE_RET["GETFILES"] + ) + self.assertCountEqual(snapper.status(num_pre=42), MODULE_RET["GETFILES"]) + self.assertCountEqual(snapper.status(num_post=43), MODULE_RET["GETFILES"]) def test_changed_files(self): with patch( diff --git a/tests/unit/modules/test_solarisipspkg.py b/tests/unit/modules/test_solarisipspkg.py index 320db023605..bf4745c5f85 100644 --- a/tests/unit/modules/test_solarisipspkg.py +++ b/tests/unit/modules/test_solarisipspkg.py @@ -1,17 +1,8 @@ -# -*- coding: utf-8 -*- - -# Import Python Libs -from __future__ import absolute_import - import sys import salt.modules.pkg_resource as pkg_resource - -# Import Salt libs import salt.modules.solarisipspkg as solarisips import salt.utils.data - -# Import Salt Testing Libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, patch from tests.support.unit import TestCase, skipIf diff --git a/tests/unit/modules/test_sqlite3.py b/tests/unit/modules/test_sqlite3.py index 5d84ba8fc01..1b534e7d963 100644 --- a/tests/unit/modules/test_sqlite3.py +++ b/tests/unit/modules/test_sqlite3.py @@ -1,20 +1,14 @@ -# -*- coding: utf-8 -*- """ :codeauthor: Jayesh Kariya """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals -# Import Salt Libs import salt.modules.sqlite3 as sqlite3 - -# Import Salt Testing Libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.unit import TestCase -class MockSqlite3(object): +class MockSqlite3: """ Mock sqlite3 class """ diff --git a/tests/unit/modules/test_ssh.py b/tests/unit/modules/test_ssh.py index 42c07d5d5f0..efcfc4bf1ae 100644 --- a/tests/unit/modules/test_ssh.py +++ b/tests/unit/modules/test_ssh.py @@ -1,18 +1,9 @@ -# -*- coding: utf-8 -*- - -# import Python Libs -from __future__ import absolute_import, print_function, unicode_literals - import tempfile import salt.modules.ssh as ssh - -# Import Salt Libs import salt.utils.files import salt.utils.platform from salt.exceptions import CommandExecutionError - -# Import Salt Testing Libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, patch from tests.support.unit import TestCase @@ -103,7 +94,7 @@ class SSHAuthKeyTestCase(TestCase, LoaderModuleMockMixin): _fh.write(comment_line) # Add empty line for #41335 _fh.write(empty_line) - _fh.write("{0} {1} {2} {3}".format(options, enc, key, email)) + _fh.write("{} {} {} {}".format(options, enc, key, email)) with patch.dict(ssh.__salt__, {"user.info": MagicMock(return_value={})}): with patch( @@ -125,7 +116,7 @@ class SSHAuthKeyTestCase(TestCase, LoaderModuleMockMixin): key = "abcxyz" with salt.utils.files.fopen(temp_file.name, "a") as _fh: - _fh.write(salt.utils.stringutils.to_str("{0} {1}".format(enc, key))) + _fh.write(salt.utils.stringutils.to_str("{} {}".format(enc, key))) # Replace the simple key from before with the more complicated options + new email # Option example is taken from Pull Request #39855 @@ -156,7 +147,7 @@ class SSHAuthKeyTestCase(TestCase, LoaderModuleMockMixin): file_txt = salt.utils.stringutils.to_unicode(_fh.read()) self.assertIn(enc, file_txt) self.assertIn(key, file_txt) - self.assertIn("{0} ".format(",".join(options)), file_txt) + self.assertIn("{} ".format(",".join(options)), file_txt) self.assertIn(email, file_txt) self.assertIn(empty_line, file_txt) self.assertIn(comment_line, file_txt) diff --git a/tests/unit/modules/test_supervisord.py b/tests/unit/modules/test_supervisord.py index bf74c225d90..c21e81da59d 100644 --- a/tests/unit/modules/test_supervisord.py +++ b/tests/unit/modules/test_supervisord.py @@ -1,16 +1,10 @@ -# -*- coding: utf-8 -*- """ :codeauthor: Jayesh Kariya """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals -# Import Salt Libs import salt.modules.supervisord as supervisord from salt.exceptions import CommandExecutionError - -# Import Salt Testing Libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, patch from tests.support.unit import TestCase @@ -171,7 +165,7 @@ class SupervisordTestCase(TestCase, LoaderModuleMockMixin): for a given process """ - class MockConfig(object): + class MockConfig: """ Mock Config class """ diff --git a/tests/unit/modules/test_swarm.py b/tests/unit/modules/test_swarm.py index f6364c9dd7c..8506c707217 100644 --- a/tests/unit/modules/test_swarm.py +++ b/tests/unit/modules/test_swarm.py @@ -1,9 +1,4 @@ -# Import Python libs - -# Import Salt Libs import salt.modules.swarm - -# Import Salt Testing Libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import patch from tests.support.unit import TestCase diff --git a/tests/unit/modules/test_sysmod.py b/tests/unit/modules/test_sysmod.py index 257bca27ff8..00185a90099 100644 --- a/tests/unit/modules/test_sysmod.py +++ b/tests/unit/modules/test_sysmod.py @@ -1,21 +1,15 @@ -# -*- coding: utf-8 -*- """ :codeauthor: Jayesh Kariya """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals -# Import Salt Libs import salt.modules.sysmod as sysmod - -# Import Salt Testing Libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import patch from tests.support.unit import TestCase -class MockDocstringable(object): +class MockDocstringable: def __init__(self, docstr): self.__doc__ = docstr @@ -23,12 +17,12 @@ class MockDocstringable(object): self.__globals__ = {"__doc__": docstr} -class Mockstate(object): +class Mockstate: """ Mock of State """ - class State(object): + class State: """ Mock state functions """ @@ -39,12 +33,12 @@ class Mockstate(object): pass -class Mockrunner(object): +class Mockrunner: """ Mock of runner """ - class Runner(object): + class Runner: """ Mock runner functions """ @@ -57,7 +51,7 @@ class Mockrunner(object): return sysmod.__salt__ -class Mockloader(object): +class Mockloader: """ Mock of loader """ @@ -114,20 +108,20 @@ class SysmodTestCase(TestCase, LoaderModuleMockMixin): cls.salt_dunder = {} for func in cls._functions: - docstring = "docstring for {0}".format(func) + docstring = "docstring for {}".format(func) cls.salt_dunder[func] = MockDocstringable(docstring) cls._docstrings[func] = docstring module = func.split(".")[0] cls._statedocstrings[func] = docstring - cls._statedocstrings[module] = "docstring for {0}".format(module) + cls._statedocstrings[module] = "docstring for {}".format(module) cls._modules.add(func.split(".")[0]) - docstring = "docstring for {0}".format(func) + docstring = "docstring for {}".format(func) mock = MockDocstringable(docstring) - mock.set_module_docstring("docstring for {0}".format(func.split(".")[0])) + mock.set_module_docstring("docstring for {}".format(func.split(".")[0])) Mockstate.State.states[func] = mock cls._modules = sorted(list(cls._modules)) diff --git a/tests/unit/modules/test_tomcat.py b/tests/unit/modules/test_tomcat.py index 7fc7482fa04..41c0d29821e 100644 --- a/tests/unit/modules/test_tomcat.py +++ b/tests/unit/modules/test_tomcat.py @@ -1,23 +1,7 @@ -# -*- coding: utf-8 -*- +import io +import urllib.request -# Import future libs -from __future__ import absolute_import, print_function, unicode_literals - -# Import 3rd-party libs -from io import BytesIO, StringIO - -# Import salt module import salt.modules.tomcat as tomcat -from salt.ext.six import string_types -from salt.ext.six.moves.urllib.request import ( - HTTPBasicAuthHandler as _HTTPBasicAuthHandler, -) -from salt.ext.six.moves.urllib.request import ( - HTTPDigestAuthHandler as _HTTPDigestAuthHandler, -) -from salt.ext.six.moves.urllib.request import build_opener as _build_opener - -# Import Salt Testing libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, patch from tests.support.unit import TestCase @@ -33,8 +17,8 @@ class TomcatTestCasse(TestCase, LoaderModuleMockMixin): def test_tomcat_wget_no_bytestring(self): responses = { - "string": StringIO("Best response ever\r\nAnd you know it!"), - "bytes": BytesIO(b"Best response ever\r\nAnd you know it!"), + "string": io.StringIO("Best response ever\r\nAnd you know it!"), + "bytes": io.BytesIO(b"Best response ever\r\nAnd you know it!"), } string_mock = MagicMock(return_value=responses["string"]) @@ -42,8 +26,9 @@ class TomcatTestCasse(TestCase, LoaderModuleMockMixin): with patch( "salt.modules.tomcat._auth", MagicMock( - return_value=_build_opener( - _HTTPBasicAuthHandler(), _HTTPDigestAuthHandler() + return_value=urllib.request.build_opener( + urllib.request.HTTPBasicAuthHandler(), + urllib.request.HTTPDigestAuthHandler(), ) ), ): @@ -52,7 +37,7 @@ class TomcatTestCasse(TestCase, LoaderModuleMockMixin): "tomcat.wait", url="http://localhost:8080/nofail" ) for line in response["msg"]: - self.assertIsInstance(line, string_types) + self.assertIsInstance(line, str) with patch("salt.modules.tomcat._urlopen", bytes_mock): try: @@ -69,4 +54,4 @@ class TomcatTestCasse(TestCase, LoaderModuleMockMixin): raise type_error for line in response["msg"]: - self.assertIsInstance(line, string_types) + self.assertIsInstance(line, str) diff --git a/tests/unit/modules/test_twilio_notify.py b/tests/unit/modules/test_twilio_notify.py index a1e966b86c0..3528e04030d 100644 --- a/tests/unit/modules/test_twilio_notify.py +++ b/tests/unit/modules/test_twilio_notify.py @@ -1,15 +1,9 @@ -# -*- coding: utf-8 -*- """ :codeauthor: Jayesh Kariya """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals -# Import Salt Libs import salt.modules.twilio_notify as twilio_notify - -# Import Salt Testing Libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, patch from tests.support.unit import TestCase, skipIf @@ -38,10 +32,10 @@ class MockTwilioRestException(Exception): self.code = "error code" self.msg = "Exception error" self.status = "Not send" - super(MockTwilioRestException, self).__init__(self.msg) + super().__init__(self.msg) -class MockMessages(object): +class MockMessages: """ Mock SMS class """ @@ -73,7 +67,7 @@ class MockMessages(object): return msg -class MockSMS(object): +class MockSMS: """ Mock SMS class """ @@ -82,7 +76,7 @@ class MockSMS(object): self.messages = MockMessages() -class MockTwilioRestClient(object): +class MockTwilioRestClient: """ Mock TwilioRestClient class """ diff --git a/tests/unit/modules/test_useradd.py b/tests/unit/modules/test_useradd.py index 6f9ae2208f8..690654cc1bf 100644 --- a/tests/unit/modules/test_useradd.py +++ b/tests/unit/modules/test_useradd.py @@ -1,16 +1,10 @@ -# -*- coding: utf-8 -*- """ :codeauthor: Jayesh Kariya """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals -# Import Salt Libs import salt.modules.useradd as useradd from salt.exceptions import CommandExecutionError - -# Import Salt Testing Libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, patch from tests.support.unit import TestCase, skipIf diff --git a/tests/unit/modules/test_virt.py b/tests/unit/modules/test_virt.py index fd89716c98c..dd95d216662 100644 --- a/tests/unit/modules/test_virt.py +++ b/tests/unit/modules/test_virt.py @@ -19,7 +19,6 @@ import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError # pylint: disable=import-error -from salt.ext.six.moves import range # pylint: disable=redefined-builtin from tests.support.helpers import dedent from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, patch @@ -1954,8 +1953,7 @@ class VirtTestCase(TestCase, LoaderModuleMockMixin): with patch.dict(virt.__dict__, {"CACHE_DIR": cache_dir}): with patch( - "salt.ext.six.moves.urllib.request.urlopen", - MagicMock(return_value=mock_response), + "urllib.request.urlopen", MagicMock(return_value=mock_response), ): with patch( "salt.utils.files.fopen", return_value=mock_response diff --git a/tests/unit/modules/test_virtualenv_mod.py b/tests/unit/modules/test_virtualenv_mod.py index ba2d309358a..1c562a3432e 100644 --- a/tests/unit/modules/test_virtualenv_mod.py +++ b/tests/unit/modules/test_virtualenv_mod.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ :codeauthor: Pedro Algarvio (pedro@algarvio.me) @@ -8,16 +7,12 @@ """ # Import python libraries -from __future__ import absolute_import, print_function, unicode_literals import sys -# Import salt libs import salt.modules.virtualenv_mod as virtualenv_mod from salt.exceptions import CommandExecutionError from tests.support.helpers import ForceImportErrorOn, TstSuiteLoggingHandler - -# Import Salt Testing libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, patch from tests.support.unit import TestCase @@ -280,7 +275,7 @@ class VirtualenvTestCase(TestCase, LoaderModuleMockMixin): "/tmp/foo", python=sys.executable, ) mock.assert_called_once_with( - ["virtualenv", "--python={0}".format(sys.executable), "/tmp/foo"], + ["virtualenv", "--python={}".format(sys.executable), "/tmp/foo"], runas=None, python_shell=False, ) diff --git a/tests/unit/modules/test_win_groupadd.py b/tests/unit/modules/test_win_groupadd.py index 33c0583812d..316d68a1c84 100644 --- a/tests/unit/modules/test_win_groupadd.py +++ b/tests/unit/modules/test_win_groupadd.py @@ -2,19 +2,14 @@ :codeauthor: Jayesh Kariya """ -# Import Python Libs -# Import Salt Libs import salt.modules.win_groupadd as win_groupadd import salt.utils.win_functions - -# Import Salt Testing Libs from tests.support.helpers import TstSuiteLoggingHandler from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, Mock, patch from tests.support.unit import TestCase, skipIf -# Import Other Libs # pylint: disable=unused-import try: import win32com diff --git a/tests/unit/modules/test_win_system.py b/tests/unit/modules/test_win_system.py index c1c9b1320c4..11fb438b836 100644 --- a/tests/unit/modules/test_win_system.py +++ b/tests/unit/modules/test_win_system.py @@ -1,20 +1,14 @@ -# -*- coding: utf-8 -*- """ :codeauthor: Rahul Handay """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals import types from datetime import datetime -# Import Salt Libs import salt.modules.win_system as win_system import salt.utils.platform import salt.utils.stringutils - -# Import Salt Testing Libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, Mock, patch from tests.support.unit import TestCase, skipIf @@ -27,7 +21,7 @@ except ImportError: HAS_WMI = False -class MockWMI_ComputerSystem(object): +class MockWMI_ComputerSystem: """ Mock WMI Win32_ComputerSystem Class """ @@ -67,7 +61,7 @@ class MockWMI_ComputerSystem(object): return [0] -class MockWMI_OperatingSystem(object): +class MockWMI_OperatingSystem: """ Mock WMI Win32_OperatingSystem Class """ @@ -97,7 +91,7 @@ class MockWMI_ComputerSystemProduct: self.SKUNumber = None -class MockWMI_Processor(object): +class MockWMI_Processor: """ Mock WMI Win32_Processor Class """ @@ -112,7 +106,7 @@ class MockWMI_Processor(object): pass -class MockWMI_BIOS(object): +class MockWMI_BIOS: """ Mock WMI Win32_BIOS Class """ @@ -148,7 +142,7 @@ class WinSystemTestCase(TestCase, LoaderModuleMockMixin): if win_system.HAS_WIN32NET_MODS is False: win32api = types.ModuleType( - str("win32api") # future lint: disable=blacklisted-function + "win32api" # future lint: disable=blacklisted-function ) now = datetime.now() win32api.GetLocalTime = MagicMock( @@ -165,7 +159,7 @@ class WinSystemTestCase(TestCase, LoaderModuleMockMixin): ) modules_globals["win32api"] = win32api win32net = types.ModuleType( - str("win32net") + "win32net" ) # future lint: disable=blacklisted-function win32net.NetServerGetInfo = MagicMock() win32net.NetServerSetInfo = MagicMock() @@ -606,7 +600,7 @@ class WinSystemTestCase(TestCase, LoaderModuleMockMixin): """ # Create a mock processor class that does not have the # NumberOfCoresEnabled property - class MockWMIProcessor(object): + class MockWMIProcessor: """ Mock WMI Win32_Processor Class """ diff --git a/tests/unit/modules/test_zypperpkg.py b/tests/unit/modules/test_zypperpkg.py index 919dbb97373..10714b4adad 100644 --- a/tests/unit/modules/test_zypperpkg.py +++ b/tests/unit/modules/test_zypperpkg.py @@ -3,6 +3,8 @@ """ +import configparser +import io import os from xml.dom import minidom @@ -11,8 +13,6 @@ import salt.modules.zypperpkg as zypper import salt.utils.files import salt.utils.pkg from salt.exceptions import CommandExecutionError -from salt.ext import six -from salt.ext.six.moves import configparser from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, Mock, call, patch from tests.support.unit import TestCase @@ -1516,7 +1516,7 @@ Repository 'DUMMY' not found by its alias, number, or URI. """ repos_cfg = configparser.ConfigParser() for cfg in ["zypper-repo-1.cfg", "zypper-repo-2.cfg"]: - repos_cfg.readfp(six.moves.StringIO(get_test_data(cfg))) + repos_cfg.readfp(io.StringIO(get_test_data(cfg))) for alias in repos_cfg.sections(): r_info = zypper._get_repo_info(alias, repos_cfg=repos_cfg) diff --git a/tests/unit/states/__init__.py b/tests/unit/states/__init__.py index 40a96afc6ff..e69de29bb2d 100644 --- a/tests/unit/states/__init__.py +++ b/tests/unit/states/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/tests/unit/states/test_cron.py b/tests/unit/states/test_cron.py index f3501f8bbfc..d7fe7645adc 100644 --- a/tests/unit/states/test_cron.py +++ b/tests/unit/states/test_cron.py @@ -1,8 +1,6 @@ -# -*- coding: utf-8 -*- """ :codeauthor: Mike Place """ -from __future__ import absolute_import, print_function, unicode_literals import io @@ -45,7 +43,7 @@ class CronTestCase(TestCase, LoaderModuleMockMixin): } def setUp(self): - super(CronTestCase, self).setUp() + super().setUp() self._crontab = io.StringIO() self.addCleanup(delattr, self, "_crontab") self.set_crontab("") diff --git a/tests/unit/states/test_disk.py b/tests/unit/states/test_disk.py index 975f248a601..2e713700a66 100644 --- a/tests/unit/states/test_disk.py +++ b/tests/unit/states/test_disk.py @@ -1,16 +1,10 @@ -# -*- coding: utf-8 -*- """ Tests for disk state """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals from os import path -# Import Salt Libs import salt.states.disk as disk - -# Import Salt Testing Libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, patch from tests.support.unit import TestCase @@ -156,17 +150,13 @@ class DiskTestCase(TestCase, LoaderModuleMockMixin): "data": self.mock_data[mock_fs], } - mock_ret[ - "comment" - ] = "Disk used space is below minimum of {0} % at {1} %".format( + mock_ret["comment"] = "Disk used space is below minimum of {} % at {} %".format( mock_min, mock_used ) ret = disk.status(mock_fs, minimum=mock_min) self.assertEqual(ret, mock_ret) - mock_ret[ - "comment" - ] = "Disk used space is above maximum of {0} % at {1} %".format( + mock_ret["comment"] = "Disk used space is above maximum of {} % at {} %".format( mock_max, mock_used ) ret = disk.status(mock_fs, maximum=mock_max) diff --git a/tests/unit/states/test_grains.py b/tests/unit/states/test_grains.py index 936dcbcf681..d2c8e21e295 100644 --- a/tests/unit/states/test_grains.py +++ b/tests/unit/states/test_grains.py @@ -1,27 +1,18 @@ -# -*- coding: utf-8 -*- """ unit tests for the grains state """ -from __future__ import absolute_import, print_function, unicode_literals import contextlib - -# Import Python libs import os import salt.modules.grains as grainsmod import salt.states.grains as grains - -# Import salt libs import salt.utils.files import salt.utils.stringutils import salt.utils.yaml -from salt.ext import six from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, patch - -# Import Salt Testing libs from tests.support.runtests import RUNTIME_VARS from tests.support.unit import TestCase @@ -340,12 +331,7 @@ class GrainsTestCase(TestCase, LoaderModuleMockMixin): # Force to overwrite a grain to a list ret = grains.present(name="foo", value=["l1", "l2"], force=True) self.assertEqual(ret["result"], True) - self.assertEqual( - ret["comment"], - "Set grain foo to ['l1', 'l2']" - if six.PY3 - else "Set grain foo to [u'l1', u'l2']", - ) + self.assertEqual(ret["comment"], "Set grain foo to ['l1', 'l2']") self.assertEqual(ret["changes"], {"foo": ["l1", "l2"]}) self.assertEqual(grains.__grains__, {"a": "aval", "foo": ["l1", "l2"]}) self.assertGrainFileContent("a: aval\n" + "foo:\n" + "- l1\n" + "- l2\n") @@ -354,12 +340,7 @@ class GrainsTestCase(TestCase, LoaderModuleMockMixin): # Force setting a grain to a dict ret = grains.present(name="foo", value={"k1": "v1"}, force=True) self.assertEqual(ret["result"], True) - self.assertEqual( - ret["comment"], - "Set grain foo to {'k1': 'v1'}" - if six.PY3 - else "Set grain foo to {u'k1': u'v1'}", - ) + self.assertEqual(ret["comment"], "Set grain foo to {'k1': 'v1'}") self.assertEqual(ret["changes"], {"foo": {"k1": "v1"}}) self.assertEqual(grains.__grains__, {"a": "aval", "foo": {"k1": "v1"}}) self.assertGrainFileContent("a: aval\n" + "foo:\n" + " k1: v1\n") @@ -371,12 +352,7 @@ class GrainsTestCase(TestCase, LoaderModuleMockMixin): ) self.assertEqual(ret["result"], True) self.assertEqual(ret["changes"], {"foo": {"is": {"nested": ["l1", "l2"]}}}) - self.assertEqual( - ret["comment"], - "Set grain foo:is:nested to ['l1', 'l2']" - if six.PY3 - else "Set grain foo:is:nested to [u'l1', u'l2']", - ) + self.assertEqual(ret["comment"], "Set grain foo:is:nested to ['l1', 'l2']") self.assertEqual( grains.__grains__, {"a": "aval", "foo": {"is": {"nested": ["l1", "l2"]}}}, @@ -396,12 +372,7 @@ class GrainsTestCase(TestCase, LoaderModuleMockMixin): # Force setting a nested grain to a dict ret = grains.present(name="foo:is:nested", value={"k1": "v1"}, force=True) self.assertEqual(ret["result"], True) - self.assertEqual( - ret["comment"], - "Set grain foo:is:nested to {'k1': 'v1'}" - if six.PY3 - else "Set grain foo:is:nested to {u'k1': u'v1'}", - ) + self.assertEqual(ret["comment"], "Set grain foo:is:nested to {'k1': 'v1'}") self.assertEqual( ret["changes"], {"foo": {"is": {"nested": {"k1": "v1"}}, "and": "other"}}, @@ -447,12 +418,7 @@ class GrainsTestCase(TestCase, LoaderModuleMockMixin): # Converts a value to a nested grain key ret = grains.present(name="foo:is:nested", value={"k1": "v1"}) self.assertEqual(ret["result"], True) - self.assertEqual( - ret["comment"], - "Set grain foo:is:nested to {'k1': 'v1'}" - if six.PY3 - else "Set grain foo:is:nested to {u'k1': u'v1'}", - ) + self.assertEqual(ret["comment"], "Set grain foo:is:nested to {'k1': 'v1'}") self.assertEqual(ret["changes"], {"foo": {"is": {"nested": {"k1": "v1"}}}}) self.assertEqual( grains.__grains__, @@ -466,12 +432,7 @@ class GrainsTestCase(TestCase, LoaderModuleMockMixin): # Converts a list element to a nested grain key ret = grains.present(name="foo:is:nested", value={"k1": "v1"}) self.assertEqual(ret["result"], True) - self.assertEqual( - ret["comment"], - "Set grain foo:is:nested to {'k1': 'v1'}" - if six.PY3 - else "Set grain foo:is:nested to {u'k1': u'v1'}", - ) + self.assertEqual(ret["comment"], "Set grain foo:is:nested to {'k1': 'v1'}") self.assertEqual( ret["changes"], {"foo": ["one", {"is": {"nested": {"k1": "v1"}}}, "correct"]}, diff --git a/tests/unit/states/test_group.py b/tests/unit/states/test_group.py index 065eae4214c..77fb9452d8a 100644 --- a/tests/unit/states/test_group.py +++ b/tests/unit/states/test_group.py @@ -1,16 +1,10 @@ -# -*- coding: utf-8 -*- """ :codeauthor: Rahul Handay """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals -# Import Salt Libs import salt.states.group as group from salt.utils.odict import OrderedDict - -# Import Salt Testing Libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, patch from tests.support.unit import TestCase diff --git a/tests/unit/states/test_heat.py b/tests/unit/states/test_heat.py index 74b3cd0f052..c36bc2e98b5 100644 --- a/tests/unit/states/test_heat.py +++ b/tests/unit/states/test_heat.py @@ -1,8 +1,3 @@ -# -*- coding: utf-8 -*- - -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals - import os import salt.modules.file as file_ @@ -11,11 +6,7 @@ import salt.modules.win_file as win_file import salt.states.heat as heat import salt.utils.platform import salt.utils.win_dacl as dacl - -# Import Salt Libs import tests.unit.modules.test_heat - -# Import Salt Testing Libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, patch from tests.support.runtests import RUNTIME_VARS diff --git a/tests/unit/states/test_ipset.py b/tests/unit/states/test_ipset.py index 75154f6eeca..58630380d6d 100644 --- a/tests/unit/states/test_ipset.py +++ b/tests/unit/states/test_ipset.py @@ -1,14 +1,8 @@ -# -*- coding: utf-8 -*- """ :codeauthor: Jayesh Kariya """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals -# Import Salt Libs import salt.states.ipset as ipset - -# Import Salt Testing Libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, call, patch from tests.support.unit import TestCase @@ -59,7 +53,7 @@ class IpsetSetPresentTestCase(TestCase, LoaderModuleMockMixin): ret = { "name": self.fake_name, "result": True, - "comment": "ipset set {0} already exists for ipv4".format(self.fake_name), + "comment": "ipset set {} already exists for ipv4".format(self.fake_name), "changes": {}, } self._runner(ret, check_set=True, new_set_assertion=False) @@ -72,7 +66,7 @@ class IpsetSetPresentTestCase(TestCase, LoaderModuleMockMixin): ret = { "name": self.fake_name, "result": None, - "comment": "ipset set {0} would be added for ipv4".format(self.fake_name), + "comment": "ipset set {} would be added for ipv4".format(self.fake_name), "changes": {}, } self._runner(ret, test=True, new_set_assertion=False) @@ -81,7 +75,7 @@ class IpsetSetPresentTestCase(TestCase, LoaderModuleMockMixin): ret = { "name": self.fake_name, "result": True, - "comment": "ipset set {0} created successfully for ipv4".format( + "comment": "ipset set {} created successfully for ipv4".format( self.fake_name ), "changes": {"locale": self.fake_name}, @@ -92,7 +86,7 @@ class IpsetSetPresentTestCase(TestCase, LoaderModuleMockMixin): ret = { "name": self.fake_name, "result": False, - "comment": "Failed to create set {0} for ipv4: ".format(self.fake_name), + "comment": "Failed to create set {} for ipv4: ".format(self.fake_name), "changes": {}, } self._runner(ret, new_set="") @@ -148,9 +142,7 @@ class IpsetSetAbsentTestCase(TestCase, LoaderModuleMockMixin): ret = { "name": self.fake_name, "result": True, - "comment": "ipset set {0} for ipv4 is already absent".format( - self.fake_name - ), + "comment": "ipset set {} for ipv4 is already absent".format(self.fake_name), "changes": {}, } self._runner(ret, check_set=False, delete_set=None) @@ -159,7 +151,7 @@ class IpsetSetAbsentTestCase(TestCase, LoaderModuleMockMixin): ret = { "name": self.fake_name, "result": None, - "comment": "ipset set {0} for ipv4 would be removed".format(self.fake_name), + "comment": "ipset set {} for ipv4 would be removed".format(self.fake_name), "changes": {}, } self._runner(ret, test=True, delete_set=None) @@ -168,7 +160,7 @@ class IpsetSetAbsentTestCase(TestCase, LoaderModuleMockMixin): ret = { "name": self.fake_name, "result": False, - "comment": "Failed to delete set {0} for ipv4: ".format(self.fake_name), + "comment": "Failed to delete set {} for ipv4: ".format(self.fake_name), "changes": {}, } self._runner(ret, flush_assertion=True, delete_set_assertion=True) @@ -177,7 +169,7 @@ class IpsetSetAbsentTestCase(TestCase, LoaderModuleMockMixin): ret = { "name": self.fake_name, "result": True, - "comment": "ipset set {0} deleted successfully for family ipv4".format( + "comment": "ipset set {} deleted successfully for family ipv4".format( self.fake_name ), "changes": {"locale": "fake_ipset"}, @@ -253,7 +245,7 @@ class IpsetPresentTestCase(TestCase, LoaderModuleMockMixin): ret = { "name": self.fake_name, "result": False, - "comment": "Failed to add to entry 192.168.1.3 to set {0} for family ipv4.\n" + "comment": "Failed to add to entry 192.168.1.3 to set {} for family ipv4.\n" "Error".format(self.fake_name), "changes": {}, } @@ -351,7 +343,7 @@ class IpsetAbsentTestCase(TestCase, LoaderModuleMockMixin): ret = { "name": self.fake_name, "result": False, - "comment": "Failed to delete ipset entry from set {0} for ipv4. Attempted entry was 192.168.1.3.\n" + "comment": "Failed to delete ipset entry from set {} for ipv4. Attempted entry was 192.168.1.3.\n" "Error\n".format(self.fake_name), "changes": {}, } @@ -412,7 +404,7 @@ class IpsetFlushTestCase(TestCase, LoaderModuleMockMixin): ret = { "name": self.fake_name, "result": False, - "comment": "ipset set {0} does not exist for ipv4".format(self.fake_name), + "comment": "ipset set {} does not exist for ipv4".format(self.fake_name), "changes": {}, } self._runner(ret, check_set=False, flush_assertion=False) @@ -421,7 +413,7 @@ class IpsetFlushTestCase(TestCase, LoaderModuleMockMixin): ret = { "name": self.fake_name, "result": None, - "comment": "ipset entries in set {0} for ipv4 would be flushed".format( + "comment": "ipset entries in set {} for ipv4 would be flushed".format( self.fake_name ), "changes": {}, @@ -432,7 +424,7 @@ class IpsetFlushTestCase(TestCase, LoaderModuleMockMixin): ret = { "name": self.fake_name, "result": False, - "comment": "Failed to flush ipset entries from set {0} for ipv4".format( + "comment": "Failed to flush ipset entries from set {} for ipv4".format( self.fake_name ), "changes": {}, @@ -443,7 +435,7 @@ class IpsetFlushTestCase(TestCase, LoaderModuleMockMixin): ret = { "name": self.fake_name, "result": True, - "comment": "Flushed ipset entries from set {0} for ipv4".format( + "comment": "Flushed ipset entries from set {} for ipv4".format( self.fake_name ), "changes": {"locale": "fake_ipset"}, diff --git a/tests/unit/states/test_syslog_ng.py b/tests/unit/states/test_syslog_ng.py index ea329927fe6..b51b31fec3e 100644 --- a/tests/unit/states/test_syslog_ng.py +++ b/tests/unit/states/test_syslog_ng.py @@ -1,10 +1,7 @@ -# -*- coding: utf-8 -*- """ Test module for syslog_ng state """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import os import re diff --git a/tests/unit/test_zypp_plugins.py b/tests/unit/test_zypp_plugins.py index 7abc74b7939..b2b41bf6acd 100644 --- a/tests/unit/test_zypp_plugins.py +++ b/tests/unit/test_zypp_plugins.py @@ -1,18 +1,10 @@ -# -*- coding: utf-8 -*- """ :codeauthor: Bo Maryniuk """ - -# Import Python Libs -from __future__ import absolute_import - import imp import os -import sys from tests.support.mock import MagicMock, patch - -# Import Salt Testing Libs from tests.support.unit import TestCase, skipIf try: @@ -22,10 +14,7 @@ try: except ImportError: HAS_ZYPP_PLUGIN = False -if sys.version_info >= (3,): - BUILTINS_OPEN = "builtins.open" -else: - BUILTINS_OPEN = "__builtin__.open" +BUILTINS_OPEN = "builtins.open" ZYPPNOTIFY_FILE = os.path.sep.join( os.path.dirname(__file__).split(os.path.sep)[:-2] diff --git a/tests/unit/transport/__init__.py b/tests/unit/transport/__init__.py index 40a96afc6ff..e69de29bb2d 100644 --- a/tests/unit/transport/__init__.py +++ b/tests/unit/transport/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/tests/unit/utils/__init__.py b/tests/unit/utils/__init__.py index 40a96afc6ff..e69de29bb2d 100644 --- a/tests/unit/utils/__init__.py +++ b/tests/unit/utils/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/tests/unit/utils/test_aggregation.py b/tests/unit/utils/test_aggregation.py index 1b7d607bdb4..b1ab53f0f81 100644 --- a/tests/unit/utils/test_aggregation.py +++ b/tests/unit/utils/test_aggregation.py @@ -1,12 +1,4 @@ -# -*- coding: utf-8 -*- - -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals - -# Import salt libs from salt.utils.aggregation import Map, Scalar, aggregate - -# Import Salt Testing libs from tests.support.unit import TestCase diff --git a/tests/unit/utils/test_asynchronous.py b/tests/unit/utils/test_asynchronous.py index 2aebea3fe0c..e5bd974cb62 100644 --- a/tests/unit/utils/test_asynchronous.py +++ b/tests/unit/utils/test_asynchronous.py @@ -1,13 +1,10 @@ -# coding: utf-8 -from __future__ import absolute_import, print_function, unicode_literals - import salt.ext.tornado.gen import salt.ext.tornado.testing import salt.utils.asynchronous as asynchronous from salt.ext.tornado.testing import AsyncTestCase -class HelperA(object): +class HelperA: async_methods = [ "sleep", @@ -22,7 +19,7 @@ class HelperA(object): raise salt.ext.tornado.gen.Return(True) -class HelperB(object): +class HelperB: async_methods = [ "sleep", diff --git a/tests/unit/utils/test_botomod.py b/tests/unit/utils/test_botomod.py index 0705faf954b..fd8a2e90478 100644 --- a/tests/unit/utils/test_botomod.py +++ b/tests/unit/utils/test_botomod.py @@ -1,25 +1,14 @@ -# -*- coding: utf-8 -*- - -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals - import os import salt.utils.boto3mod as boto3mod - -# Import Salt libs import salt.utils.botomod as botomod from salt.exceptions import SaltInvocationError -from salt.ext import six from salt.utils.versions import LooseVersion - -# Import Salt Testing libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, patch from tests.support.runtests import RUNTIME_VARS from tests.support.unit import TestCase, skipIf -# Import 3rd-party libs # pylint: disable=import-error try: import boto @@ -125,7 +114,7 @@ def _has_required_boto3(): else: return True except AttributeError as exc: - if "has no attribute '__version__'" not in six.text_type(exc): + if "has no attribute '__version__'" not in str(exc): raise return False @@ -194,7 +183,7 @@ class BotoUtilsCacheIdTestCase(BotoUtilsTestCaseBase): @skipIf( _has_required_boto() is False, "The boto module must be greater than" - " or equal to version {0}".format(required_boto_version), + " or equal to version {}".format(required_boto_version), ) class BotoUtilsGetConnTestCase(BotoUtilsTestCaseBase): @mock_ec2 @@ -210,7 +199,7 @@ class BotoUtilsGetConnTestCase(BotoUtilsTestCaseBase): @mock_ec2 def test_get_conn_with_no_auth_params_raises_invocation_error(self): with patch( - "boto.{0}.connect_to_region".format(service), + "boto.{}.connect_to_region".format(service), side_effect=boto.exception.NoAuthHandlerFound(), ): with self.assertRaises(SaltInvocationError): @@ -219,7 +208,7 @@ class BotoUtilsGetConnTestCase(BotoUtilsTestCaseBase): @mock_ec2 def test_get_conn_error_raises_command_execution_error(self): with patch( - "boto.{0}.connect_to_region".format(service), + "boto.{}.connect_to_region".format(service), side_effect=BotoServerError(400, "Mocked error", body=error_body), ): with self.assertRaises(BotoServerError): @@ -236,7 +225,7 @@ class BotoUtilsGetConnTestCase(BotoUtilsTestCaseBase): @skipIf( _has_required_boto() is False, "The boto module must be greater than" - " or equal to version {0}".format(required_boto_version), + " or equal to version {}".format(required_boto_version), ) class BotoUtilsGetErrorTestCase(BotoUtilsTestCaseBase): def test_error_message(self): @@ -276,13 +265,13 @@ class BotoUtilsGetErrorTestCase(BotoUtilsTestCaseBase): @skipIf( _has_required_boto() is False, "The boto module must be greater than" - " or equal to version {0}".format(required_boto_version), + " or equal to version {}".format(required_boto_version), ) @skipIf(HAS_BOTO3 is False, "The boto3 module must be installed.") @skipIf( _has_required_boto3() is False, "The boto3 module must be greater than" - " or equal to version {0}".format(required_boto3_version), + " or equal to version {}".format(required_boto3_version), ) class BotoBoto3CacheContextCollisionTest(BotoUtilsTestCaseBase): def test_context_conflict_between_boto_and_boto3_utils(self): diff --git a/tests/unit/utils/test_color.py b/tests/unit/utils/test_color.py index 5f0e2f17c97..b80b2e4eaf1 100644 --- a/tests/unit/utils/test_color.py +++ b/tests/unit/utils/test_color.py @@ -1,29 +1,20 @@ -# -*- coding: utf-8 -*- """ Unit tests for salt.utils.color.py """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals -# Import Salt libs import salt.utils.color -from salt.ext import six - -# Import Salt Testing libs from tests.support.unit import TestCase class ColorUtilsTestCase(TestCase): def test_get_colors(self): ret = salt.utils.color.get_colors() - self.assertEqual("\x1b[0;37m", six.text_type(ret["LIGHT_GRAY"])) + self.assertEqual("\x1b[0;37m", str(ret["LIGHT_GRAY"])) ret = salt.utils.color.get_colors(use=False) self.assertDictContainsSubset({"LIGHT_GRAY": ""}, ret) ret = salt.utils.color.get_colors(use="LIGHT_GRAY") # LIGHT_YELLOW now == LIGHT_GRAY - self.assertEqual( - six.text_type(ret["LIGHT_YELLOW"]), six.text_type(ret["LIGHT_GRAY"]) - ) + self.assertEqual(str(ret["LIGHT_YELLOW"]), str(ret["LIGHT_GRAY"])) diff --git a/tests/unit/utils/test_configcomparer.py b/tests/unit/utils/test_configcomparer.py index ee1205f4ab0..f2b922c69f8 100644 --- a/tests/unit/utils/test_configcomparer.py +++ b/tests/unit/utils/test_configcomparer.py @@ -1,14 +1,6 @@ -# -*- coding: utf-8 -*- - -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals - import copy -# Import Salt libs import salt.utils.configcomparer as configcomparer - -# Import Salt Testing libs from tests.support.unit import TestCase diff --git a/tests/unit/utils/test_configparser.py b/tests/unit/utils/test_configparser.py index cffc2f7d205..8f33acff014 100644 --- a/tests/unit/utils/test_configparser.py +++ b/tests/unit/utils/test_configparser.py @@ -1,12 +1,9 @@ -# -*- coding: utf-8 -*- """ tests.unit.utils.test_configparser ================================== Test the funcs in the custom parsers in salt.utils.configparser """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals import copy import errno @@ -14,14 +11,9 @@ import logging import os import salt.utils.configparser - -# Import salt libs import salt.utils.files import salt.utils.platform import salt.utils.stringutils -from salt.ext import six - -# Import Salt Testing Libs from tests.support.runtests import RUNTIME_VARS from tests.support.unit import TestCase @@ -111,7 +103,7 @@ class TestGitConfigParser(TestCase): def _test_write(self, mode): kwargs = {"mode": mode} - if six.PY3 and salt.utils.platform.is_windows() and "b" not in mode: + if salt.utils.platform.is_windows() and "b" not in mode: kwargs["encoding"] = "utf-8" with salt.utils.files.fopen(self.new_config, **kwargs) as fp_: self.conf.write(fp_) diff --git a/tests/unit/utils/test_dateutils.py b/tests/unit/utils/test_dateutils.py index 4536f046398..666855c630e 100644 --- a/tests/unit/utils/test_dateutils.py +++ b/tests/unit/utils/test_dateutils.py @@ -1,21 +1,14 @@ -# -*- coding: utf-8 -*- """ Tests for salt.utils.dateutils """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import datetime -# Import Salt libs import salt.utils.dateutils from tests.support.mock import patch - -# Import Salt Testing libs from tests.support.unit import TestCase, skipIf -# Import 3rd-party libs try: import timelib # pylint: disable=import-error,unused-import diff --git a/tests/unit/utils/test_dicttrim.py b/tests/unit/utils/test_dicttrim.py index 573aeaed207..ef08009bf33 100644 --- a/tests/unit/utils/test_dicttrim.py +++ b/tests/unit/utils/test_dicttrim.py @@ -1,14 +1,6 @@ -# -*- coding: utf-8 -*- - -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals - import logging -# Import Salt libs import salt.utils.dicttrim as dicttrimmer - -# Import Salt Testing libs from tests.support.unit import TestCase log = logging.getLogger(__name__) diff --git a/tests/unit/utils/test_dictupdate.py b/tests/unit/utils/test_dictupdate.py index 70f3099ceff..b68f7ea7905 100644 --- a/tests/unit/utils/test_dictupdate.py +++ b/tests/unit/utils/test_dictupdate.py @@ -1,16 +1,8 @@ -# -*- coding: utf-8 -*- - -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals - import copy -# Import Salt libs import salt.utils.dictupdate as dictupdate from salt.exceptions import SaltInvocationError from salt.utils.odict import OrderedDict - -# Import Salt Testing libs from tests.support.unit import TestCase diff --git a/tests/unit/utils/test_doc.py b/tests/unit/utils/test_doc.py index 6765fdf7a2d..244a5e18cae 100644 --- a/tests/unit/utils/test_doc.py +++ b/tests/unit/utils/test_doc.py @@ -1,15 +1,9 @@ -# -*- coding: utf-8 -*- """ Unit Tests for functions located in salt.utils.doc.py. """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals -# Import Salt libs import salt.utils.doc - -# Import Salt Testing libs from tests.support.unit import TestCase diff --git a/tests/unit/utils/test_dockermod.py b/tests/unit/utils/test_dockermod.py index 663bc3be7d3..42e7b5e1917 100644 --- a/tests/unit/utils/test_dockermod.py +++ b/tests/unit/utils/test_dockermod.py @@ -1,37 +1,28 @@ -# -*- coding: utf-8 -*- """ tests.unit.utils.test_dockermod =============================== Test the funcs in salt.utils.dockermod and salt.utils.dockermod.translate """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals import copy import functools import logging import os -# Import salt libs import salt.config import salt.loader import salt.utils.dockermod.translate.container import salt.utils.dockermod.translate.network import salt.utils.platform from salt.exceptions import CommandExecutionError - -# Import 3rd-party libs -from salt.ext import six from salt.utils.dockermod.translate import helpers as translate_helpers - -# Import Salt Testing Libs from tests.support.unit import TestCase log = logging.getLogger(__name__) -class Assert(object): +class Assert: def __init__(self, translator): self.translator = translator @@ -129,7 +120,7 @@ class Assert(object): ) if alias is not None: # Test collision - test_kwargs = {name: vals, alias: "hello{0}world".format(delimiter)} + test_kwargs = {name: vals, alias: "hello{}world".format(delimiter)} testcase.assertEqual( salt.utils.dockermod.translate_input( self.translator, @@ -357,8 +348,7 @@ class assert_dict(Assert): # "Dictlist" input from states testcase.assertEqual( salt.utils.dockermod.translate_input( - self.translator, - **{item: [{x: y} for x, y in six.iteritems(expected)]} + self.translator, **{item: [{x: y} for x, y in expected.items()]} ), testcase.apply_defaults({name: expected}), ) @@ -512,10 +502,10 @@ class assert_device_rates(Assert): path = os.path.join("foo", "bar", "baz") with testcase.assertRaisesRegex( CommandExecutionError, - "Path '{0}' is not absolute".format(path.replace("\\", "\\\\")), + "Path '{}' is not absolute".format(path.replace("\\", "\\\\")), ): salt.utils.dockermod.translate_input( - self.translator, **{item: "{0}:1048576".format(path)} + self.translator, **{item: "{}:1048576".format(path)} ) if name.endswith("_bps"): @@ -671,7 +661,7 @@ class assert_subnet(Assert): ): log.debug("Verifying '%s' is not a valid subnet", val) with testcase.assertRaisesRegex( - CommandExecutionError, "'{0}' is not a valid subnet".format(val) + CommandExecutionError, "'{}' is not a valid subnet".format(val) ): salt.utils.dockermod.translate_input( self.translator, validate_ip_addrs=True, **{item: val} @@ -712,7 +702,7 @@ class TranslateBase(TestCase): def apply_defaults(self, ret, skip_translate=None): if skip_translate is not True: defaults = getattr(self.translator, "DEFAULTS", {}) - for key, val in six.iteritems(defaults): + for key, val in defaults.items(): if key not in ret: ret[key] = val return ret @@ -733,7 +723,7 @@ class TranslateBase(TestCase): tcp_ports = [] udp_ports = [] for item in ret[0]["ports"]: - if isinstance(item, six.integer_types): + if isinstance(item, int): tcp_ports.append(item) else: udp_ports.append(item) @@ -780,7 +770,7 @@ class TranslateContainerInputTestCase(TranslateBase): tcp_ports = [] udp_ports = [] for item in ret["ports"]: - if isinstance(item, six.integer_types): + if isinstance(item, int): tcp_ports.append(item) else: udp_ports.append(item) @@ -1729,7 +1719,7 @@ class TranslateContainerInputTestCase(TranslateBase): path = os.path.join("foo", "bar", "baz") with self.assertRaisesRegex( CommandExecutionError, - "'{0}' is not an absolute path".format(path.replace("\\", "\\\\")), + "'{}' is not an absolute path".format(path.replace("\\", "\\\\")), ): salt.utils.dockermod.translate_input(self.translator, volumes=path) @@ -1748,7 +1738,7 @@ class TranslateContainerInputTestCase(TranslateBase): path = os.path.join("foo", "bar", "baz") with self.assertRaisesRegex( CommandExecutionError, - "'{0}' is not an absolute path".format(path.replace("\\", "\\\\")), + "'{}' is not an absolute path".format(path.replace("\\", "\\\\")), ): salt.utils.dockermod.translate_input(self.translator, working_dir=path) @@ -1924,7 +1914,7 @@ class TranslateNetworkInputTestCase(TranslateBase): for val in self.ip_addrs[False]: with self.assertRaisesRegex( - CommandExecutionError, "'{0}' is not a valid IP address".format(val) + CommandExecutionError, "'{}' is not a valid IP address".format(val) ): salt.utils.dockermod.translate_input( self.translator, validate_ip_addrs=True, gateway=val, @@ -1934,11 +1924,7 @@ class TranslateNetworkInputTestCase(TranslateBase): self.translator, validate_ip_addrs=False, gateway=val, ), self.apply_defaults( - { - "gateway": val - if isinstance(val, six.string_types) - else six.text_type(val) - } + {"gateway": val if isinstance(val, str) else str(val)} ), ) @@ -1962,7 +1948,7 @@ class TranslateNetworkInputTestCase(TranslateBase): for val in self.ip_addrs[False]: addresses = {"foo.bar.tld": val} with self.assertRaisesRegex( - CommandExecutionError, "'{0}' is not a valid IP address".format(val) + CommandExecutionError, "'{}' is not a valid IP address".format(val) ): salt.utils.dockermod.translate_input( self.translator, validate_ip_addrs=True, **{item: addresses} diff --git a/tests/unit/utils/test_environment.py b/tests/unit/utils/test_environment.py index 8e4339fbf86..0420641e517 100644 --- a/tests/unit/utils/test_environment.py +++ b/tests/unit/utils/test_environment.py @@ -1,8 +1,6 @@ -# coding=utf-8 """ Test case for utils/__init__.py """ -from __future__ import absolute_import, print_function, unicode_literals import salt.utils.environment from tests.support.unit import TestCase, skipIf diff --git a/tests/unit/utils/test_extend.py b/tests/unit/utils/test_extend.py index 37f9e9135fa..d276d6989d8 100644 --- a/tests/unit/utils/test_extend.py +++ b/tests/unit/utils/test_extend.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ tests.unit.utils.extend_test ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -6,20 +5,15 @@ Test the salt extend script, leave templates/test alone to keep this working! """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import os import shutil from datetime import date -# Import salt libs import salt.utils.extend import salt.utils.files from tests.support.mock import MagicMock, patch from tests.support.runtests import RUNTIME_VARS - -# Import Salt Testing libs from tests.support.unit import TestCase, skipIf diff --git a/tests/unit/utils/test_filebuffer.py b/tests/unit/utils/test_filebuffer.py index e9f77bb4152..b88a2f4fc56 100644 --- a/tests/unit/utils/test_filebuffer.py +++ b/tests/unit/utils/test_filebuffer.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ :codeauthor: Pedro Algarvio (pedro@algarvio.me) @@ -7,16 +6,11 @@ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import os -# Import salt libs from salt.utils.filebuffer import BufferedReader, InvalidFileMode from tests.support.paths import BASE_FILES - -# Import Salt Testing libs from tests.support.unit import TestCase @@ -48,7 +42,7 @@ class TestFileBuffer(TestCase): if stripped_text in chunk: return True return False - except (IOError, OSError): + except OSError: return False self.assertTrue(find_value("We have the Holy Hand Grenade")) diff --git a/tests/unit/utils/test_find.py b/tests/unit/utils/test_find.py index 6f4b5dbed46..d591ff96b95 100644 --- a/tests/unit/utils/test_find.py +++ b/tests/unit/utils/test_find.py @@ -1,23 +1,11 @@ -# -*- coding: utf-8 -*- - -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals - import os import shutil import stat import sys import tempfile -# Import salt libs import salt.utils.files import salt.utils.find -from salt.ext import six - -# Import 3rd-party libs -from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin - -# Import Salt Testing libs from tests.support.runtests import RUNTIME_VARS from tests.support.unit import TestCase, skipIf @@ -272,12 +260,12 @@ class TestFind(TestCase): class TestGrepOption(TestCase): def setUp(self): - super(TestGrepOption, self).setUp() + super().setUp() self.tmpdir = tempfile.mkdtemp(dir=RUNTIME_VARS.TMP) def tearDown(self): shutil.rmtree(self.tmpdir) - super(TestGrepOption, self).tearDown() + super().tearDown() def test_grep_option_requires(self): self.assertRaises(ValueError, salt.utils.find.GrepOption, "grep", "(foo)|(bar}") @@ -310,12 +298,12 @@ class TestGrepOption(TestCase): class TestPrintOption(TestCase): def setUp(self): - super(TestPrintOption, self).setUp() + super().setUp() self.tmpdir = tempfile.mkdtemp(dir=RUNTIME_VARS.TMP) def tearDown(self): shutil.rmtree(self.tmpdir) - super(TestPrintOption, self).tearDown() + super().tearDown() def test_print_option_defaults(self): option = salt.utils.find.PrintOption("print", "") @@ -411,25 +399,21 @@ class TestPrintOption(TestCase): class TestFinder(TestCase): def setUp(self): - super(TestFinder, self).setUp() + super().setUp() self.tmpdir = tempfile.mkdtemp(dir=RUNTIME_VARS.TMP) def tearDown(self): shutil.rmtree(self.tmpdir) - super(TestFinder, self).tearDown() + super().tearDown() @skipIf(sys.platform.startswith("win"), "No /dev/null on Windows") def test_init(self): finder = salt.utils.find.Finder({}) - self.assertEqual( - six.text_type(finder.actions[0].__class__)[-13:-2], "PrintOption" - ) + self.assertEqual(str(finder.actions[0].__class__)[-13:-2], "PrintOption") self.assertEqual(finder.criteria, []) finder = salt.utils.find.Finder({"_": None}) - self.assertEqual( - six.text_type(finder.actions[0].__class__)[-13:-2], "PrintOption" - ) + self.assertEqual(str(finder.actions[0].__class__)[-13:-2], "PrintOption") self.assertEqual(finder.criteria, []) self.assertRaises(ValueError, salt.utils.find.Finder, {"": None}) @@ -437,93 +421,51 @@ class TestFinder(TestCase): self.assertRaises(ValueError, salt.utils.find.Finder, {"nonexist": "somevalue"}) finder = salt.utils.find.Finder({"name": "test_name"}) - self.assertEqual( - six.text_type(finder.actions[0].__class__)[-13:-2], "PrintOption" - ) - self.assertEqual( - six.text_type(finder.criteria[0].__class__)[-12:-2], "NameOption" - ) + self.assertEqual(str(finder.actions[0].__class__)[-13:-2], "PrintOption") + self.assertEqual(str(finder.criteria[0].__class__)[-12:-2], "NameOption") finder = salt.utils.find.Finder({"iname": "test_name"}) - self.assertEqual( - six.text_type(finder.actions[0].__class__)[-13:-2], "PrintOption" - ) - self.assertEqual( - six.text_type(finder.criteria[0].__class__)[-13:-2], "InameOption" - ) + self.assertEqual(str(finder.actions[0].__class__)[-13:-2], "PrintOption") + self.assertEqual(str(finder.criteria[0].__class__)[-13:-2], "InameOption") finder = salt.utils.find.Finder({"regex": r".*\.txt"}) - self.assertEqual( - six.text_type(finder.actions[0].__class__)[-13:-2], "PrintOption" - ) - self.assertEqual( - six.text_type(finder.criteria[0].__class__)[-13:-2], "RegexOption" - ) + self.assertEqual(str(finder.actions[0].__class__)[-13:-2], "PrintOption") + self.assertEqual(str(finder.criteria[0].__class__)[-13:-2], "RegexOption") finder = salt.utils.find.Finder({"iregex": r".*\.txt"}) - self.assertEqual( - six.text_type(finder.actions[0].__class__)[-13:-2], "PrintOption" - ) - self.assertEqual( - six.text_type(finder.criteria[0].__class__)[-14:-2], "IregexOption" - ) + self.assertEqual(str(finder.actions[0].__class__)[-13:-2], "PrintOption") + self.assertEqual(str(finder.criteria[0].__class__)[-14:-2], "IregexOption") finder = salt.utils.find.Finder({"type": "d"}) - self.assertEqual( - six.text_type(finder.actions[0].__class__)[-13:-2], "PrintOption" - ) - self.assertEqual( - six.text_type(finder.criteria[0].__class__)[-12:-2], "TypeOption" - ) + self.assertEqual(str(finder.actions[0].__class__)[-13:-2], "PrintOption") + self.assertEqual(str(finder.criteria[0].__class__)[-12:-2], "TypeOption") finder = salt.utils.find.Finder({"owner": "root"}) - self.assertEqual( - six.text_type(finder.actions[0].__class__)[-13:-2], "PrintOption" - ) - self.assertEqual( - six.text_type(finder.criteria[0].__class__)[-13:-2], "OwnerOption" - ) + self.assertEqual(str(finder.actions[0].__class__)[-13:-2], "PrintOption") + self.assertEqual(str(finder.criteria[0].__class__)[-13:-2], "OwnerOption") if sys.platform.startswith(("darwin", "freebsd", "openbsd")): group_name = "wheel" else: group_name = "root" finder = salt.utils.find.Finder({"group": group_name}) - self.assertEqual( - six.text_type(finder.actions[0].__class__)[-13:-2], "PrintOption" - ) - self.assertEqual( - six.text_type(finder.criteria[0].__class__)[-13:-2], "GroupOption" - ) + self.assertEqual(str(finder.actions[0].__class__)[-13:-2], "PrintOption") + self.assertEqual(str(finder.criteria[0].__class__)[-13:-2], "GroupOption") finder = salt.utils.find.Finder({"size": "+1G"}) - self.assertEqual( - six.text_type(finder.actions[0].__class__)[-13:-2], "PrintOption" - ) - self.assertEqual( - six.text_type(finder.criteria[0].__class__)[-12:-2], "SizeOption" - ) + self.assertEqual(str(finder.actions[0].__class__)[-13:-2], "PrintOption") + self.assertEqual(str(finder.criteria[0].__class__)[-12:-2], "SizeOption") finder = salt.utils.find.Finder({"mtime": "1d"}) - self.assertEqual( - six.text_type(finder.actions[0].__class__)[-13:-2], "PrintOption" - ) - self.assertEqual( - six.text_type(finder.criteria[0].__class__)[-13:-2], "MtimeOption" - ) + self.assertEqual(str(finder.actions[0].__class__)[-13:-2], "PrintOption") + self.assertEqual(str(finder.criteria[0].__class__)[-13:-2], "MtimeOption") finder = salt.utils.find.Finder({"grep": "foo"}) - self.assertEqual( - six.text_type(finder.actions[0].__class__)[-13:-2], "PrintOption" - ) - self.assertEqual( - six.text_type(finder.criteria[0].__class__)[-12:-2], "GrepOption" - ) + self.assertEqual(str(finder.actions[0].__class__)[-13:-2], "PrintOption") + self.assertEqual(str(finder.criteria[0].__class__)[-12:-2], "GrepOption") finder = salt.utils.find.Finder({"print": "name"}) - self.assertEqual( - six.text_type(finder.actions[0].__class__)[-13:-2], "PrintOption" - ) + self.assertEqual(str(finder.actions[0].__class__)[-13:-2], "PrintOption") self.assertEqual(finder.criteria, []) def test_find(self): diff --git a/tests/unit/utils/test_hashutils.py b/tests/unit/utils/test_hashutils.py index 3bcc12c4d5e..5cf11c114ef 100644 --- a/tests/unit/utils/test_hashutils.py +++ b/tests/unit/utils/test_hashutils.py @@ -1,12 +1,4 @@ -# -*- coding: utf-8 -*- - -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals - -# Import Salt libs import salt.utils.hashutils - -# Import Salt Testing libs from tests.support.unit import TestCase diff --git a/tests/unit/utils/test_immutabletypes.py b/tests/unit/utils/test_immutabletypes.py index 3cc960b4310..745f9b933ed 100644 --- a/tests/unit/utils/test_immutabletypes.py +++ b/tests/unit/utils/test_immutabletypes.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ :codeauthor: Pedro Algarvio (pedro@algarvio.me) @@ -9,13 +8,8 @@ Test salt.utils.immutabletypes """ -# Import Python libs -from __future__ import absolute_import, unicode_literals -# Import salt libs import salt.utils.immutabletypes as immutabletypes - -# Import Salt Testing libs from tests.support.unit import TestCase diff --git a/tests/unit/utils/test_job.py b/tests/unit/utils/test_job.py index 957a153d88b..3d25719ade3 100644 --- a/tests/unit/utils/test_job.py +++ b/tests/unit/utils/test_job.py @@ -1,25 +1,15 @@ -# -*- coding: utf-8 -*- """ unit tests for salt.utils.job """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals import salt.minion - -# Import Salt Libs import salt.utils.job as job - -# Import 3rd-party libs -from salt.ext import six - -# Import Salt Testing Libs from tests.support.mock import patch -from tests.support.unit import TestCase, skipIf +from tests.support.unit import TestCase -class MockMasterMinion(object): +class MockMasterMinion: def return_mock_jobs(self): return self.mock_jobs_cache @@ -41,7 +31,6 @@ class JobTest(TestCase): Validate salt.utils.job """ - @skipIf(not six.PY3, "Can only assertLogs in PY3") def test_store_job_exception_handled(self): """ test store_job exception handling diff --git a/tests/unit/utils/test_kickstart.py b/tests/unit/utils/test_kickstart.py index 35dc9223910..acfa1b10df8 100644 --- a/tests/unit/utils/test_kickstart.py +++ b/tests/unit/utils/test_kickstart.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, unicode_literals - import salt.utils.kickstart as kickstart from tests.support.unit import TestCase diff --git a/tests/unit/utils/test_locales.py b/tests/unit/utils/test_locales.py index 3d4d81310df..5cbdb50257a 100644 --- a/tests/unit/utils/test_locales.py +++ b/tests/unit/utils/test_locales.py @@ -1,13 +1,6 @@ -# coding: utf-8 +import imp -# Import Python libs -from __future__ import absolute_import, unicode_literals - -# Import Salt libs import salt.utils.locales as locales - -# Import 3rd-part libs -from salt.ext.six.moves import reload_module from tests.support.mock import patch from tests.support.unit import TestCase @@ -16,12 +9,12 @@ class TestLocales(TestCase): def test_get_encodings(self): # reload locales modules before and after to defeat memoization of # get_encodings() - reload_module(locales) + imp.reload(locales) with patch("sys.getdefaultencoding", return_value="xyzzy"): encodings = locales.get_encodings() for enc in (__salt_system_encoding__, "xyzzy", "utf-8", "latin-1"): self.assertIn(enc, encodings) - reload_module(locales) + imp.reload(locales) def test_split_locale(self): self.assertDictEqual( diff --git a/tests/unit/utils/test_master.py b/tests/unit/utils/test_master.py index 8e357a3fecf..d6ad8db91f2 100644 --- a/tests/unit/utils/test_master.py +++ b/tests/unit/utils/test_master.py @@ -1,13 +1,5 @@ -# -*- coding: utf-8 -*- - -# Import python libs -from __future__ import absolute_import, unicode_literals - -# Import Salt Libs import salt.utils.master from tests.support.mock import patch - -# Import Salt Testing Libs from tests.support.unit import TestCase diff --git a/tests/unit/utils/test_minion.py b/tests/unit/utils/test_minion.py index 41a94b75c24..f0c2608fc02 100644 --- a/tests/unit/utils/test_minion.py +++ b/tests/unit/utils/test_minion.py @@ -1,12 +1,7 @@ -# Import python libs - import logging -# Import Salt Libs import salt.utils.minion from tests.support.mock import MagicMock, mock_open, patch - -# Import Salt Testing Libs from tests.support.unit import TestCase log = logging.getLogger(__name__) diff --git a/tests/unit/utils/test_minions.py b/tests/unit/utils/test_minions.py index 24962d59310..0c5d06338fb 100644 --- a/tests/unit/utils/test_minions.py +++ b/tests/unit/utils/test_minions.py @@ -1,15 +1,7 @@ -# -*- coding: utf-8 -*- - -# Import python libs -from __future__ import absolute_import, unicode_literals - import sys -# Import Salt Libs import salt.utils.minions from tests.support.mock import MagicMock, patch - -# Import Salt Testing Libs from tests.support.unit import TestCase, skipIf NODEGROUPS = { diff --git a/tests/unit/utils/test_msgpack.py b/tests/unit/utils/test_msgpack.py index 3c5f54dd3f7..db26f8ca884 100644 --- a/tests/unit/utils/test_msgpack.py +++ b/tests/unit/utils/test_msgpack.py @@ -9,7 +9,6 @@ import sys from io import BytesIO import salt.utils.msgpack -from salt.ext.six.moves import range from salt.utils.odict import OrderedDict from tests.support.unit import TestCase, skipIf diff --git a/tests/unit/utils/test_path.py b/tests/unit/utils/test_path.py index 4967533b6f1..36eb9449022 100644 --- a/tests/unit/utils/test_path.py +++ b/tests/unit/utils/test_path.py @@ -1,10 +1,7 @@ -# -*- coding: utf-8 -*- """ Tests for salt.utils.path """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import ntpath import os @@ -13,17 +10,11 @@ import posixpath import sys import tempfile -# Import Salt libs import salt.utils.compat import salt.utils.path import salt.utils.platform from salt.exceptions import CommandNotFoundError - -# Import 3rd-party libs -from salt.ext import six from tests.support.mock import patch - -# Import Salt Testing libs from tests.support.unit import TestCase, skipIf @@ -55,9 +46,7 @@ class PathJoinTestCase(TestCase): ) for idx, (parts, expected) in enumerate(self.NIX_PATHS): path = salt.utils.path.join(*parts) - self.assertEqual( - "{0}: {1}".format(idx, path), "{0}: {1}".format(idx, expected) - ) + self.assertEqual("{}: {}".format(idx, path), "{}: {}".format(idx, expected)) @skipIf(True, "Skipped until properly mocked") def test_windows_paths(self): @@ -69,9 +58,7 @@ class PathJoinTestCase(TestCase): for idx, (parts, expected) in enumerate(self.WIN_PATHS): path = salt.utils.path.join(*parts) - self.assertEqual( - "{0}: {1}".format(idx, path), "{0}: {1}".format(idx, expected) - ) + self.assertEqual("{}: {}".format(idx, path), "{}: {}".format(idx, expected)) @skipIf(True, "Skipped until properly mocked") def test_windows_paths_patched_path_module(self): @@ -85,9 +72,7 @@ class PathJoinTestCase(TestCase): for idx, (parts, expected) in enumerate(self.WIN_PATHS): path = salt.utils.path.join(*parts) - self.assertEqual( - "{0}: {1}".format(idx, path), "{0}: {1}".format(idx, expected) - ) + self.assertEqual("{}: {}".format(idx, path), "{}: {}".format(idx, expected)) self.__unpatch_path() @@ -117,7 +102,7 @@ class PathJoinTestCase(TestCase): code = """'''Salt unittest loaded NT module'''""" module = imp.new_module("nt") - six.exec_(code, module.__dict__) + exec(code, module.__dict__) sys.modules["nt"] = module sys.builtin_module_names = modules diff --git a/tests/unit/utils/test_pbm.py b/tests/unit/utils/test_pbm.py index 7f81385a102..768bb2c786e 100644 --- a/tests/unit/utils/test_pbm.py +++ b/tests/unit/utils/test_pbm.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ :codeauthor: :email:`Alexandru Bleotu ` @@ -6,7 +5,6 @@ """ # Import python libraries -from __future__ import absolute_import, print_function, unicode_literals import logging @@ -18,7 +16,6 @@ from salt.exceptions import ( VMwareObjectRetrievalError, VMwareRuntimeError, ) -from salt.ext.six.moves import range from tests.support.mock import MagicMock, PropertyMock, patch # Import Salt testing libraries @@ -355,7 +352,7 @@ class GetStoragePoliciesTestCase(TestCase): resourceType=pbm.profile.ResourceTypeEnum.STORAGE ) ) - mock_obj.name = "fake_policy{0}".format(i) + mock_obj.name = "fake_policy{}".format(i) self.mock_policies.append(mock_obj) patches = ( ( diff --git a/tests/unit/utils/test_proxy.py b/tests/unit/utils/test_proxy.py index 6d77cd70c27..1c9a34ede31 100644 --- a/tests/unit/utils/test_proxy.py +++ b/tests/unit/utils/test_proxy.py @@ -1,10 +1,8 @@ -# -*- coding: utf-8 -*- """ Unit tests for salt.utils.proxy :codeauthor: :email:`Gareth J. Greenaway ` """ -from __future__ import absolute_import, print_function, unicode_literals import salt.utils.proxy from tests.support.mock import patch diff --git a/tests/unit/utils/test_reactor.py b/tests/unit/utils/test_reactor.py index 624d8472689..b83308cedbf 100644 --- a/tests/unit/utils/test_reactor.py +++ b/tests/unit/utils/test_reactor.py @@ -1,7 +1,3 @@ -# -*- coding: utf-8 -*- - -from __future__ import absolute_import, print_function, unicode_literals - import codecs import glob import logging diff --git a/tests/unit/utils/test_roster_matcher.py b/tests/unit/utils/test_roster_matcher.py index 51fe66ceaba..388a4f90edf 100644 --- a/tests/unit/utils/test_roster_matcher.py +++ b/tests/unit/utils/test_roster_matcher.py @@ -1,20 +1,13 @@ -# -*- coding: utf-8 -*- - """ Test generic roster matching utility. """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import os -# Import Salt Libs import salt.config import salt.loader import salt.utils.roster_matcher - -# Import Salt Testing Libs from tests.support import mixins from tests.support.runtests import RUNTIME_VARS from tests.support.unit import TestCase, skipIf diff --git a/tests/unit/utils/test_sanitizers.py b/tests/unit/utils/test_sanitizers.py index 008119aedae..1b2984f1a41 100644 --- a/tests/unit/utils/test_sanitizers.py +++ b/tests/unit/utils/test_sanitizers.py @@ -1,14 +1,4 @@ -# -*- coding: utf-8 -*- - -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals - -from salt.ext.six import text_type as text - -# Import Salt Libs from salt.utils.sanitizers import clean, mask_args_value - -# Import Salt Testing Libs from tests.support.unit import TestCase @@ -24,7 +14,7 @@ class SanitizersTestCase(TestCase): value = " sample " response = clean.trim(value) assert response == "sample" - assert type(response) == text + assert type(response) == str def test_sanitized_filename(self): """ diff --git a/tests/unit/utils/test_sdb.py b/tests/unit/utils/test_sdb.py index dbaac31dd6f..87886cbc521 100644 --- a/tests/unit/utils/test_sdb.py +++ b/tests/unit/utils/test_sdb.py @@ -1,18 +1,12 @@ -# -*- coding: utf-8 -*- """ :codeauthor: :email:`Vernon Cole ` """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals import os -# Import Salt Libs import salt.utils.sdb as sdb from tests.support.mixins import LoaderModuleMockMixin - -# Import Salt Testing Libs from tests.support.runtests import RUNTIME_VARS from tests.support.unit import TestCase diff --git a/tests/unit/utils/test_ssdp.py b/tests/unit/utils/test_ssdp.py index d37facc98bc..df26173847c 100644 --- a/tests/unit/utils/test_ssdp.py +++ b/tests/unit/utils/test_ssdp.py @@ -1,15 +1,11 @@ -# -*- coding: utf-8 -*- """ :codeauthor: :email:`Bo Maryniuk ` """ -from __future__ import absolute_import, print_function, unicode_literals import datetime import salt.utils.ssdp as ssdp import salt.utils.stringutils -from salt.ext import six -from salt.ext.six.moves import zip from tests.support.mock import MagicMock, patch from tests.support.unit import TestCase, skipIf @@ -19,7 +15,7 @@ except ImportError: pytest = None -class Mocks(object): +class Mocks: def get_socket_mock(self, expected_ip, expected_hostname): """ Get a mock of a socket @@ -90,7 +86,7 @@ class SSDPBaseTestCase(TestCase, Mocks): Side effect :return: """ - raise AttributeError("attribute error: {0}. {1}".format(args, kwargs)) + raise AttributeError("attribute error: {}. {}".format(args, kwargs)) @patch("salt.utils.ssdp._json", None) @patch("salt.utils.ssdp.asyncio", None) @@ -462,7 +458,7 @@ class SSDPClientTestCase(TestCase, Mocks): Client-related test cases """ - class Resource(object): + class Resource: """ Fake network reader """ @@ -564,7 +560,7 @@ class SSDPClientTestCase(TestCase, Mocks): assert ( "Discovery master collection failure" in clnt.log.error.call_args[0][0] ) - assert error_msg == six.text_type(clnt.log.error.call_args[0][1]) + assert error_msg == str(clnt.log.error.call_args[0][1]) assert not response def test_discover_no_masters(self): diff --git a/tests/unit/utils/test_state.py b/tests/unit/utils/test_state.py index 3fa309bd675..1b533e494f2 100644 --- a/tests/unit/utils/test_state.py +++ b/tests/unit/utils/test_state.py @@ -1,21 +1,13 @@ -# -*- coding: utf-8 -*- """ Unit Tests for functions located in salt.utils.state.py. """ -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals import copy import textwrap import salt.utils.odict import salt.utils.state - -# Import Salt libs -from salt.ext import six - -# Import Salt Testing libs from tests.support.unit import TestCase @@ -129,9 +121,9 @@ class StateUtilTestCase(TestCase): ] ), } - for test, data in six.iteritems(test_valid_false_states): + for test, data in test_valid_false_states.items(): self.assertFalse( - salt.utils.state.check_result(data), msg="{0} failed".format(test) + salt.utils.state.check_result(data), msg="{} failed".format(test) ) test_valid_true_states = { "test1": salt.utils.odict.OrderedDict( @@ -221,9 +213,9 @@ class StateUtilTestCase(TestCase): ] ), } - for test, data in six.iteritems(test_valid_true_states): + for test, data in test_valid_true_states.items(): self.assertTrue( - salt.utils.state.check_result(data), msg="{0} failed".format(test) + salt.utils.state.check_result(data), msg="{} failed".format(test) ) test_invalid_true_ht_states = { "test_onfail_simple2": ( @@ -518,7 +510,7 @@ class StateUtilTestCase(TestCase): {}, ), } - for test, testdata in six.iteritems(test_invalid_true_ht_states): + for test, testdata in test_invalid_true_ht_states.items(): data, ht = testdata for t_ in [a for a in data["host1"]]: tdata = data["host1"][t_] @@ -527,7 +519,7 @@ class StateUtilTestCase(TestCase): tdata["__id__"] = t_ self.assertFalse( salt.utils.state.check_result(data, highstate=ht), - msg="{0} failed".format(test), + msg="{} failed".format(test), ) test_valid_true_ht_states = { @@ -745,7 +737,7 @@ class StateUtilTestCase(TestCase): }, ), } - for test, testdata in six.iteritems(test_valid_true_ht_states): + for test, testdata in test_valid_true_ht_states.items(): data, ht = testdata for t_ in [a for a in data["host1"]]: tdata = data["host1"][t_] @@ -754,7 +746,7 @@ class StateUtilTestCase(TestCase): tdata["__id__"] = t_ self.assertTrue( salt.utils.state.check_result(data, highstate=ht), - msg="{0} failed".format(test), + msg="{} failed".format(test), ) test_valid_false_state = {"host1": {"test_state": {"result": False}}} self.assertFalse(salt.utils.state.check_result(test_valid_false_state)) @@ -843,7 +835,7 @@ class UtilStateMergeSubreturnTestcase(TestCase): main_comment_1 = "First primary comment." main_comment_2 = "Second primary comment." sub_comment_1 = "First secondary comment,\nwhich spans two lines." - sub_comment_2 = "Second secondary comment: {0}".format( + sub_comment_2 = "Second secondary comment: {}".format( "some error\n And a traceback", ) final_comment = textwrap.dedent( diff --git a/tests/unit/utils/test_timed_subprocess.py b/tests/unit/utils/test_timed_subprocess.py index b7e3cbb96c8..56e896c0031 100644 --- a/tests/unit/utils/test_timed_subprocess.py +++ b/tests/unit/utils/test_timed_subprocess.py @@ -1,12 +1,4 @@ -# -*- coding: utf-8 -*- - -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals - -# Import salt libs import salt.utils.timed_subprocess as timed_subprocess - -# Import Salt Testing libs from tests.support.unit import TestCase diff --git a/tests/unit/utils/test_url.py b/tests/unit/utils/test_url.py index 46df564125c..1029b93a91b 100644 --- a/tests/unit/utils/test_url.py +++ b/tests/unit/utils/test_url.py @@ -1,14 +1,6 @@ -# -*- coding: utf-8 -*- - -# Import python libs -from __future__ import absolute_import, print_function, unicode_literals - -# Import Salt Libs import salt.utils.platform import salt.utils.url from tests.support.mock import MagicMock, patch - -# Import Salt Testing Libs from tests.support.unit import TestCase diff --git a/tests/unit/utils/test_vt.py b/tests/unit/utils/test_vt.py index 87fc6a342c1..9fa6308a711 100644 --- a/tests/unit/utils/test_vt.py +++ b/tests/unit/utils/test_vt.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ :codeauthor: Pedro Algarvio (pedro@algarvio.me) @@ -9,8 +8,6 @@ VirtualTerminal tests """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals import functools import io @@ -20,17 +17,11 @@ import subprocess import sys import time -# Import Salt libs import salt.utils import salt.utils.files import salt.utils.platform import salt.utils.stringutils import salt.utils.vt - -# Import 3rd-party libs -from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin - -# Import Salt Testing libs from tests.support.paths import CODE_DIR from tests.support.unit import TestCase, skipIf @@ -116,7 +107,7 @@ class VTTestCase(TestCase): ) stdout, _ = proc.communicate() return int(stdout.strip()) - except (ValueError, OSError, IOError): + except (ValueError, OSError): if salt.utils.platform.is_darwin(): # We're unable to findout how many PTY's are open self.skipTest( @@ -131,7 +122,7 @@ class VTTestCase(TestCase): for idx in range(0, nr_ptys + n_executions): try: with salt.utils.vt.Terminal( - 'echo "Run {0}"'.format(idx), + 'echo "Run {}"'.format(idx), shell=True, stream_stdout=False, stream_stderr=False, @@ -140,7 +131,7 @@ class VTTestCase(TestCase): try: if current_pty_count() > (nr_ptys + (n_executions / 2)): self.fail("VT is not cleaning up PTY's") - except (ValueError, OSError, IOError): + except (ValueError, OSError): self.fail("Unable to find out how many PTY's are open") except Exception as exc: # pylint: disable=broad-except if "out of pty devices" in str(exc): @@ -153,7 +144,7 @@ class VTTestCase(TestCase): for idx in range(0, nr_ptys + n_executions): try: terminal = salt.utils.vt.Terminal( - 'echo "Run {0}"'.format(idx), + 'echo "Run {}"'.format(idx), shell=True, stream_stdout=False, stream_stderr=False, @@ -162,7 +153,7 @@ class VTTestCase(TestCase): try: if current_pty_count() > (nr_ptys + (n_executions / 2)): self.fail("VT is not cleaning up PTY's") - except (ValueError, OSError, IOError): + except (ValueError, OSError): self.fail("Unable to find out how many PTY's are open") except Exception as exc: # pylint: disable=broad-except if "out of pty devices" in str(exc): diff --git a/tests/unit/utils/test_win_dotnet.py b/tests/unit/utils/test_win_dotnet.py index a262d32e00b..6391ddbfd03 100644 --- a/tests/unit/utils/test_win_dotnet.py +++ b/tests/unit/utils/test_win_dotnet.py @@ -1,13 +1,5 @@ -# -*- coding: utf-8 -*- - -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals - -# Import Salt Libs import salt.utils.platform import salt.utils.win_dotnet as win_dotnet - -# Import Salt Testing Libs from tests.support.mock import MagicMock, patch from tests.support.unit import TestCase, skipIf diff --git a/tests/unit/utils/test_win_osinfo.py b/tests/unit/utils/test_win_osinfo.py index 9bf173e60ba..9166cc67838 100644 --- a/tests/unit/utils/test_win_osinfo.py +++ b/tests/unit/utils/test_win_osinfo.py @@ -1,21 +1,11 @@ -# -*- coding: utf-8 -*- """ :codeauthor: Shane Lee """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals import sys import salt.utils.platform - -# Import Salt Libs import salt.utils.win_osinfo as win_osinfo - -# Import 3rd Party Libs -from salt.ext import six - -# Import Salt Testing Libs from tests.support.unit import TestCase, skipIf @@ -36,7 +26,7 @@ class WinOsInfo(TestCase): # Since we can't get the actual value another way, we will just check # that it exists and is a number self.assertIn("PlatformID", get_info) - self.assertTrue(isinstance(get_info["BuildNumber"], six.integer_types)) + self.assertTrue(isinstance(get_info["BuildNumber"], int)) def test_get_join_info(self): join_info = win_osinfo.get_join_info() diff --git a/tests/unit/utils/test_win_system.py b/tests/unit/utils/test_win_system.py index aa14f04589e..62fd39c0aaf 100644 --- a/tests/unit/utils/test_win_system.py +++ b/tests/unit/utils/test_win_system.py @@ -1,10 +1,6 @@ -# Import Python Libs import os -# Import Salt Libs import salt.utils.platform - -# Import Salt Testing Libs from tests.support.mock import patch from tests.support.unit import TestCase, skipIf diff --git a/tests/unit/utils/test_yamlencoding.py b/tests/unit/utils/test_yamlencoding.py index add28624b0d..179b7067cd1 100644 --- a/tests/unit/utils/test_yamlencoding.py +++ b/tests/unit/utils/test_yamlencoding.py @@ -1,12 +1,8 @@ -# -*- coding: utf-8 -*- """ Tests for salt.utils.yamlencoding """ -# Import Python libs -from __future__ import absolute_import, print_function, unicode_literals -# Import Salt libs import salt.utils.yaml import salt.utils.yamlencoding from tests.support.unit import TestCase diff --git a/tests/unit/utils/validate/__init__.py b/tests/unit/utils/validate/__init__.py index 40a96afc6ff..e69de29bb2d 100644 --- a/tests/unit/utils/validate/__init__.py +++ b/tests/unit/utils/validate/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/tests/wheeltest.py b/tests/wheeltest.py index 3eda0874a20..93880b0b9f3 100644 --- a/tests/wheeltest.py +++ b/tests/wheeltest.py @@ -1,20 +1,14 @@ -# -*- coding: utf-8 -*- - #!/usr/bin/env python """ Test interacting with the wheel system. This script is useful when testing wheel modules """ -# Import Python libs -from __future__ import absolute_import import optparse import pprint import salt.auth - -# Import Salt Libs import salt.config import salt.wheel @@ -45,7 +39,7 @@ def parse(): return cli -class Wheeler(object): +class Wheeler: """ Set up communication with the wheel interface """ diff --git a/tests/zypp_plugin.py b/tests/zypp_plugin.py index 783c716cd0e..45e6d79c285 100644 --- a/tests/zypp_plugin.py +++ b/tests/zypp_plugin.py @@ -1,10 +1,9 @@ -# -*- coding: utf-8 -*- """ Related to zypp_plugins_test.py module. """ -class Plugin(object): +class Plugin: """ Bogus module for Zypp Plugins tests. """ @@ -24,7 +23,7 @@ class Plugin(object): """ -class BogusIO(object): +class BogusIO: """ Read/write logger. """