Pyupgrade and drop six

This commit is contained in:
Daniel A. Wozniak 2021-04-01 16:29:01 -07:00 committed by Megan Wilhite
parent 55683944a8
commit a55f6b2797
759 changed files with 4682 additions and 8588 deletions

View file

@ -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
)

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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"]

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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,
)

View file

@ -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)

View file

@ -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

View file

@ -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"]

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
#
# Copyright 2015 SUSE LLC
#

View file

@ -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

View file

@ -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__
),
)

View file

@ -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()}

View file

@ -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

View file

@ -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

View file

@ -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)

View file

@ -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(

View file

@ -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

View file

@ -48,10 +48,8 @@ Connection module for Amazon EFS
"""
# Import python libs
import logging
# Import salt libs
import salt.utils.versions
try:

View file

@ -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,

View file

@ -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__)

View file

@ -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__)

View file

@ -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__)

View file

@ -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)

View file

@ -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

View file

@ -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,

View file

@ -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

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
Glue execution module to link to the :mod:`fx2 proxymodule <salt.proxy.fx2>`.
@ -13,9 +12,7 @@ parameter in :mod:`salt.modules.dracr <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

View file

@ -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 = """<firmwareBootUnit dn='sys/rack-unit-1/mgmt/fw-boot-def/bootunit-combined'
adminState='trigger' image='backup' resetOnActivate='{0}' />""".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 = """<aaaUser id="{0}" accountStatus="active" name="{1}" priv="{2}"
pwd="{3}" dn="sys/user-ext/user-{0}"/>""".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 = """<commVMediaMap dn='sys/svc-ext/vmedia-svc/vmmap-{0}' map='{1}'{2}
remoteFile='{3}' remoteShare='{4}' status='created'
dn = "sys/svc-ext/vmedia-svc/vmmap-{}".format(name)
inconfig = """<commVMediaMap dn='sys/svc-ext/vmedia-svc/vmmap-{}' map='{}'{}
remoteFile='{}' remoteShare='{}' status='created'
volumeName='Win12' />""".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 = """<mgmtIf dn="sys/rack-unit-1/mgmt/if-1" hostname="{0}" ></mgmtIf>""".format(
inconfig = """<mgmtIf dn="sys/rack-unit-1/mgmt/if-1" hostname="{}" ></mgmtIf>""".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 = """<commSyslog dn="sys/svc-ext/syslog"{0} ></commSyslog>""".format(query)
inconfig = """<commSyslog dn="sys/svc-ext/syslog"{} ></commSyslog>""".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 = """<commNtpProvider dn="sys/svc-ext/ntp-svc" ntpEnable="yes" ntpServer1="{0}" ntpServer2="{1}"
ntpServer3="{2}" ntpServer4="{3}"/>""".format(
inconfig = """<commNtpProvider dn="sys/svc-ext/ntp-svc" ntpEnable="yes" ntpServer1="{}" ntpServer2="{}"
ntpServer3="{}" ntpServer4="{}"/>""".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 = """<biosVfResumeOnACPowerLoss
dn="sys/rack-unit-1/board/Resume-on-AC-power-loss"{0}>
dn="sys/rack-unit-1/board/Resume-on-AC-power-loss"{}>
</biosVfResumeOnACPowerLoss>""".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 = """<commSyslogClient name='primary' adminState='enabled' hostname='{0}'
inconfig = """<commSyslogClient name='primary' adminState='enabled' hostname='{}'
dn='sys/svc-ext/syslog/client-primary'> </commSyslogClient>""".format(
server
)
elif type == "secondary":
dn = "sys/svc-ext/syslog/client-secondary"
inconfig = """<commSyslogClient name='secondary' adminState='enabled' hostname='{0}'
inconfig = """<commSyslogClient name='secondary' adminState='enabled' hostname='{}'
dn='sys/svc-ext/syslog/client-secondary'> </commSyslogClient>""".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 = """<aaaUser id="{0}"{1} dn="sys/user-ext/user-{0}"/>""".format(uid, conf)
@ -975,7 +970,7 @@ def tftp_update_bios(server=None, path=None):
dn = "sys/rack-unit-1/bios/fw-updatable"
inconfig = """<firmwareUpdatable adminState='trigger' dn='sys/rack-unit-1/bios/fw-updatable'
protocol='tftp' remoteServer='{0}' remotePath='{1}'
protocol='tftp' remoteServer='{}' remotePath='{}'
type='blade-bios' />""".format(
server, path
)
@ -1013,7 +1008,7 @@ def tftp_update_cimc(server=None, path=None):
dn = "sys/rack-unit-1/mgmt/fw-updatable"
inconfig = """<firmwareUpdatable adminState='trigger' dn='sys/rack-unit-1/mgmt/fw-updatable'
protocol='tftp' remoteServer='{0}' remotePath='{1}'
protocol='tftp' remoteServer='{}' remotePath='{}'
type='blade-controller' />""".format(
server, path
)

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
Execution module for `ciscoconfparse <http://www.pennington.net/py/ciscoconfparse/index.html>`_
@ -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

View file

@ -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

View file

@ -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")

View file

@ -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 = []

View file

@ -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)

View file

@ -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 <service name>
"""
__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 <service name>
"""
__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 <service name>
"""
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 <service name>
"""
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)

View file

@ -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

View file

@ -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)

View file

@ -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

View file

@ -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"

View file

@ -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 <settings_module> <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)

View file

@ -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())

View file

@ -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():

View file

@ -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()

View file

@ -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:

View file

@ -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)

View file

@ -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__)

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
Glues the VMware vSphere Execution Module to the VMware ESXi Proxy Minions to the
:mod:`esxi proxymodule <salt.proxy.esxi>`.
@ -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__)

View file

@ -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__)

View file

@ -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):

View file

@ -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 [<jail name>]
"""
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 [<jail name>]
"""
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 [<jail name>]
"""
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]

View file

@ -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"])

View file

@ -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:

View file

@ -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
<module-provider-override>`.
"""
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 <service name>
"""
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 <service name>
"""
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 <service name>
"""
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 <service name>
"""
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
)

View file

@ -1,19 +1,15 @@
# -*- coding: utf-8 -*-
"""
:maintainer: Alberto Planas <aplanas@suse.com>
: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

View file

@ -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

View file

@ -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
<module-provider-override>`.
"""
# 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)

View file

@ -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:

View file

@ -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:

View file

@ -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:

View file

@ -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
)

View file

@ -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

View file

@ -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 <user_id>
"""
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=<login> password=<password> email=<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 <user_id> login=<login> email=<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 <user_id> 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 <user_id> isGrafanaAdmin=<true|false>
"""
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 <user_id>
"""
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 <user_id>
"""
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 <user_id> <org_id>
"""
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 <name>
"""
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 <name>
"""
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 <orgname>
"""
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 <orgname> loginOrEmail=<loginOrEmail> role=<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 <user_id> <orgname> loginOrEmail=<loginOrEmail> role=<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 <user_id> <orgname>
"""
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 <orgname>
"""
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 <orgname> country=<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 <orgname>
"""
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 <orgname> theme=<theme> timezone=<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 <name>
"""
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 <org_id> name=<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 <org_id>
"""
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 <orgname>
"""
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 <datasourceid>
"""
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 <datasource_id>
"""
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 <slug>
"""
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 <slug>
"""
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=<dashboard> overwrite=True orgname=<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),

View file

@ -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))

View file

@ -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"]

View file

@ -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

View file

@ -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__)

View file

@ -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)

View file

@ -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,
)

View file

@ -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"}

View file

@ -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

View file

@ -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

View file

@ -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)

View file

@ -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.
"""

View file

@ -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):

View file

@ -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

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
#
# Copyright 2015 SUSE LLC
#

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
#
# Copyright 2016 SUSE LLC
#
@ -18,7 +17,6 @@
:codeauthor: Bo Maryniuk <bo@suse.de>
"""
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):

View file

@ -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))
)

View file

@ -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"]
)
)

View file

@ -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):

View file

@ -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

View file

@ -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))

View file

@ -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)

View file

@ -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:

View file

@ -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:

View file

@ -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

View file

@ -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

View file

@ -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
)
)

View file

@ -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,

Some files were not shown because too many files have changed in this diff Show more