Run pyupgrade on the files changed on the merge forward

Signed-off-by: Pedro Algarvio <palgarvio@vmware.com>
This commit is contained in:
Pedro Algarvio 2023-09-11 10:13:13 +01:00
parent 2d46e659f4
commit c096bc6022
No known key found for this signature in database
GPG key ID: BB36BF6584A298FF
44 changed files with 423 additions and 466 deletions

View file

@ -116,10 +116,9 @@ def test_pip_non_root(shell, install_salt, test_account, extras_pypath_bin):
install_salt.binary_paths["salt"] + ["--help"],
preexec_fn=demote(test_account.uid, test_account.gid),
env=test_account.env,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
capture_output=True,
check=False,
universal_newlines=True,
text=True,
)
assert ret.returncode == 0, ret.stderr
assert "Usage" in ret.stdout
@ -127,10 +126,9 @@ def test_pip_non_root(shell, install_salt, test_account, extras_pypath_bin):
# Let tiamat-pip create the pypath directory for us
ret = subprocess.run(
install_salt.binary_paths["pip"] + ["install", "-h"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
capture_output=True,
check=False,
universal_newlines=True,
text=True,
)
assert ret.returncode == 0, ret.stderr
@ -139,19 +137,17 @@ def test_pip_non_root(shell, install_salt, test_account, extras_pypath_bin):
install_salt.binary_paths["pip"] + ["install", "pep8"],
preexec_fn=demote(test_account.uid, test_account.gid),
env=test_account.env,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
capture_output=True,
check=False,
universal_newlines=True,
text=True,
)
assert ret.returncode != 0, ret.stderr
# But we should be able to install as root
ret = subprocess.run(
install_salt.binary_paths["pip"] + ["install", "pep8"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
capture_output=True,
check=False,
universal_newlines=True,
text=True,
)
assert check_path.exists()

View file

@ -79,7 +79,7 @@ def beacon(config):
for uuid in current_images:
event = {}
if uuid not in IMGADM_STATE["images"]:
event["tag"] = "imported/{}".format(uuid)
event["tag"] = f"imported/{uuid}"
for label in current_images[uuid]:
event[label] = current_images[uuid][label]
@ -90,7 +90,7 @@ def beacon(config):
for uuid in IMGADM_STATE["images"]:
event = {}
if uuid not in current_images:
event["tag"] = "deleted/{}".format(uuid)
event["tag"] = f"deleted/{uuid}"
for label in IMGADM_STATE["images"][uuid]:
event[label] = IMGADM_STATE["images"][uuid][label]

View file

@ -82,7 +82,7 @@ def beacon(config):
for uuid in current_vms:
event = {}
if uuid not in VMADM_STATE["vms"]:
event["tag"] = "created/{}".format(uuid)
event["tag"] = f"created/{uuid}"
for label in current_vms[uuid]:
if label == "state":
continue
@ -95,7 +95,7 @@ def beacon(config):
for uuid in VMADM_STATE["vms"]:
event = {}
if uuid not in current_vms:
event["tag"] = "deleted/{}".format(uuid)
event["tag"] = f"deleted/{uuid}"
for label in VMADM_STATE["vms"][uuid]:
if label == "state":
continue

View file

@ -88,7 +88,7 @@ def clean_fsbackend(opts):
# Clear remote fileserver backend caches so they get recreated
for backend in ("git", "hg", "svn"):
if backend in opts["fileserver_backend"]:
env_cache = os.path.join(opts["cachedir"], "{}fs".format(backend), "envs.p")
env_cache = os.path.join(opts["cachedir"], f"{backend}fs", "envs.p")
if os.path.isfile(env_cache):
log.debug("Clearing %sfs env cache", backend)
try:
@ -99,7 +99,7 @@ def clean_fsbackend(opts):
)
file_lists_dir = os.path.join(
opts["cachedir"], "file_lists", "{}fs".format(backend)
opts["cachedir"], "file_lists", f"{backend}fs"
)
try:
file_lists_caches = os.listdir(file_lists_dir)
@ -177,7 +177,7 @@ def mk_key(opts, user):
opts["cachedir"], ".{}_key".format(user.replace("\\", "_"))
)
else:
keyfile = os.path.join(opts["cachedir"], ".{}_key".format(user))
keyfile = os.path.join(opts["cachedir"], f".{user}_key")
if os.path.exists(keyfile):
log.debug("Removing stale keyfile: %s", keyfile)
@ -220,7 +220,7 @@ def access_keys(opts):
for user in acl_users:
log.info("Preparing the %s key for local communication", user)
keyfile = os.path.join(opts["cachedir"], ".{}_key".format(user))
keyfile = os.path.join(opts["cachedir"], f".{user}_key")
if os.path.exists(keyfile):
with salt.utils.files.fopen(keyfile, "r") as fp:
key = salt.utils.stringutils.to_unicode(fp.read())
@ -603,7 +603,7 @@ class RemoteFuncs:
minions = _res["minions"]
minion_side_acl = {} # Cache minion-side ACL
for minion in minions:
mine_data = self.cache.fetch("minions/{}".format(minion), "mine")
mine_data = self.cache.fetch(f"minions/{minion}", "mine")
if not isinstance(mine_data, dict):
continue
for function in functions_allowed:
@ -630,7 +630,7 @@ class RemoteFuncs:
continue
salt.utils.dictupdate.set_dict_key_value(
minion_side_acl,
"{}:{}".format(minion, function),
f"{minion}:{function}",
get_minion,
)
if salt.utils.mine.minion_side_acl_denied(
@ -1190,7 +1190,7 @@ class LocalFuncs:
fun = load.pop("fun")
tag = salt.utils.event.tagify(jid, prefix="wheel")
data = {
"fun": "wheel.{}".format(fun),
"fun": f"wheel.{fun}",
"jid": jid,
"tag": tag,
"user": username,
@ -1274,7 +1274,7 @@ class LocalFuncs:
# Setup authorization list variable and error information
auth_list = auth_check.get("auth_list", [])
error = auth_check.get("error")
err_msg = 'Authentication failure of type "{}" occurred.'.format(auth_type)
err_msg = f'Authentication failure of type "{auth_type}" occurred.'
if error:
# Authentication error occurred: do not continue.

View file

@ -62,7 +62,7 @@ def _user_mdata(mdata_list=None, mdata_get=None):
log.warning("mdata-list returned an error, skipping mdata grains.")
continue
mdata_value = __salt__["cmd.run"](
"{} {}".format(mdata_get, mdata_grain), ignore_retcode=True
f"{mdata_get} {mdata_grain}", ignore_retcode=True
)
if not mdata_grain.startswith("sdc:"):
@ -108,7 +108,7 @@ def _sdc_mdata(mdata_list=None, mdata_get=None):
for mdata_grain in sdc_text_keys + sdc_json_keys:
mdata_value = __salt__["cmd.run"](
"{} sdc:{}".format(mdata_get, mdata_grain), ignore_retcode=True
f"{mdata_get} sdc:{mdata_grain}", ignore_retcode=True
)
if mdata_value.startswith("ERROR:"):
log.warning(

View file

@ -48,7 +48,7 @@ def _cmd(binary, *args):
"""
binary = salt.utils.path.which(binary)
if not binary:
raise CommandNotFoundError("{}: command not found".format(binary))
raise CommandNotFoundError(f"{binary}: command not found")
cmd = [binary] + list(args)
return __salt__["cmd.run_stdout"]([binary] + list(args), python_shell=False)
@ -307,7 +307,7 @@ def atc(jobid):
if output is None:
return "'at.atc' is not available."
elif output == "":
return {"error": "invalid job id '{}'".format(jobid)}
return {"error": f"invalid job id '{jobid}'"}
return output
@ -327,7 +327,7 @@ def _atq(**kwargs):
month = kwargs.get("month", None)
year = kwargs.get("year", None)
if year and len(str(year)) == 2:
year = "20{}".format(year)
year = f"20{year}"
jobinfo = atq()["jobs"]
if not jobinfo:
@ -351,28 +351,28 @@ def _atq(**kwargs):
if not hour:
pass
elif "{:02d}".format(int(hour)) == job["time"].split(":")[0]:
elif f"{int(hour):02d}" == job["time"].split(":")[0]:
pass
else:
continue
if not minute:
pass
elif "{:02d}".format(int(minute)) == job["time"].split(":")[1]:
elif f"{int(minute):02d}" == job["time"].split(":")[1]:
pass
else:
continue
if not day:
pass
elif "{:02d}".format(int(day)) == job["date"].split("-")[2]:
elif f"{int(day):02d}" == job["date"].split("-")[2]:
pass
else:
continue
if not month:
pass
elif "{:02d}".format(int(month)) == job["date"].split("-")[1]:
elif f"{int(month):02d}" == job["date"].split("-")[1]:
pass
else:
continue

View file

@ -95,7 +95,7 @@ def atq(tag=None):
job = str(job)
# search for any tags
atjob_file = "/var/spool/cron/atjobs/{job}".format(job=job)
atjob_file = f"/var/spool/cron/atjobs/{job}"
if __salt__["file.file_exists"](atjob_file):
with salt.utils.files.fopen(atjob_file, "r") as atjob:
for line in atjob:
@ -162,7 +162,7 @@ def atrm(*args):
# call atrm for each job in ret['jobs']['removed']
for job in ret["jobs"]["removed"]:
res_job = __salt__["cmd.run_all"]("atrm {job}".format(job=job))
res_job = __salt__["cmd.run_all"](f"atrm {job}")
if res_job["retcode"] > 0:
if "failed" not in ret["jobs"]:
ret["jobs"]["failed"] = {}
@ -205,9 +205,7 @@ def at(*args, **kwargs): # pylint: disable=C0103
cmd_kwargs = {"stdin": stdin, "python_shell": False}
if "runas" in kwargs:
cmd_kwargs["runas"] = kwargs["runas"]
res = __salt__["cmd.run_all"](
'at "{timespec}"'.format(timespec=args[0]), **cmd_kwargs
)
res = __salt__["cmd.run_all"](f'at "{args[0]}"', **cmd_kwargs)
# verify job creation
if res["retcode"] > 0:
@ -233,14 +231,14 @@ def atc(jobid):
salt '*' at.atc <jobid>
"""
atjob_file = "/var/spool/cron/atjobs/{job}".format(job=jobid)
atjob_file = f"/var/spool/cron/atjobs/{jobid}"
if __salt__["file.file_exists"](atjob_file):
with salt.utils.files.fopen(atjob_file, "r") as rfh:
return "".join(
[salt.utils.stringutils.to_unicode(x) for x in rfh.readlines()]
)
else:
return {"error": "invalid job id '{}'".format(jobid)}
return {"error": f"invalid job id '{jobid}'"}
def _atq(**kwargs):
@ -258,7 +256,7 @@ def _atq(**kwargs):
month = kwargs.get("month", None)
year = kwargs.get("year", None)
if year and len(str(year)) == 2:
year = "20{}".format(year)
year = f"20{year}"
jobinfo = atq()["jobs"]
if not jobinfo:
@ -282,28 +280,28 @@ def _atq(**kwargs):
if not hour:
pass
elif "{:02d}".format(int(hour)) == job["time"].split(":")[0]:
elif f"{int(hour):02d}" == job["time"].split(":")[0]:
pass
else:
continue
if not minute:
pass
elif "{:02d}".format(int(minute)) == job["time"].split(":")[1]:
elif f"{int(minute):02d}" == job["time"].split(":")[1]:
pass
else:
continue
if not day:
pass
elif "{:02d}".format(int(day)) == job["date"].split("-")[2]:
elif f"{int(day):02d}" == job["date"].split("-")[2]:
pass
else:
continue
if not month:
pass
elif "{:02d}".format(int(month)) == job["date"].split("-")[1]:
elif f"{int(month):02d}" == job["date"].split("-")[1]:
pass
else:
continue

View file

@ -51,9 +51,9 @@ def _linux_brshow(br=None):
brctl = _tool_path("brctl")
if br:
cmd = "{} show {}".format(brctl, br)
cmd = f"{brctl} show {br}"
else:
cmd = "{} show".format(brctl)
cmd = f"{brctl} show"
brs = {}
@ -96,7 +96,7 @@ def _linux_bradd(br):
Internal, creates the bridge
"""
brctl = _tool_path("brctl")
return __salt__["cmd.run"]("{} addbr {}".format(brctl, br), python_shell=False)
return __salt__["cmd.run"](f"{brctl} addbr {br}", python_shell=False)
def _linux_brdel(br):
@ -104,7 +104,7 @@ def _linux_brdel(br):
Internal, deletes the bridge
"""
brctl = _tool_path("brctl")
return __salt__["cmd.run"]("{} delbr {}".format(brctl, br), python_shell=False)
return __salt__["cmd.run"](f"{brctl} delbr {br}", python_shell=False)
def _linux_addif(br, iface):
@ -112,9 +112,7 @@ def _linux_addif(br, iface):
Internal, adds an interface to a bridge
"""
brctl = _tool_path("brctl")
return __salt__["cmd.run"](
"{} addif {} {}".format(brctl, br, iface), python_shell=False
)
return __salt__["cmd.run"](f"{brctl} addif {br} {iface}", python_shell=False)
def _linux_delif(br, iface):
@ -122,9 +120,7 @@ def _linux_delif(br, iface):
Internal, removes an interface from a bridge
"""
brctl = _tool_path("brctl")
return __salt__["cmd.run"](
"{} delif {} {}".format(brctl, br, iface), python_shell=False
)
return __salt__["cmd.run"](f"{brctl} delif {br} {iface}", python_shell=False)
def _linux_stp(br, state):
@ -132,9 +128,7 @@ def _linux_stp(br, state):
Internal, sets STP state
"""
brctl = _tool_path("brctl")
return __salt__["cmd.run"](
"{} stp {} {}".format(brctl, br, state), python_shell=False
)
return __salt__["cmd.run"](f"{brctl} stp {br} {state}", python_shell=False)
def _bsd_brshow(br=None):
@ -151,14 +145,14 @@ def _bsd_brshow(br=None):
if br:
ifaces[br] = br
else:
cmd = "{} -g bridge".format(ifconfig)
cmd = f"{ifconfig} -g bridge"
for line in __salt__["cmd.run"](cmd, python_shell=False).splitlines():
ifaces[line] = line
brs = {}
for iface in ifaces:
cmd = "{} {}".format(ifconfig, iface)
cmd = f"{ifconfig} {iface}"
for line in __salt__["cmd.run"](cmd, python_shell=False).splitlines():
brs[iface] = {"interfaces": [], "stp": "no"}
line = line.lstrip()
@ -179,9 +173,9 @@ def _netbsd_brshow(br=None):
brconfig = _tool_path("brconfig")
if br:
cmd = "{} {}".format(brconfig, br)
cmd = f"{brconfig} {br}"
else:
cmd = "{} -a".format(brconfig)
cmd = f"{brconfig} -a"
brs = {}
start_int = False
@ -219,21 +213,13 @@ def _bsd_bradd(br):
if not br:
return False
if (
__salt__["cmd.retcode"](
"{} {} create up".format(ifconfig, br), python_shell=False
)
!= 0
):
if __salt__["cmd.retcode"](f"{ifconfig} {br} create up", python_shell=False) != 0:
return False
# NetBSD is two cmds
if kernel == "NetBSD":
brconfig = _tool_path("brconfig")
if (
__salt__["cmd.retcode"]("{} {} up".format(brconfig, br), python_shell=False)
!= 0
):
if __salt__["cmd.retcode"](f"{brconfig} {br} up", python_shell=False) != 0:
return False
return True
@ -246,7 +232,7 @@ def _bsd_brdel(br):
ifconfig = _tool_path("ifconfig")
if not br:
return False
return __salt__["cmd.run"]("{} {} destroy".format(ifconfig, br), python_shell=False)
return __salt__["cmd.run"](f"{ifconfig} {br} destroy", python_shell=False)
def _bsd_addif(br, iface):
@ -264,9 +250,7 @@ def _bsd_addif(br, iface):
if not br or not iface:
return False
return __salt__["cmd.run"](
"{} {} {} {}".format(cmd, br, brcmd, iface), python_shell=False
)
return __salt__["cmd.run"](f"{cmd} {br} {brcmd} {iface}", python_shell=False)
def _bsd_delif(br, iface):
@ -284,9 +268,7 @@ def _bsd_delif(br, iface):
if not br or not iface:
return False
return __salt__["cmd.run"](
"{} {} {} {}".format(cmd, br, brcmd, iface), python_shell=False
)
return __salt__["cmd.run"](f"{cmd} {br} {brcmd} {iface}", python_shell=False)
def _bsd_stp(br, state, iface):
@ -303,9 +285,7 @@ def _bsd_stp(br, state, iface):
if not br or not iface:
return False
return __salt__["cmd.run"](
"{} {} {} {}".format(cmd, br, state, iface), python_shell=False
)
return __salt__["cmd.run"](f"{cmd} {br} {state} {iface}", python_shell=False)
def _os_dispatch(func, *args, **kwargs):
@ -317,7 +297,7 @@ def _os_dispatch(func, *args, **kwargs):
else:
kernel = __grains__["kernel"].lower()
_os_func = getattr(sys.modules[__name__], "_{}_{}".format(kernel, func))
_os_func = getattr(sys.modules[__name__], f"_{kernel}_{func}")
if callable(_os_func):
return _os_func(*args, **kwargs)

View file

@ -69,7 +69,7 @@ def __virtual__():
return __virtualname__
return (
False,
"{} module can only be loaded on SmartOS zones".format(__virtualname__),
f"{__virtualname__} module can only be loaded on SmartOS zones",
)
@ -85,7 +85,7 @@ def list_():
"""
mdata = _check_mdata_list()
if mdata:
cmd = "{}".format(mdata)
cmd = f"{mdata}"
return __salt__["cmd.run"](cmd, ignore_retcode=True).splitlines()
return {}
@ -116,7 +116,7 @@ def get_(*keyname):
for k in keyname:
if mdata:
cmd = "{} {}".format(mdata, k)
cmd = f"{mdata} {k}"
res = __salt__["cmd.run_all"](cmd, ignore_retcode=True)
ret[k] = res["stdout"] if res["retcode"] == 0 else ""
else:
@ -144,7 +144,7 @@ def put_(keyname, val):
ret = {}
if mdata:
cmd = "echo {2} | {0} {1}".format(mdata, keyname, val)
cmd = f"echo {val} | {mdata} {keyname}"
ret = __salt__["cmd.run_all"](cmd, python_shell=True, ignore_retcode=True)
return ret["retcode"] == 0
@ -170,7 +170,7 @@ def delete_(*keyname):
for k in keyname:
if mdata and k in valid_keynames:
cmd = "{} {}".format(mdata, k)
cmd = f"{mdata} {k}"
ret[k] = __salt__["cmd.run_all"](cmd, ignore_retcode=True)["retcode"] == 0
else:
ret[k] = True

View file

@ -58,11 +58,11 @@ def show(config_file=False):
out = __salt__["cmd.run"](cmd, output_loglevel="trace")
comps = [""]
for line in out.splitlines():
if any([line.startswith("{}.".format(root)) for root in roots]):
if any([line.startswith(f"{root}.") for root in roots]):
comps = re.split("[=:]", line, 1)
ret[comps[0]] = comps[1]
elif comps[0]:
ret[comps[0]] += "{}\n".format(line)
ret[comps[0]] += f"{line}\n"
else:
continue
return ret
@ -78,7 +78,7 @@ def get(name):
salt '*' sysctl.get hw.physmem
"""
cmd = "sysctl -n {}".format(name)
cmd = f"sysctl -n {name}"
out = __salt__["cmd.run"](cmd, python_shell=False)
return out
@ -94,7 +94,7 @@ def assign(name, value):
salt '*' sysctl.assign net.inet.icmp.icmplim 50
"""
ret = {}
cmd = 'sysctl -w {}="{}"'.format(name, value)
cmd = f'sysctl -w {name}="{value}"'
data = __salt__["cmd.run_all"](cmd, python_shell=False)
if data["retcode"] != 0:
@ -130,7 +130,7 @@ def persist(name, value, config="/etc/sysctl.conf"):
with salt.utils.files.fopen(config, "r") as ifile:
for line in ifile:
line = salt.utils.stringutils.to_unicode(line)
m = re.match(r"{}(\??=)".format(name), line)
m = re.match(rf"{name}(\??=)", line)
if not m:
nlines.append(line)
continue
@ -145,13 +145,13 @@ def persist(name, value, config="/etc/sysctl.conf"):
rest = rest[len(rest_v) :]
if rest_v == value:
return "Already set"
new_line = "{}{}{}{}".format(name, m.group(1), value, rest)
new_line = f"{name}{m.group(1)}{value}{rest}"
nlines.append(new_line)
edited = True
if not edited:
newline = "{}={}".format(name, value)
nlines.append("{}\n".format(newline))
newline = f"{name}={value}"
nlines.append(f"{newline}\n")
with salt.utils.files.fopen(config, "wb") as ofile:
ofile.writelines(salt.utils.data.encode(nlines))

View file

@ -41,7 +41,7 @@ def start(name):
salt '*' service.start <service name>
"""
cmd = "/etc/rc.d/{} onestart".format(name)
cmd = f"/etc/rc.d/{name} onestart"
return not __salt__["cmd.retcode"](cmd)
@ -55,7 +55,7 @@ def stop(name):
salt '*' service.stop <service name>
"""
cmd = "/etc/rc.d/{} onestop".format(name)
cmd = f"/etc/rc.d/{name} onestop"
return not __salt__["cmd.retcode"](cmd)
@ -69,7 +69,7 @@ def restart(name):
salt '*' service.restart <service name>
"""
cmd = "/etc/rc.d/{} onerestart".format(name)
cmd = f"/etc/rc.d/{name} onerestart"
return not __salt__["cmd.retcode"](cmd)
@ -83,7 +83,7 @@ def reload_(name):
salt '*' service.reload <service name>
"""
cmd = "/etc/rc.d/{} onereload".format(name)
cmd = f"/etc/rc.d/{name} onereload"
return not __salt__["cmd.retcode"](cmd)
@ -97,7 +97,7 @@ def force_reload(name):
salt '*' service.force_reload <service name>
"""
cmd = "/etc/rc.d/{} forcereload".format(name)
cmd = f"/etc/rc.d/{name} forcereload"
return not __salt__["cmd.retcode"](cmd)
@ -134,7 +134,7 @@ def status(name, sig=None):
services = [name]
results = {}
for service in services:
cmd = "/etc/rc.d/{} onestatus".format(service)
cmd = f"/etc/rc.d/{service} onestatus"
results[service] = not __salt__["cmd.retcode"](cmd, ignore_retcode=True)
if contains_globbing:
return results
@ -146,9 +146,9 @@ def _get_svc(rcd, service_status):
Returns a unique service status
"""
ena = None
lines = __salt__["cmd.run"]("{} rcvar".format(rcd)).splitlines()
lines = __salt__["cmd.run"](f"{rcd} rcvar").splitlines()
for rcvar in lines:
if rcvar.startswith("$") and "={}".format(service_status) in rcvar:
if rcvar.startswith("$") and f"={service_status}" in rcvar:
ena = "yes"
elif rcvar.startswith("#"):
svc = rcvar.split(" ", 1)[1]
@ -166,7 +166,7 @@ def _get_svc_list(service_status):
"""
prefix = "/etc/rc.d/"
ret = set()
lines = glob.glob("{}*".format(prefix))
lines = glob.glob(f"{prefix}*")
for line in lines:
svc = _get_svc(line, service_status)
if svc is not None:
@ -249,9 +249,9 @@ def _rcconf_status(name, service_status):
can be started via /etc/rc.d/<service>
"""
rcconf = "/etc/rc.conf"
rxname = "^{}=.*".format(name)
newstatus = "{}={}".format(name, service_status)
ret = __salt__["cmd.retcode"]("grep '{}' {}".format(rxname, rcconf))
rxname = f"^{name}=.*"
newstatus = f"{name}={service_status}"
ret = __salt__["cmd.retcode"](f"grep '{rxname}' {rcconf}")
if ret == 0: # service found in rc.conf, modify its status
__salt__["file.replace"](rcconf, rxname, newstatus)
else:
@ -296,7 +296,7 @@ def enabled(name, **kwargs):
salt '*' service.enabled <service name>
"""
return _get_svc("/etc/rc.d/{}".format(name), "YES")
return _get_svc(f"/etc/rc.d/{name}", "YES")
def disabled(name):
@ -309,4 +309,4 @@ def disabled(name):
salt '*' service.disabled <service name>
"""
return _get_svc("/etc/rc.d/{}".format(name), "NO")
return _get_svc(f"/etc/rc.d/{name}", "NO")

View file

@ -165,7 +165,7 @@ def delete(login):
"""
if login in list_users(False):
res = __salt__["cmd.run_all"](
"pdbedit --delete {login}".format(login=shlex.quote(login)),
f"pdbedit --delete {shlex.quote(login)}",
)
if res["retcode"] > 0:

View file

@ -40,7 +40,7 @@ def _check_pkgin():
"pkg_info -Q LOCALBASE pkgin", output_loglevel="trace"
)
if localbase is not None:
ppath = "{}/bin/pkgin".format(localbase)
ppath = f"{localbase}/bin/pkgin"
if not os.path.exists(ppath):
return None
except CommandExecutionError:
@ -124,7 +124,7 @@ def search(pkg_name, **kwargs):
return pkglist
if _supports_regex():
pkg_name = "^{}$".format(pkg_name)
pkg_name = f"^{pkg_name}$"
out = __salt__["cmd.run"]([pkgin, "se", pkg_name], output_loglevel="trace")
for line in out.splitlines():
@ -170,7 +170,7 @@ def latest_version(*names, **kwargs):
cmd_prefix.insert(1, "-p")
for name in names:
cmd = copy.deepcopy(cmd_prefix)
cmd.append("^{}$".format(name) if _supports_regex() else name)
cmd.append(f"^{name}$" if _supports_regex() else name)
out = __salt__["cmd.run"](cmd, output_loglevel="trace")
for line in out.splitlines():
@ -564,9 +564,9 @@ def remove(name=None, pkgs=None, **kwargs):
if not ver:
continue
if isinstance(ver, list):
args.extend(["{}-{}".format(param, v) for v in ver])
args.extend([f"{param}-{v}" for v in ver])
else:
args.append("{}-{}".format(param, ver))
args.append(f"{param}-{ver}")
if not args:
return {}

View file

@ -21,7 +21,7 @@ def __virtual__():
return __virtualname__
return (
False,
"{} module can only be loaded on a solaris like system".format(__virtualname__),
f"{__virtualname__} module can only be loaded on a solaris like system",
)
@ -459,7 +459,7 @@ def auth_list():
# add auth info to dict
if auth[0][-1:] == ".":
auth[0] = "{}*".format(auth[0])
auth[0] = f"{auth[0]}*"
auths[auth[0]] = auth[3]
return auths
@ -509,7 +509,7 @@ def auth_get(user, computed=True):
## also parse auths command
if computed:
res = __salt__["cmd.run_all"]("auths {}".format(user))
res = __salt__["cmd.run_all"](f"auths {user}")
if res["retcode"] == 0:
for auth in res["stdout"].splitlines():
if "," in auth:

View file

@ -122,7 +122,7 @@ def start(name):
salt '*' runit.start <service name>
"""
cmd = "sv start {}".format(_service_path(name))
cmd = f"sv start {_service_path(name)}"
return not __salt__["cmd.retcode"](cmd)
@ -140,7 +140,7 @@ def stop(name):
salt '*' runit.stop <service name>
"""
cmd = "sv stop {}".format(_service_path(name))
cmd = f"sv stop {_service_path(name)}"
return not __salt__["cmd.retcode"](cmd)
@ -158,7 +158,7 @@ def reload_(name):
salt '*' runit.reload <service name>
"""
cmd = "sv reload {}".format(_service_path(name))
cmd = f"sv reload {_service_path(name)}"
return not __salt__["cmd.retcode"](cmd)
@ -176,7 +176,7 @@ def restart(name):
salt '*' runit.restart <service name>
"""
cmd = "sv restart {}".format(_service_path(name))
cmd = f"sv restart {_service_path(name)}"
return not __salt__["cmd.retcode"](cmd)
@ -226,7 +226,7 @@ def status(name, sig=None):
# sv return code is not relevant to get a service status.
# Check its output instead.
cmd = "sv status {}".format(svc_path)
cmd = f"sv status {svc_path}"
try:
out = __salt__["cmd.run_stdout"](cmd)
return out.startswith("run: ")
@ -628,7 +628,7 @@ def enable(name, start=False, **kwargs):
# if not, down_file might be removed too quickly,
# before 'sv' have time to take care about it.
# Documentation indicates that a change is handled within 5 seconds.
cmd = "sv status {}".format(_service_path(name))
cmd = f"sv status {_service_path(name)}"
retcode_sv = 1
count_sv = 0
while retcode_sv != 0 and count_sv < 10:

View file

@ -46,7 +46,7 @@ def start(name):
salt '*' service.start <service name>
"""
cmd = "/bin/sh {}.{} start".format(prefix, name)
cmd = f"/bin/sh {prefix}.{name} start"
return not __salt__["cmd.retcode"](cmd)
@ -62,7 +62,7 @@ def stop(name):
salt '*' service.stop <service name>
"""
cmd = "/bin/sh {}.{} stop".format(prefix, name)
cmd = f"/bin/sh {prefix}.{name} stop"
return not __salt__["cmd.retcode"](cmd)
@ -78,7 +78,7 @@ def restart(name):
salt '*' service.restart <service name>
"""
cmd = "/bin/sh {}.{} restart".format(prefix, name)
cmd = f"/bin/sh {prefix}.{name} restart"
return not __salt__["cmd.retcode"](cmd)
@ -94,7 +94,7 @@ def reload_(name):
salt '*' service.reload <service name>
"""
cmd = "/bin/sh {}.{} reload".format(prefix, name)
cmd = f"/bin/sh {prefix}.{name} reload"
return not __salt__["cmd.retcode"](cmd)
@ -110,7 +110,7 @@ def force_reload(name):
salt '*' service.force_reload <service name>
"""
cmd = "/bin/sh {}.{} forcereload".format(prefix, name)
cmd = f"/bin/sh {prefix}.{name} forcereload"
return not __salt__["cmd.retcode"](cmd)
@ -146,7 +146,7 @@ def status(name, sig=None):
services = [name]
results = {}
for service in services:
cmd = "/bin/sh {}.{} status".format(prefix, service)
cmd = f"/bin/sh {prefix}.{service} status"
results[service] = not __salt__["cmd.retcode"](cmd, ignore_retcode=True)
if contains_globbing:
return results
@ -179,7 +179,7 @@ def _get_svc_list(service_status):
)
)
ret = set()
lines = glob.glob("{}.*".format(prefix))
lines = glob.glob(f"{prefix}.*")
for line in lines:
if not notservice.match(line):
svc = _get_svc(line, service_status)
@ -328,7 +328,7 @@ def enabled(name, **kwargs):
salt '*' service.enabled <service name>
"""
ret = True
if _get_svc("{}.{}".format(prefix, name), "ON") is None:
if _get_svc(f"{prefix}.{name}", "ON") is None:
ret = False
return ret
@ -346,6 +346,6 @@ def disabled(name):
salt '*' service.disabled <service name>
"""
ret = True
if _get_svc("{}.{}".format(prefix, name), "OFF") is None:
if _get_svc(f"{prefix}.{name}", "OFF") is None:
ret = False
return ret

View file

@ -29,7 +29,7 @@ def __virtual__():
return __virtualname__
return (
False,
"{} module can only be loaded on SmartOS compute nodes".format(__virtualname__),
f"{__virtualname__} module can only be loaded on SmartOS compute nodes",
)
@ -70,7 +70,7 @@ def _parse_image_meta(image=None, detail=False):
docker_repo = image["manifest"]["tags"][tag]
if docker_repo and docker_tag:
name = "{}:{}".format(docker_repo, docker_tag)
name = f"{docker_repo}:{docker_tag}"
description = (
"Docker image imported from {repo}:{tag} on {date}.".format(
repo=docker_repo,
@ -183,7 +183,7 @@ def update_installed(uuid=""):
salt '*' imgadm.update [uuid]
"""
cmd = "imgadm update {}".format(uuid).rstrip()
cmd = f"imgadm update {uuid}".rstrip()
__salt__["cmd.run"](cmd)
return {}
@ -279,7 +279,7 @@ def show(uuid):
ret = {}
if _is_uuid(uuid) or _is_docker_uuid(uuid):
cmd = "imgadm show {}".format(uuid)
cmd = f"imgadm show {uuid}"
res = __salt__["cmd.run_all"](cmd, python_shell=False)
retcode = res["retcode"]
if retcode != 0:
@ -287,7 +287,7 @@ def show(uuid):
else:
ret = salt.utils.json.loads(res["stdout"])
else:
ret["Error"] = "{} is not a valid uuid.".format(uuid)
ret["Error"] = f"{uuid} is not a valid uuid."
return ret
@ -312,7 +312,7 @@ def get(uuid):
uuid = docker_to_uuid(uuid)
if _is_uuid(uuid):
cmd = "imgadm get {}".format(uuid)
cmd = f"imgadm get {uuid}"
res = __salt__["cmd.run_all"](cmd, python_shell=False)
retcode = res["retcode"]
if retcode != 0:
@ -320,7 +320,7 @@ def get(uuid):
else:
ret = salt.utils.json.loads(res["stdout"])
else:
ret["Error"] = "{} is not a valid uuid.".format(uuid)
ret["Error"] = f"{uuid} is not a valid uuid."
return ret
@ -341,7 +341,7 @@ def import_image(uuid, verbose=False):
salt '*' imgadm.import e42f8c84-bbea-11e2-b920-078fab2aab1f [verbose=True]
"""
ret = {}
cmd = "imgadm import {}".format(uuid)
cmd = f"imgadm import {uuid}"
res = __salt__["cmd.run_all"](cmd, python_shell=False)
retcode = res["retcode"]
if retcode != 0:
@ -367,7 +367,7 @@ def delete(uuid):
salt '*' imgadm.delete e42f8c84-bbea-11e2-b920-078fab2aab1f
"""
ret = {}
cmd = "imgadm delete {}".format(uuid)
cmd = f"imgadm delete {uuid}"
res = __salt__["cmd.run_all"](cmd, python_shell=False)
retcode = res["retcode"]
if retcode != 0:
@ -465,7 +465,7 @@ def source_delete(source):
salt '*' imgadm.source_delete https://updates.joyent.com
"""
ret = {}
cmd = "imgadm sources -d {}".format(source)
cmd = f"imgadm sources -d {source}"
res = __salt__["cmd.run_all"](cmd)
retcode = res["retcode"]
if retcode != 0:
@ -500,7 +500,7 @@ def source_add(source, source_type="imgapi"):
if source_type not in ["imgapi", "docker"]:
log.warning("Possible unsupported imgage source type specified!")
cmd = "imgadm sources -a {} -t {}".format(source, source_type)
cmd = f"imgadm sources -a {source} -t {source_type}"
res = __salt__["cmd.run_all"](cmd)
retcode = res["retcode"]
if retcode != 0:

View file

@ -35,7 +35,7 @@ def __virtual__():
return __virtualname__
return (
False,
"{} module can only be loaded on SmartOS compute nodes".format(__virtualname__),
f"{__virtualname__} module can only be loaded on SmartOS compute nodes",
)
@ -86,7 +86,7 @@ def vms(nictag):
salt '*' nictagadm.vms admin
"""
ret = {}
cmd = "nictagadm vms {}".format(nictag)
cmd = f"nictagadm vms {nictag}"
res = __salt__["cmd.run_all"](cmd)
retcode = res["retcode"]
if retcode != 0:
@ -157,13 +157,13 @@ def add(name, mac, mtu=1500):
res = __salt__["cmd.run_all"](cmd)
# dladm prints '00' as '0', so account for that.
if mac.replace("00", "0") not in res["stdout"].splitlines():
return {"Error": "{} is not present on this system.".format(mac)}
return {"Error": f"{mac} is not present on this system."}
if mac == "etherstub":
cmd = "nictagadm add -l {}".format(name)
cmd = f"nictagadm add -l {name}"
res = __salt__["cmd.run_all"](cmd)
else:
cmd = "nictagadm add -p mtu={},mac={} {}".format(mtu, mac, name)
cmd = f"nictagadm add -p mtu={mtu},mac={mac} {name}"
res = __salt__["cmd.run_all"](cmd)
if res["retcode"] == 0:
@ -196,7 +196,7 @@ def update(name, mac=None, mtu=None):
ret = {}
if name not in list_nictags():
return {"Error": "nictag {} does not exists.".format(name)}
return {"Error": f"nictag {name} does not exists."}
if not mtu and not mac:
return {"Error": "please provide either mac or/and mtu."}
if mtu:
@ -210,16 +210,16 @@ def update(name, mac=None, mtu=None):
res = __salt__["cmd.run_all"](cmd)
# dladm prints '00' as '0', so account for that.
if mac.replace("00", "0") not in res["stdout"].splitlines():
return {"Error": "{} is not present on this system.".format(mac)}
return {"Error": f"{mac} is not present on this system."}
if mac and mtu:
properties = "mtu={},mac={}".format(mtu, mac)
properties = f"mtu={mtu},mac={mac}"
elif mac:
properties = "mac={}".format(mac) if mac else ""
properties = f"mac={mac}" if mac else ""
elif mtu:
properties = "mtu={}".format(mtu) if mtu else ""
properties = f"mtu={mtu}" if mtu else ""
cmd = "nictagadm update -p {} {}".format(properties, name)
cmd = f"nictagadm update -p {properties} {name}"
res = __salt__["cmd.run_all"](cmd)
if res["retcode"] == 0:

View file

@ -35,7 +35,7 @@ def __virtual__():
return __virtualname__
return (
False,
"{} module can only be loaded on SmartOS compute nodes".format(__virtualname__),
f"{__virtualname__} module can only be loaded on SmartOS compute nodes",
)
@ -55,7 +55,7 @@ def _create_update_from_file(mode="create", uuid=None, path=None):
"""
ret = {}
if not os.path.isfile(path) or path is None:
ret["Error"] = "File ({}) does not exists!".format(path)
ret["Error"] = f"File ({path}) does not exists!"
return ret
# vmadm validate create|update [-f <filename>]
cmd = "vmadm validate {mode} {brand} -f {path}".format(
@ -169,7 +169,7 @@ def start(vm, options=None, key="uuid"):
if key not in ["uuid", "alias", "hostname"]:
ret["Error"] = "Key must be either uuid, alias or hostname"
return ret
vm = lookup("{}={}".format(key, vm), one=True)
vm = lookup(f"{key}={vm}", one=True)
if "Error" in vm:
return vm
# vmadm start <uuid> [option=value ...]
@ -208,7 +208,7 @@ def stop(vm, force=False, key="uuid"):
if key not in ["uuid", "alias", "hostname"]:
ret["Error"] = "Key must be either uuid, alias or hostname"
return ret
vm = lookup("{}={}".format(key, vm), one=True)
vm = lookup(f"{key}={vm}", one=True)
if "Error" in vm:
return vm
# vmadm stop <uuid> [-F]
@ -245,7 +245,7 @@ def reboot(vm, force=False, key="uuid"):
if key not in ["uuid", "alias", "hostname"]:
ret["Error"] = "Key must be either uuid, alias or hostname"
return ret
vm = lookup("{}={}".format(key, vm), one=True)
vm = lookup(f"{key}={vm}", one=True)
if "Error" in vm:
return vm
# vmadm reboot <uuid> [-F]
@ -284,8 +284,8 @@ def list_vms(search=None, sort=None, order="uuid,type,ram,state,alias", keyed=Tr
ret = {}
# vmadm list [-p] [-H] [-o field,...] [-s field,...] [field=value ...]
cmd = "vmadm list -p -H {order} {sort} {search}".format(
order="-o {}".format(order) if order else "",
sort="-s {}".format(sort) if sort else "",
order=f"-o {order}" if order else "",
sort=f"-s {sort}" if sort else "",
search=search if search else "",
)
res = __salt__["cmd.run_all"](cmd)
@ -339,7 +339,7 @@ def lookup(search=None, order=None, one=False):
# vmadm lookup [-j|-1] [-o field,...] [field=value ...]
cmd = "vmadm lookup {one} {order} {search}".format(
one="-1" if one else "-j",
order="-o {}".format(order) if order else "",
order=f"-o {order}" if order else "",
search=search if search else "",
)
res = __salt__["cmd.run_all"](cmd)
@ -384,11 +384,11 @@ def sysrq(vm, action="nmi", key="uuid"):
if action not in ["nmi", "screenshot"]:
ret["Error"] = "Action must be either nmi or screenshot"
return ret
vm = lookup("{}={}".format(key, vm), one=True)
vm = lookup(f"{key}={vm}", one=True)
if "Error" in vm:
return vm
# vmadm sysrq <uuid> <nmi|screenshot>
cmd = "vmadm sysrq {uuid} {action}".format(uuid=vm, action=action)
cmd = f"vmadm sysrq {vm} {action}"
res = __salt__["cmd.run_all"](cmd)
retcode = res["retcode"]
if retcode != 0:
@ -417,11 +417,11 @@ def delete(vm, key="uuid"):
if key not in ["uuid", "alias", "hostname"]:
ret["Error"] = "Key must be either uuid, alias or hostname"
return ret
vm = lookup("{}={}".format(key, vm), one=True)
vm = lookup(f"{key}={vm}", one=True)
if "Error" in vm:
return vm
# vmadm delete <uuid>
cmd = "vmadm delete {}".format(vm)
cmd = f"vmadm delete {vm}"
res = __salt__["cmd.run_all"](cmd)
retcode = res["retcode"]
if retcode != 0:
@ -450,11 +450,11 @@ def get(vm, key="uuid"):
if key not in ["uuid", "alias", "hostname"]:
ret["Error"] = "Key must be either uuid, alias or hostname"
return ret
vm = lookup("{}={}".format(key, vm), one=True)
vm = lookup(f"{key}={vm}", one=True)
if "Error" in vm:
return vm
# vmadm get <uuid>
cmd = "vmadm get {}".format(vm)
cmd = f"vmadm get {vm}"
res = __salt__["cmd.run_all"](cmd)
retcode = res["retcode"]
if retcode != 0:
@ -501,11 +501,11 @@ def info(vm, info_type="all", key="uuid"):
if key not in ["uuid", "alias", "hostname"]:
ret["Error"] = "Key must be either uuid, alias or hostname"
return ret
vm = lookup("{}={}".format(key, vm), one=True)
vm = lookup(f"{key}={vm}", one=True)
if "Error" in vm:
return vm
# vmadm info <uuid> [type,...]
cmd = "vmadm info {uuid} {type}".format(uuid=vm, type=info_type)
cmd = f"vmadm info {vm} {info_type}"
res = __salt__["cmd.run_all"](cmd)
retcode = res["retcode"]
if retcode != 0:
@ -539,7 +539,7 @@ def create_snapshot(vm, name, key="uuid"):
if key not in ["uuid", "alias", "hostname"]:
ret["Error"] = "Key must be either uuid, alias or hostname"
return ret
vm = lookup("{}={}".format(key, vm), one=True)
vm = lookup(f"{key}={vm}", one=True)
if "Error" in vm:
return vm
vmobj = get(vm)
@ -553,7 +553,7 @@ def create_snapshot(vm, name, key="uuid"):
ret["Error"] = "VM must be running to take a snapshot"
return ret
# vmadm create-snapshot <uuid> <snapname>
cmd = "vmadm create-snapshot {uuid} {snapshot}".format(snapshot=name, uuid=vm)
cmd = f"vmadm create-snapshot {vm} {name}"
res = __salt__["cmd.run_all"](cmd)
retcode = res["retcode"]
if retcode != 0:
@ -587,7 +587,7 @@ def delete_snapshot(vm, name, key="uuid"):
if key not in ["uuid", "alias", "hostname"]:
ret["Error"] = "Key must be either uuid, alias or hostname"
return ret
vm = lookup("{}={}".format(key, vm), one=True)
vm = lookup(f"{key}={vm}", one=True)
if "Error" in vm:
return vm
vmobj = get(vm)
@ -598,7 +598,7 @@ def delete_snapshot(vm, name, key="uuid"):
ret["Error"] = "VM must be of type OS"
return ret
# vmadm delete-snapshot <uuid> <snapname>
cmd = "vmadm delete-snapshot {uuid} {snapshot}".format(snapshot=name, uuid=vm)
cmd = f"vmadm delete-snapshot {vm} {name}"
res = __salt__["cmd.run_all"](cmd)
retcode = res["retcode"]
if retcode != 0:
@ -632,7 +632,7 @@ def rollback_snapshot(vm, name, key="uuid"):
if key not in ["uuid", "alias", "hostname"]:
ret["Error"] = "Key must be either uuid, alias or hostname"
return ret
vm = lookup("{}={}".format(key, vm), one=True)
vm = lookup(f"{key}={vm}", one=True)
if "Error" in vm:
return vm
vmobj = get(vm)
@ -643,7 +643,7 @@ def rollback_snapshot(vm, name, key="uuid"):
ret["Error"] = "VM must be of type OS"
return ret
# vmadm rollback-snapshot <uuid> <snapname>
cmd = "vmadm rollback-snapshot {uuid} {snapshot}".format(snapshot=name, uuid=vm)
cmd = f"vmadm rollback-snapshot {vm} {name}"
res = __salt__["cmd.run_all"](cmd)
retcode = res["retcode"]
if retcode != 0:
@ -674,11 +674,11 @@ def reprovision(vm, image, key="uuid"):
if key not in ["uuid", "alias", "hostname"]:
ret["Error"] = "Key must be either uuid, alias or hostname"
return ret
vm = lookup("{}={}".format(key, vm), one=True)
vm = lookup(f"{key}={vm}", one=True)
if "Error" in vm:
return vm
if image not in __salt__["imgadm.list"]():
ret["Error"] = "Image ({}) is not present on this host".format(image)
ret["Error"] = f"Image ({image}) is not present on this host"
return ret
# vmadm reprovision <uuid> [-f <filename>]
cmd = "echo {image} | vmadm reprovision {uuid}".format(
@ -753,7 +753,7 @@ def update(vm, from_file=None, key="uuid", **kwargs):
if key not in ["uuid", "alias", "hostname"]:
ret["Error"] = "Key must be either uuid, alias or hostname"
return ret
uuid = lookup("{}={}".format(key, vm), one=True)
uuid = lookup(f"{key}={vm}", one=True)
if "Error" in uuid:
return uuid
@ -788,12 +788,12 @@ def send(vm, target, key="uuid"):
if not os.path.isdir(target):
ret["Error"] = "Target must be a directory or host"
return ret
vm = lookup("{}={}".format(key, vm), one=True)
vm = lookup(f"{key}={vm}", one=True)
if "Error" in vm:
return vm
# vmadm send <uuid> [target]
cmd = "vmadm send {uuid} > {target}".format(
uuid=vm, target=os.path.join(target, "{}.vmdata".format(vm))
uuid=vm, target=os.path.join(target, f"{vm}.vmdata")
)
res = __salt__["cmd.run_all"](cmd, python_shell=True)
retcode = res["retcode"]
@ -810,7 +810,7 @@ def send(vm, target, key="uuid"):
name = name[-1]
cmd = "zfs send {dataset} > {target}".format(
dataset=dataset,
target=os.path.join(target, "{}-{}.zfsds".format(vm, name)),
target=os.path.join(target, f"{vm}-{name}.zfsds"),
)
res = __salt__["cmd.run_all"](cmd, python_shell=True)
retcode = res["retcode"]
@ -839,12 +839,12 @@ def receive(uuid, source):
if not os.path.isdir(source):
ret["Error"] = "Source must be a directory or host"
return ret
if not os.path.exists(os.path.join(source, "{}.vmdata".format(uuid))):
ret["Error"] = "Unknow vm with uuid in {}".format(source)
if not os.path.exists(os.path.join(source, f"{uuid}.vmdata")):
ret["Error"] = f"Unknow vm with uuid in {source}"
return ret
# vmadm receive
cmd = "vmadm receive < {source}".format(
source=os.path.join(source, "{}.vmdata".format(uuid))
source=os.path.join(source, f"{uuid}.vmdata")
)
res = __salt__["cmd.run_all"](cmd, python_shell=True)
retcode = res["retcode"]
@ -861,14 +861,14 @@ def receive(uuid, source):
name = name[-1]
cmd = "zfs receive {dataset} < {source}".format(
dataset=dataset,
source=os.path.join(source, "{}-{}.zfsds".format(uuid, name)),
source=os.path.join(source, f"{uuid}-{name}.zfsds"),
)
res = __salt__["cmd.run_all"](cmd, python_shell=True)
retcode = res["retcode"]
if retcode != 0:
ret["Error"] = res["stderr"] if "stderr" in res else _exit_status(retcode)
return ret
cmd = "vmadm install {}".format(uuid)
cmd = f"vmadm install {uuid}"
res = __salt__["cmd.run_all"](cmd, python_shell=True)
retcode = res["retcode"]
if retcode != 0 and not res["stderr"].endswith("datasets"):

View file

@ -69,7 +69,7 @@ def _parse_fmdump(output):
# parse entries
for entry in output:
entry = [item for item in entry.split(" ") if item]
entry = ["{} {} {}".format(entry[0], entry[1], entry[2])] + entry[3:]
entry = [f"{entry[0]} {entry[1]} {entry[2]}"] + entry[3:]
# prepare faults
fault = OrderedDict()
@ -152,7 +152,7 @@ def _fmadm_action_fmri(action, fmri):
"""
ret = {}
fmadm = _check_fmadm()
cmd = "{cmd} {action} {fmri}".format(cmd=fmadm, action=action, fmri=fmri)
cmd = f"{fmadm} {action} {fmri}"
res = __salt__["cmd.run_all"](cmd)
retcode = res["retcode"]
result = {}
@ -260,8 +260,8 @@ def list_records(after=None, before=None):
fmdump = _check_fmdump()
cmd = "{cmd}{after}{before}".format(
cmd=fmdump,
after=" -t {}".format(after) if after else "",
before=" -T {}".format(before) if before else "",
after=f" -t {after}" if after else "",
before=f" -T {before}" if before else "",
)
res = __salt__["cmd.run_all"](cmd)
retcode = res["retcode"]
@ -289,7 +289,7 @@ def show(uuid):
"""
ret = {}
fmdump = _check_fmdump()
cmd = "{cmd} -u {uuid} -V".format(cmd=fmdump, uuid=uuid)
cmd = f"{fmdump} -u {uuid} -V"
res = __salt__["cmd.run_all"](cmd)
retcode = res["retcode"]
result = {}
@ -313,7 +313,7 @@ def config():
"""
ret = {}
fmadm = _check_fmadm()
cmd = "{cmd} config".format(cmd=fmadm)
cmd = f"{fmadm} config"
res = __salt__["cmd.run_all"](cmd)
retcode = res["retcode"]
result = {}
@ -340,7 +340,7 @@ def load(path):
"""
ret = {}
fmadm = _check_fmadm()
cmd = "{cmd} load {path}".format(cmd=fmadm, path=path)
cmd = f"{fmadm} load {path}"
res = __salt__["cmd.run_all"](cmd)
retcode = res["retcode"]
result = {}
@ -367,7 +367,7 @@ def unload(module):
"""
ret = {}
fmadm = _check_fmadm()
cmd = "{cmd} unload {module}".format(cmd=fmadm, module=module)
cmd = f"{fmadm} unload {module}"
res = __salt__["cmd.run_all"](cmd)
retcode = res["retcode"]
result = {}
@ -397,7 +397,7 @@ def reset(module, serd=None):
ret = {}
fmadm = _check_fmadm()
cmd = "{cmd} reset {serd}{module}".format(
cmd=fmadm, serd="-s {} ".format(serd) if serd else "", module=module
cmd=fmadm, serd=f"-s {serd} " if serd else "", module=module
)
res = __salt__["cmd.run_all"](cmd)
retcode = res["retcode"]

View file

@ -209,7 +209,7 @@ def _set_status(m, comment=INVALID_RESPONSE, status=False, out=None):
if out and isinstance(out, str):
outlog += HR
outlog += "OUTPUT:\n"
outlog += "{}\n".format(salt.utils.stringutils.to_unicode(out))
outlog += f"{salt.utils.stringutils.to_unicode(out)}\n"
outlog += HR
if m["logs"]:
outlog += HR
@ -225,7 +225,7 @@ def _set_status(m, comment=INVALID_RESPONSE, status=False, out=None):
for logger in "error", "warn", "info", "debug":
logs = m["logs_by_level"].get(logger, [])
if logs:
outlog_by_level += "\n{}:\n".format(logger.upper())
outlog_by_level += f"\n{logger.upper()}:\n"
for idx, log in enumerate(logs[:]):
logs[idx] = salt.utils.stringutils.to_unicode(log)
outlog_by_level += "\n".join(logs)
@ -287,7 +287,7 @@ def _Popen(
directory = os.path.abspath(directory)
if isinstance(command, list):
command = " ".join(command)
LOG.debug("Running {}".format(command)) # pylint: disable=str-format-in-logging
LOG.debug(f"Running {command}") # pylint: disable=str-format-in-logging
if not loglevel:
loglevel = "debug"
ret = __salt__["cmd.run_all"](
@ -499,7 +499,7 @@ def upgrade_bootstrap(
else:
buildout_ver = _get_buildout_ver(directory)
booturl = _get_bootstrap_url(directory)
LOG.debug("Using {}".format(booturl)) # pylint: disable=str-format-in-logging
LOG.debug(f"Using {booturl}") # pylint: disable=str-format-in-logging
# try to download an up-to-date bootstrap
# set defaulttimeout
# and add possible content
@ -518,7 +518,7 @@ def upgrade_bootstrap(
os.makedirs(dbuild)
# only try to download once per buildout checkout
with salt.utils.files.fopen(
os.path.join(dbuild, "{}.updated_bootstrap".format(buildout_ver))
os.path.join(dbuild, f"{buildout_ver}.updated_bootstrap")
):
pass
except OSError:
@ -537,7 +537,7 @@ def upgrade_bootstrap(
fic.write(salt.utils.stringutils.to_str(data))
if dled:
with salt.utils.files.fopen(
os.path.join(dbuild, "{}.updated_bootstrap".format(buildout_ver)), "w"
os.path.join(dbuild, f"{buildout_ver}.updated_bootstrap"), "w"
) as afic:
afic.write("foo")
except OSError:
@ -690,7 +690,7 @@ def bootstrap(
if (test_release is not False) and " --accept-buildout-test-releases" in content:
bootstrap_args += " --accept-buildout-test-releases"
if config and '"-c"' in content:
bootstrap_args += " -c {}".format(config)
bootstrap_args += f" -c {config}"
# be sure that the bootstrap belongs to the running user
try:
if runas:
@ -704,7 +704,7 @@ def bootstrap(
exc,
exc_info=_logger.isEnabledFor(logging.DEBUG),
)
cmd = "{} bootstrap.py {}".format(python, bootstrap_args)
cmd = f"{python} bootstrap.py {bootstrap_args}"
ret = _Popen(
cmd, directory=directory, runas=runas, loglevel=loglevel, env=env, use_vt=use_vt
)
@ -793,7 +793,7 @@ def run_buildout(
if parts:
for part in parts:
LOG.info(
"Installing single part: {}".format(part)
f"Installing single part: {part}"
) # pylint: disable=str-format-in-logging
cmd = "{} -c {} {} install {}".format(bcmd, config, " ".join(argv), part)
cmds.append(cmd)
@ -847,7 +847,7 @@ def _merge_statuses(statuses):
status["out"] += "\n"
status["out"] += HR
out = salt.utils.stringutils.to_unicode(out)
status["out"] += "{}\n".format(out)
status["out"] += f"{out}\n"
status["out"] += HR
if comment:
if not status["comment"]:
@ -859,12 +859,12 @@ def _merge_statuses(statuses):
if not status["outlog"]:
status["outlog"] = ""
outlog = salt.utils.stringutils.to_unicode(outlog)
status["outlog"] += "\n{}".format(HR)
status["outlog"] += f"\n{HR}"
status["outlog"] += outlog
if outlog_by_level:
if not status["outlog_by_level"]:
status["outlog_by_level"] = ""
status["outlog_by_level"] += "\n{}".format(HR)
status["outlog_by_level"] += f"\n{HR}"
status["outlog_by_level"] += salt.utils.stringutils.to_unicode(
outlog_by_level
)
@ -961,7 +961,7 @@ def buildout(
salt '*' buildout.buildout /srv/mybuildout
"""
LOG.info(
"Running buildout in {} ({})".format(directory, config)
f"Running buildout in {directory} ({config})"
) # pylint: disable=str-format-in-logging
boot_ret = bootstrap(
directory,

View file

@ -64,7 +64,7 @@ def __virtual__():
return __virtualname__
return (
False,
"{} module can only be loaded in a solaris globalzone.".format(__virtualname__),
f"{__virtualname__} module can only be loaded in a solaris globalzone.",
)
@ -145,18 +145,18 @@ def boot(zone, single=False, altinit=None, smf_options=None):
## build boot_options
boot_options = ""
if single:
boot_options = "-s {}".format(boot_options)
boot_options = f"-s {boot_options}"
if altinit: # note: we cannot validate the path, as this is local to the zonepath.
boot_options = "-i {} {}".format(altinit, boot_options)
boot_options = f"-i {altinit} {boot_options}"
if smf_options:
boot_options = "-m {} {}".format(smf_options, boot_options)
boot_options = f"-m {smf_options} {boot_options}"
if boot_options != "":
boot_options = " -- {}".format(boot_options.strip())
boot_options = f" -- {boot_options.strip()}"
## execute boot
res = __salt__["cmd.run_all"](
"zoneadm {zone} boot{boot_opts}".format(
zone="-u {}".format(zone) if _is_uuid(zone) else "-z {}".format(zone),
zone=f"-u {zone}" if _is_uuid(zone) else f"-z {zone}",
boot_opts=boot_options,
)
)
@ -195,18 +195,18 @@ def reboot(zone, single=False, altinit=None, smf_options=None):
## build boot_options
boot_options = ""
if single:
boot_options = "-s {}".format(boot_options)
boot_options = f"-s {boot_options}"
if altinit: # note: we cannot validate the path, as this is local to the zonepath.
boot_options = "-i {} {}".format(altinit, boot_options)
boot_options = f"-i {altinit} {boot_options}"
if smf_options:
boot_options = "-m {} {}".format(smf_options, boot_options)
boot_options = f"-m {smf_options} {boot_options}"
if boot_options != "":
boot_options = " -- {}".format(boot_options.strip())
boot_options = f" -- {boot_options.strip()}"
## execute reboot
res = __salt__["cmd.run_all"](
"zoneadm {zone} reboot{boot_opts}".format(
zone="-u {}".format(zone) if _is_uuid(zone) else "-z {}".format(zone),
zone=f"-u {zone}" if _is_uuid(zone) else f"-z {zone}",
boot_opts=boot_options,
)
)
@ -240,7 +240,7 @@ def halt(zone):
## halt zone
res = __salt__["cmd.run_all"](
"zoneadm {zone} halt".format(
zone="-u {}".format(zone) if _is_uuid(zone) else "-z {}".format(zone),
zone=f"-u {zone}" if _is_uuid(zone) else f"-z {zone}",
)
)
ret["status"] = res["retcode"] == 0
@ -280,18 +280,18 @@ def shutdown(zone, reboot=False, single=False, altinit=None, smf_options=None):
## build boot_options
boot_options = ""
if single:
boot_options = "-s {}".format(boot_options)
boot_options = f"-s {boot_options}"
if altinit: # note: we cannot validate the path, as this is local to the zonepath.
boot_options = "-i {} {}".format(altinit, boot_options)
boot_options = f"-i {altinit} {boot_options}"
if smf_options:
boot_options = "-m {} {}".format(smf_options, boot_options)
boot_options = f"-m {smf_options} {boot_options}"
if boot_options != "":
boot_options = " -- {}".format(boot_options.strip())
boot_options = f" -- {boot_options.strip()}"
## shutdown zone
res = __salt__["cmd.run_all"](
"zoneadm {zone} shutdown{reboot}{boot_opts}".format(
zone="-u {}".format(zone) if _is_uuid(zone) else "-z {}".format(zone),
zone=f"-u {zone}" if _is_uuid(zone) else f"-z {zone}",
reboot=" -r" if reboot else "",
boot_opts=boot_options,
)
@ -323,7 +323,7 @@ def detach(zone):
## detach zone
res = __salt__["cmd.run_all"](
"zoneadm {zone} detach".format(
zone="-u {}".format(zone) if _is_uuid(zone) else "-z {}".format(zone),
zone=f"-u {zone}" if _is_uuid(zone) else f"-z {zone}",
)
)
ret["status"] = res["retcode"] == 0
@ -360,7 +360,7 @@ def attach(zone, force=False, brand_opts=None):
"zoneadm -z {zone} attach{force}{brand_opts}".format(
zone=zone,
force=" -F" if force else "",
brand_opts=" {}".format(brand_opts) if brand_opts else "",
brand_opts=f" {brand_opts}" if brand_opts else "",
)
)
ret["status"] = res["retcode"] == 0
@ -390,7 +390,7 @@ def ready(zone):
## ready zone
res = __salt__["cmd.run_all"](
"zoneadm {zone} ready".format(
zone="-u {}".format(zone) if _is_uuid(zone) else "-z {}".format(zone),
zone=f"-u {zone}" if _is_uuid(zone) else f"-z {zone}",
)
)
ret["status"] = res["retcode"] == 0
@ -453,7 +453,7 @@ def move(zone, zonepath):
## verify zone
res = __salt__["cmd.run_all"](
"zoneadm {zone} move {path}".format(
zone="-u {}".format(zone) if _is_uuid(zone) else "-z {}".format(zone),
zone=f"-u {zone}" if _is_uuid(zone) else f"-z {zone}",
path=zonepath,
)
)
@ -487,7 +487,7 @@ def uninstall(zone):
## uninstall zone
res = __salt__["cmd.run_all"](
"zoneadm {zone} uninstall -F".format(
zone="-u {}".format(zone) if _is_uuid(zone) else "-z {}".format(zone),
zone=f"-u {zone}" if _is_uuid(zone) else f"-z {zone}",
)
)
ret["status"] = res["retcode"] == 0
@ -524,7 +524,7 @@ def install(zone, nodataset=False, brand_opts=None):
"zoneadm -z {zone} install{nodataset}{brand_opts}".format(
zone=zone,
nodataset=" -x nodataset" if nodataset else "",
brand_opts=" {}".format(brand_opts) if brand_opts else "",
brand_opts=f" {brand_opts}" if brand_opts else "",
)
)
ret["status"] = res["retcode"] == 0
@ -560,7 +560,7 @@ def clone(zone, source, snapshot=None):
"zoneadm -z {zone} clone {snapshot}{source}".format(
zone=zone,
source=source,
snapshot="-s {} ".format(snapshot) if snapshot else "",
snapshot=f"-s {snapshot} " if snapshot else "",
)
)
ret["status"] = res["retcode"] == 0

View file

@ -110,7 +110,7 @@ def __virtual__():
return __virtualname__
return (
False,
"{} module can only be loaded in a solaris globalzone.".format(__virtualname__),
f"{__virtualname__} module can only be loaded in a solaris globalzone.",
)
@ -195,7 +195,7 @@ def _sanitize_value(value):
return "".join(str(v) for v in new_value).replace(",)", ")")
else:
# note: we can't use shelx or pipes quote here because it makes zonecfg barf
return '"{}"'.format(value) if " " in value else value
return f'"{value}"' if " " in value else value
def _dump_cfg(cfg_file):
@ -233,13 +233,13 @@ def create(zone, brand, zonepath, force=False):
cfg_file = salt.utils.files.mkstemp()
with salt.utils.files.fpopen(cfg_file, "w+", mode=0o600) as fp_:
fp_.write("create -b -F\n" if force else "create -b\n")
fp_.write("set brand={}\n".format(_sanitize_value(brand)))
fp_.write("set zonepath={}\n".format(_sanitize_value(zonepath)))
fp_.write(f"set brand={_sanitize_value(brand)}\n")
fp_.write(f"set zonepath={_sanitize_value(zonepath)}\n")
# create
if not __salt__["file.directory_exists"](zonepath):
__salt__["file.makedirs_perms"](
zonepath if zonepath[-1] == "/" else "{}/".format(zonepath), mode="0700"
zonepath if zonepath[-1] == "/" else f"{zonepath}/", mode="0700"
)
_dump_cfg(cfg_file)
@ -354,7 +354,7 @@ def export(zone, path=None):
res = __salt__["cmd.run_all"](
"zonecfg -z {zone} export{path}".format(
zone=zone,
path=" -f {}".format(path) if path else "",
path=f" -f {path}" if path else "",
)
)
ret["status"] = res["retcode"] == 0
@ -422,7 +422,7 @@ def _property(methode, zone, key, value):
cfg_file = None
if methode not in ["set", "clear"]:
ret["status"] = False
ret["message"] = "unkown methode {}!".format(methode)
ret["message"] = f"unkown methode {methode}!"
else:
cfg_file = salt.utils.files.mkstemp()
with salt.utils.files.fpopen(cfg_file, "w+", mode=0o600) as fp_:
@ -430,9 +430,9 @@ def _property(methode, zone, key, value):
if isinstance(value, dict) or isinstance(value, list):
value = _sanitize_value(value)
value = str(value).lower() if isinstance(value, bool) else str(value)
fp_.write("{} {}={}\n".format(methode, key, _sanitize_value(value)))
fp_.write(f"{methode} {key}={_sanitize_value(value)}\n")
elif methode == "clear":
fp_.write("{} {}\n".format(methode, key))
fp_.write(f"{methode} {key}\n")
# update property
if cfg_file:
@ -530,7 +530,7 @@ def _resource(methode, zone, resource_type, resource_selector, **kwargs):
kwargs[k] = _sanitize_value(kwargs[k])
if methode not in ["add", "update"]:
ret["status"] = False
ret["message"] = "unknown methode {}".format(methode)
ret["message"] = f"unknown methode {methode}"
return ret
if methode in ["update"] and resource_selector and resource_selector not in kwargs:
ret["status"] = False
@ -543,7 +543,7 @@ def _resource(methode, zone, resource_type, resource_selector, **kwargs):
cfg_file = salt.utils.files.mkstemp()
with salt.utils.files.fpopen(cfg_file, "w+", mode=0o600) as fp_:
if methode in ["add"]:
fp_.write("add {}\n".format(resource_type))
fp_.write(f"add {resource_type}\n")
elif methode in ["update"]:
if resource_selector:
value = kwargs[resource_selector]
@ -556,7 +556,7 @@ def _resource(methode, zone, resource_type, resource_selector, **kwargs):
)
)
else:
fp_.write("select {}\n".format(resource_type))
fp_.write(f"select {resource_type}\n")
for k, v in kwargs.items():
if methode in ["update"] and k == resource_selector:
continue
@ -564,9 +564,9 @@ def _resource(methode, zone, resource_type, resource_selector, **kwargs):
value = _sanitize_value(value)
value = str(v).lower() if isinstance(v, bool) else str(v)
if k in _zonecfg_resource_setters[resource_type]:
fp_.write("set {}={}\n".format(k, _sanitize_value(value)))
fp_.write(f"set {k}={_sanitize_value(value)}\n")
else:
fp_.write("add {} {}\n".format(k, _sanitize_value(value)))
fp_.write(f"add {k} {_sanitize_value(value)}\n")
fp_.write("end\n")
# update property
@ -671,7 +671,7 @@ def remove_resource(zone, resource_type, resource_key, resource_value):
)
)
else:
fp_.write("remove {}\n".format(resource_type))
fp_.write(f"remove {resource_type}\n")
# update property
if cfg_file:

View file

@ -100,7 +100,7 @@ def _action(action="get", search=None, one=True, force=False):
## multiple allowed?
if one and len(matched_vms) > 1:
return {
"Error": "Matched {} vms, only one allowed!".format(len(matched_vms)),
"Error": f"Matched {len(matched_vms)} vms, only one allowed!",
"Matches": matched_vms,
}
@ -111,7 +111,7 @@ def _action(action="get", search=None, one=True, force=False):
vmadm_args = {"key": "uuid", "vm": vm}
try:
for vmadm_res in client.cmd_iter(
vms[vm]["node"], "vmadm.{}".format(action), kwarg=vmadm_args
vms[vm]["node"], f"vmadm.{action}", kwarg=vmadm_args
):
if not vmadm_res:
continue
@ -188,7 +188,7 @@ def nodes(verbose=False):
else:
ret.append(node)
except SaltClientError as client_error:
return "{}".format(client_error)
return f"{client_error}"
if not verbose:
ret.sort()
@ -256,7 +256,7 @@ def list_vms(search=None, verbose=False):
else:
ret.append(vm)
except SaltClientError as client_error:
return "{}".format(client_error)
return f"{client_error}"
if not verbose:
ret = sorted(ret)

View file

@ -74,7 +74,7 @@ def present(name, timespec, tag=None, user=None, job=None, unique_tag=False):
ret["comment"] = "no tag provided and unique_tag is set to True"
return ret
elif len(__salt__["at.jobcheck"](tag=tag)["jobs"]) > 0:
ret["comment"] = "atleast one job with tag {tag} exists.".format(tag=tag)
ret["comment"] = f"atleast one job with tag {tag} exists."
return ret
# create job
@ -82,7 +82,7 @@ def present(name, timespec, tag=None, user=None, job=None, unique_tag=False):
luser = __salt__["user.info"](user)
if not luser:
ret["result"] = False
ret["comment"] = "user {} does not exists".format(user)
ret["comment"] = f"user {user} does not exists"
return ret
ret["comment"] = "job {} added and will run as {} on {}".format(
job,
@ -176,7 +176,7 @@ def absent(name, jobid=None, **kwargs):
# limit was never support
if "limit" in kwargs:
ret["comment"] = "limit parameter not supported {}".format(name)
ret["comment"] = f"limit parameter not supported {name}"
ret["result"] = False
return ret
@ -191,7 +191,7 @@ def absent(name, jobid=None, **kwargs):
jobs = __salt__["at.atq"](jobid)
if "jobs" in jobs and len(jobs["jobs"]) == 0:
ret["result"] = True
ret["comment"] = "job with id {jobid} not present".format(jobid=jobid)
ret["comment"] = f"job with id {jobid} not present"
return ret
elif "jobs" in jobs and len(jobs["jobs"]) == 1:
if "job" in jobs["jobs"][0] and jobs["jobs"][0]["job"]:

View file

@ -152,12 +152,12 @@ def remove(name, log_file=None):
res = __salt__["logadm.remove"](name if name else log_file)
ret["result"] = "Error" not in res
if ret["result"]:
ret["comment"] = "Configuration for {} removed.".format(log_file)
ret["comment"] = f"Configuration for {log_file} removed."
ret["changes"][log_file] = None
else:
ret["comment"] = res["Error"]
else:
ret["result"] = True
ret["comment"] = "No configuration for {} present.".format(log_file)
ret["comment"] = f"No configuration for {log_file} present."
return ret

View file

@ -63,7 +63,7 @@ def absent(name):
elif res[name] not in ["absent"]: # oops something went wrong
ret["result"] = False
else:
ret["comment"] = "account {login} is absent".format(login=name)
ret["comment"] = f"account {name} is absent"
return ret

View file

@ -241,7 +241,7 @@ def present(name, **kwargs):
new_item["enabled"] = True
if new_item == current_schedule[name]:
ret["comment"].append("Job {} in correct state".format(name))
ret["comment"].append(f"Job {name} in correct state")
else:
if "test" in __opts__ and __opts__["test"]:
kwargs["test"] = True
@ -255,7 +255,7 @@ def present(name, **kwargs):
ret["comment"] = result["comment"]
return ret
else:
ret["comment"].append("Modifying job {} in schedule".format(name))
ret["comment"].append(f"Modifying job {name} in schedule")
ret["changes"] = result["changes"]
else:
if "test" in __opts__ and __opts__["test"]:
@ -269,7 +269,7 @@ def present(name, **kwargs):
ret["comment"] = result["comment"]
return ret
else:
ret["comment"].append("Adding new job {} to schedule".format(name))
ret["comment"].append(f"Adding new job {name} to schedule")
ret["changes"] = result["changes"]
ret["comment"] = "\n".join(ret["comment"])
@ -308,10 +308,10 @@ def absent(name, **kwargs):
ret["comment"] = result["comment"]
return ret
else:
ret["comment"].append("Removed job {} from schedule".format(name))
ret["comment"].append(f"Removed job {name} from schedule")
ret["changes"] = result["changes"]
else:
ret["comment"].append("Job {} not present in schedule".format(name))
ret["comment"].append(f"Job {name} not present in schedule")
ret["comment"] = "\n".join(ret["comment"])
return ret
@ -345,9 +345,9 @@ def enabled(name, **kwargs):
ret["comment"] = result["comment"]
return ret
else:
ret["comment"].append("Enabled job {} from schedule".format(name))
ret["comment"].append(f"Enabled job {name} from schedule")
else:
ret["comment"].append("Job {} not present in schedule".format(name))
ret["comment"].append(f"Job {name} not present in schedule")
ret["comment"] = "\n".join(ret["comment"])
return ret
@ -384,9 +384,9 @@ def disabled(name, **kwargs):
ret["comment"] = result["comment"]
return ret
else:
ret["comment"].append("Disabled job {} from schedule".format(name))
ret["comment"].append(f"Disabled job {name} from schedule")
else:
ret["comment"].append("Job {} not present in schedule".format(name))
ret["comment"].append(f"Job {name} not present in schedule")
ret["comment"] = "\n".join(ret["comment"])
return ret

View file

@ -213,9 +213,9 @@ def _write_config(config):
if not config[prop].startswith('"') or not config[prop].endswith(
'"'
):
config[prop] = '"{}"'.format(config[prop])
config[prop] = f'"{config[prop]}"'
config_file.write(
salt.utils.stringutils.to_str("{}={}\n".format(prop, config[prop]))
salt.utils.stringutils.to_str(f"{prop}={config[prop]}\n")
)
log.debug("smartos.config - wrote /usbkey/config: %s", config)
except OSError:
@ -299,7 +299,7 @@ def _copy_lx_vars(vmconfig):
for var in imgtags.get("docker:config", {}):
val = imgtags["docker:config"][var]
var = "docker:{}".format(var.lower())
var = f"docker:{var.lower()}"
# NOTE: skip empty values
if not val:
@ -321,7 +321,7 @@ def _copy_lx_vars(vmconfig):
):
config_env_var = config_env_var.split("=")
for img_env_var in val:
if img_env_var.startswith("{}=".format(config_env_var[0])):
if img_env_var.startswith(f"{config_env_var[0]}="):
val.remove(img_env_var)
val.append("=".join(config_env_var))
elif var in vmconfig["internal_metadata"]:
@ -362,17 +362,17 @@ def config_present(name, value):
if str(config[name]) == str(value):
# we're good
ret["result"] = True
ret["comment"] = 'property {} already has value "{}"'.format(name, value)
ret["comment"] = f'property {name} already has value "{value}"'
else:
# update property
ret["result"] = True
ret["comment"] = 'updated property {} with value "{}"'.format(name, value)
ret["comment"] = f'updated property {name} with value "{value}"'
ret["changes"][name] = value
config[name] = value
else:
# add property
ret["result"] = True
ret["comment"] = 'added property {} with value "{}"'.format(name, value)
ret["comment"] = f'added property {name} with value "{value}"'
ret["changes"][name] = value
config[name] = value
@ -407,13 +407,13 @@ def config_absent(name):
if name in config:
# delete property
ret["result"] = True
ret["comment"] = "property {} deleted".format(name)
ret["comment"] = f"property {name} deleted"
ret["changes"][name] = None
del config[name]
else:
# we're good
ret["result"] = True
ret["comment"] = "property {} is absent".format(name)
ret["comment"] = f"property {name} is absent"
# apply change if needed
if not __opts__["test"] and ret["changes"]:
@ -436,7 +436,7 @@ def source_present(name, source_type="imgapi"):
if name in __salt__["imgadm.sources"]():
# source is present
ret["result"] = True
ret["comment"] = "image source {} is present".format(name)
ret["comment"] = f"image source {name} is present"
else:
# add new source
if __opts__["test"]:
@ -447,10 +447,10 @@ def source_present(name, source_type="imgapi"):
ret["result"] = name in res
if ret["result"]:
ret["comment"] = "image source {} added".format(name)
ret["comment"] = f"image source {name} added"
ret["changes"][name] = "added"
else:
ret["comment"] = "image source {} not added".format(name)
ret["comment"] = f"image source {name} not added"
if "Error" in res:
ret["comment"] = "{}: {}".format(ret["comment"], res["Error"])
@ -469,7 +469,7 @@ def source_absent(name):
if name not in __salt__["imgadm.sources"]():
# source is absent
ret["result"] = True
ret["comment"] = "image source {} is absent".format(name)
ret["comment"] = f"image source {name} is absent"
else:
# remove source
if __opts__["test"]:
@ -480,10 +480,10 @@ def source_absent(name):
ret["result"] = name not in res
if ret["result"]:
ret["comment"] = "image source {} deleted".format(name)
ret["comment"] = f"image source {name} deleted"
ret["changes"][name] = "deleted"
else:
ret["comment"] = "image source {} not deleted".format(name)
ret["comment"] = f"image source {name} not deleted"
if "Error" in res:
ret["comment"] = "{}: {}".format(ret["comment"], res["Error"])
@ -509,7 +509,7 @@ def image_present(name):
elif name in __salt__["imgadm.list"]():
# image was already imported
ret["result"] = True
ret["comment"] = "image {} is present".format(name)
ret["comment"] = f"image {name} is present"
else:
# add image
if _is_docker_uuid(name):
@ -533,13 +533,13 @@ def image_present(name):
elif _is_docker_uuid(name):
ret["result"] = __salt__["imgadm.docker_to_uuid"](name) is not None
if ret["result"]:
ret["comment"] = "image {} imported".format(name)
ret["comment"] = f"image {name} imported"
ret["changes"] = res
else:
ret["comment"] = "image {} was unable to be imported".format(name)
ret["comment"] = f"image {name} was unable to be imported"
else:
ret["result"] = False
ret["comment"] = "image {} does not exists".format(name)
ret["comment"] = f"image {name} does not exists"
return ret
@ -567,12 +567,12 @@ def image_absent(name):
if not uuid or uuid not in __salt__["imgadm.list"]():
# image not imported
ret["result"] = True
ret["comment"] = "image {} is absent".format(name)
ret["comment"] = f"image {name} is absent"
else:
# check if image in use by vm
if uuid in __salt__["vmadm.list"](order="image_uuid"):
ret["result"] = False
ret["comment"] = "image {} currently in use by a vm".format(name)
ret["comment"] = f"image {name} currently in use by a vm"
else:
# delete image
if __opts__["test"]:
@ -599,7 +599,7 @@ def image_absent(name):
name, image_count
)
else:
ret["comment"] = "image {} deleted".format(name)
ret["comment"] = f"image {name} deleted"
ret["changes"][name] = None
return ret
@ -905,7 +905,7 @@ def vm_present(name, vmconfig, config=None):
continue
# enforcement
enforce = config["enforce_{}".format(collection)]
enforce = config[f"enforce_{collection}"]
log.debug("smartos.vm_present::enforce_%s = %s", collection, enforce)
# dockerinit handling
@ -940,13 +940,13 @@ def vm_present(name, vmconfig, config=None):
continue
# create set_ dict
if "set_{}".format(collection) not in vmconfig["changed"]:
vmconfig["changed"]["set_{}".format(collection)] = {}
if f"set_{collection}" not in vmconfig["changed"]:
vmconfig["changed"][f"set_{collection}"] = {}
# add property to changeset
vmconfig["changed"]["set_{}".format(collection)][prop] = vmconfig[
"state"
][collection][prop]
vmconfig["changed"][f"set_{collection}"][prop] = vmconfig["state"][
collection
][prop]
# process remove for collection
if (
@ -964,11 +964,11 @@ def vm_present(name, vmconfig, config=None):
continue
# create remove_ array
if "remove_{}".format(collection) not in vmconfig["changed"]:
vmconfig["changed"]["remove_{}".format(collection)] = []
if f"remove_{collection}" not in vmconfig["changed"]:
vmconfig["changed"][f"remove_{collection}"] = []
# remove property
vmconfig["changed"]["remove_{}".format(collection)].append(prop)
vmconfig["changed"][f"remove_{collection}"].append(prop)
# process instances
for instance in vmconfig_type["instance"]:
@ -1018,28 +1018,23 @@ def vm_present(name, vmconfig, config=None):
# update instance
if update_cfg:
# create update_ array
if (
"update_{}".format(instance)
not in vmconfig["changed"]
):
vmconfig["changed"][
"update_{}".format(instance)
] = []
if f"update_{instance}" not in vmconfig["changed"]:
vmconfig["changed"][f"update_{instance}"] = []
update_cfg[
vmconfig_type["instance"][instance]
] = state_cfg[vmconfig_type["instance"][instance]]
vmconfig["changed"][
"update_{}".format(instance)
].append(update_cfg)
vmconfig["changed"][f"update_{instance}"].append(
update_cfg
)
if add_instance:
# create add_ array
if "add_{}".format(instance) not in vmconfig["changed"]:
vmconfig["changed"]["add_{}".format(instance)] = []
if f"add_{instance}" not in vmconfig["changed"]:
vmconfig["changed"][f"add_{instance}"] = []
# add instance
vmconfig["changed"]["add_{}".format(instance)].append(state_cfg)
vmconfig["changed"][f"add_{instance}"].append(state_cfg)
# remove instances
if (
@ -1067,11 +1062,11 @@ def vm_present(name, vmconfig, config=None):
if remove_instance:
# create remove_ array
if "remove_{}".format(instance) not in vmconfig["changed"]:
vmconfig["changed"]["remove_{}".format(instance)] = []
if f"remove_{instance}" not in vmconfig["changed"]:
vmconfig["changed"][f"remove_{instance}"] = []
# remove instance
vmconfig["changed"]["remove_{}".format(instance)].append(
vmconfig["changed"][f"remove_{instance}"].append(
current_cfg[vmconfig_type["instance"][instance]]
)
@ -1221,7 +1216,7 @@ def vm_absent(name, archive=False):
if name not in __salt__["vmadm.list"](order="hostname"):
# we're good
ret["result"] = True
ret["comment"] = "vm {} is absent".format(name)
ret["comment"] = f"vm {name} is absent"
else:
# delete vm
if not __opts__["test"]:
@ -1237,9 +1232,9 @@ def vm_absent(name, archive=False):
if not isinstance(ret["result"], bool) and ret["result"].get("Error"):
ret["result"] = False
ret["comment"] = "failed to delete vm {}".format(name)
ret["comment"] = f"failed to delete vm {name}"
else:
ret["comment"] = "vm {} deleted".format(name)
ret["comment"] = f"vm {name} deleted"
ret["changes"][name] = None
return ret
@ -1263,7 +1258,7 @@ def vm_running(name):
if name in __salt__["vmadm.list"](order="hostname", search="state=running"):
# we're good
ret["result"] = True
ret["comment"] = "vm {} already running".format(name)
ret["comment"] = f"vm {name} already running"
else:
# start the vm
ret["result"] = (
@ -1271,10 +1266,10 @@ def vm_running(name):
)
if not isinstance(ret["result"], bool) and ret["result"].get("Error"):
ret["result"] = False
ret["comment"] = "failed to start {}".format(name)
ret["comment"] = f"failed to start {name}"
else:
ret["changes"][name] = "running"
ret["comment"] = "vm {} started".format(name)
ret["comment"] = f"vm {name} started"
return ret
@ -1297,7 +1292,7 @@ def vm_stopped(name):
if name in __salt__["vmadm.list"](order="hostname", search="state=stopped"):
# we're good
ret["result"] = True
ret["comment"] = "vm {} already stopped".format(name)
ret["comment"] = f"vm {name} already stopped"
else:
# stop the vm
ret["result"] = (
@ -1305,9 +1300,9 @@ def vm_stopped(name):
)
if not isinstance(ret["result"], bool) and ret["result"].get("Error"):
ret["result"] = False
ret["comment"] = "failed to stop {}".format(name)
ret["comment"] = f"failed to stop {name}"
else:
ret["changes"][name] = "stopped"
ret["comment"] = "vm {} stopped".format(name)
ret["comment"] = f"vm {name} stopped"
return ret

View file

@ -118,7 +118,7 @@ def _absent(name, dataset_type, force=False, recursive=False):
ret["comment"] = mod_res["error"]
else:
## NOTE: no dataset found with name of the dataset_type
ret["comment"] = "{} {} is absent".format(dataset_type, name)
ret["comment"] = f"{dataset_type} {name} is absent"
return ret
@ -145,7 +145,7 @@ def filesystem_absent(name, force=False, recursive=False):
"name": name,
"changes": {},
"result": False,
"comment": "invalid dataset name: {}".format(name),
"comment": f"invalid dataset name: {name}",
}
else:
ret = _absent(name, "filesystem", force, recursive)
@ -174,7 +174,7 @@ def volume_absent(name, force=False, recursive=False):
"name": name,
"changes": {},
"result": False,
"comment": "invalid dataset name: {}".format(name),
"comment": f"invalid dataset name: {name}",
}
else:
ret = _absent(name, "volume", force, recursive)
@ -198,7 +198,7 @@ def snapshot_absent(name, force=False, recursive=False):
"name": name,
"changes": {},
"result": False,
"comment": "invalid snapshot name: {}".format(name),
"comment": f"invalid snapshot name: {name}",
}
else:
ret = _absent(name, "snapshot", force, recursive)
@ -222,7 +222,7 @@ def bookmark_absent(name, force=False, recursive=False):
"name": name,
"changes": {},
"result": False,
"comment": "invalid bookmark name: {}".format(name),
"comment": f"invalid bookmark name: {name}",
}
else:
ret = _absent(name, "bookmark", force, recursive)
@ -250,7 +250,7 @@ def hold_absent(name, snapshot, recursive=False):
## check we have a snapshot/tag name
if not __utils__["zfs.is_snapshot"](snapshot):
ret["result"] = False
ret["comment"] = "invalid snapshot name: {}".format(snapshot)
ret["comment"] = f"invalid snapshot name: {snapshot}"
return ret
if (
@ -259,7 +259,7 @@ def hold_absent(name, snapshot, recursive=False):
or name == "error"
):
ret["result"] = False
ret["comment"] = "invalid tag name: {}".format(name)
ret["comment"] = f"invalid tag name: {name}"
return ret
## release hold if required
@ -319,7 +319,7 @@ def hold_present(name, snapshot, recursive=False):
## check we have a snapshot/tag name
if not __utils__["zfs.is_snapshot"](snapshot):
ret["result"] = False
ret["comment"] = "invalid snapshot name: {}".format(snapshot)
ret["comment"] = f"invalid snapshot name: {snapshot}"
return ret
if (
@ -328,7 +328,7 @@ def hold_present(name, snapshot, recursive=False):
or name == "error"
):
ret["result"] = False
ret["comment"] = "invalid tag name: {}".format(name)
ret["comment"] = f"invalid tag name: {name}"
return ret
## place hold if required
@ -349,9 +349,9 @@ def hold_present(name, snapshot, recursive=False):
ret["result"] = mod_res["held"]
if ret["result"]:
ret["changes"] = OrderedDict([(snapshot, OrderedDict([(name, "held")]))])
ret["comment"] = "hold {} added to {}".format(name, snapshot)
ret["comment"] = f"hold {name} added to {snapshot}"
else:
ret["comment"] = "failed to add hold {} to {}".format(name, snapshot)
ret["comment"] = f"failed to add hold {name} to {snapshot}"
if "error" in mod_res:
ret["comment"] = mod_res["error"]
@ -440,19 +440,19 @@ def _dataset_present(
## check we have valid filesystem name/volume name/clone snapshot
if not __utils__["zfs.is_dataset"](name):
ret["result"] = False
ret["comment"] = "invalid dataset name: {}".format(name)
ret["comment"] = f"invalid dataset name: {name}"
return ret
if cloned_from and not __utils__["zfs.is_snapshot"](cloned_from):
ret["result"] = False
ret["comment"] = "{} is not a snapshot".format(cloned_from)
ret["comment"] = f"{cloned_from} is not a snapshot"
return ret
## ensure dataset is in correct state
## NOTE: update the dataset
exists = __salt__["zfs.exists"](name, **{"type": dataset_type})
if exists and len(properties) == 0:
ret["comment"] = "{} {} is uptodate".format(dataset_type, name)
ret["comment"] = f"{dataset_type} {name} is uptodate"
elif exists and len(properties) > 0:
## NOTE: fetch current volume properties
properties_current = __salt__["zfs.get"](
@ -500,11 +500,11 @@ def _dataset_present(
## NOTE: update comment
if ret["result"] and name in ret["changes"]:
ret["comment"] = "{} {} was updated".format(dataset_type, name)
ret["comment"] = f"{dataset_type} {name} was updated"
elif ret["result"]:
ret["comment"] = "{} {} is uptodate".format(dataset_type, name)
ret["comment"] = f"{dataset_type} {name} is uptodate"
else:
ret["comment"] = "{} {} failed to be updated".format(dataset_type, name)
ret["comment"] = f"{dataset_type} {name} failed to be updated"
## NOTE: create or clone the dataset
elif not exists:
@ -521,7 +521,7 @@ def _dataset_present(
mod_res = __salt__["zfs.clone"](
cloned_from,
name,
**{"create_parent": create_parent, "properties": properties}
**{"create_parent": create_parent, "properties": properties},
)
else:
## NOTE: create the dataset
@ -532,7 +532,7 @@ def _dataset_present(
"properties": properties,
"volume_size": volume_size,
"sparse": sparse,
}
},
)
ret["result"] = mod_res[mod_res_action]
@ -658,7 +658,7 @@ def bookmark_present(name, snapshot):
## check we have valid snapshot/bookmark name
if not __utils__["zfs.is_snapshot"](snapshot):
ret["result"] = False
ret["comment"] = "invalid snapshot name: {}".format(name)
ret["comment"] = f"invalid snapshot name: {name}"
return ret
if "#" not in name and "/" not in name:
@ -670,7 +670,7 @@ def bookmark_present(name, snapshot):
if not __utils__["zfs.is_bookmark"](name):
ret["result"] = False
ret["comment"] = "invalid bookmark name: {}".format(name)
ret["comment"] = f"invalid bookmark name: {name}"
return ret
## ensure bookmark exists
@ -684,9 +684,9 @@ def bookmark_present(name, snapshot):
ret["result"] = mod_res["bookmarked"]
if ret["result"]:
ret["changes"][name] = snapshot
ret["comment"] = "{} bookmarked as {}".format(snapshot, name)
ret["comment"] = f"{snapshot} bookmarked as {name}"
else:
ret["comment"] = "failed to bookmark {}".format(snapshot)
ret["comment"] = f"failed to bookmark {snapshot}"
if "error" in mod_res:
ret["comment"] = mod_res["error"]
else:
@ -724,7 +724,7 @@ def snapshot_present(name, recursive=False, properties=None):
## check we have valid snapshot name
if not __utils__["zfs.is_snapshot"](name):
ret["result"] = False
ret["comment"] = "invalid snapshot name: {}".format(name)
ret["comment"] = f"invalid snapshot name: {name}"
return ret
## ensure snapshot exits
@ -742,9 +742,9 @@ def snapshot_present(name, recursive=False, properties=None):
ret["changes"][name] = "snapshotted"
if properties:
ret["changes"][name] = properties
ret["comment"] = "snapshot {} was created".format(name)
ret["comment"] = f"snapshot {name} was created"
else:
ret["comment"] = "failed to create snapshot {}".format(name)
ret["comment"] = f"failed to create snapshot {name}"
if "error" in mod_res:
ret["comment"] = mod_res["error"]
else:
@ -772,14 +772,14 @@ def promoted(name):
## check we if we have a valid dataset name
if not __utils__["zfs.is_dataset"](name):
ret["result"] = False
ret["comment"] = "invalid dataset name: {}".format(name)
ret["comment"] = f"invalid dataset name: {name}"
return ret
## ensure dataset is the primary instance
if not __salt__["zfs.exists"](name, **{"type": "filesystem,volume"}):
## NOTE: we don't have a dataset
ret["result"] = False
ret["comment"] = "dataset {} does not exist".format(name)
ret["comment"] = f"dataset {name} does not exist"
else:
## NOTE: check if we have a blank origin (-)
if (
@ -789,7 +789,7 @@ def promoted(name):
== "-"
):
## NOTE: we're already promoted
ret["comment"] = "{} already promoted".format(name)
ret["comment"] = f"{name} already promoted"
else:
## NOTE: promote dataset
if not __opts__["test"]:
@ -800,9 +800,9 @@ def promoted(name):
ret["result"] = mod_res["promoted"]
if ret["result"]:
ret["changes"][name] = "promoted"
ret["comment"] = "{} promoted".format(name)
ret["comment"] = f"{name} promoted"
else:
ret["comment"] = "failed to promote {}".format(name)
ret["comment"] = f"failed to promote {name}"
if "error" in mod_res:
ret["comment"] = mod_res["error"]
@ -833,7 +833,7 @@ def _schedule_snapshot_retrieve(dataset, prefix, snapshots):
snap_name = snap[snap.index("@") + 1 :]
## NOTE: we only want snapshots matching our prefix
if not snap_name.startswith("{}-".format(prefix)):
if not snap_name.startswith(f"{prefix}-"):
continue
## NOTE: retrieve the holds for this snapshot
@ -886,7 +886,7 @@ def _schedule_snapshot_prepare(dataset, prefix, snapshots):
## NOTE: extract datetime from snapshot name
timestamp = datetime.strptime(
snapshots[hold][-1],
"{}@{}-%Y%m%d_%H%M%S".format(dataset, prefix),
f"{dataset}@{prefix}-%Y%m%d_%H%M%S",
).replace(second=0, microsecond=0)
## NOTE: compare current timestamp to timestamp from snapshot
@ -954,15 +954,15 @@ def scheduled_snapshot(name, prefix, recursive=True, schedule=None):
## NOTE: we need a valid dataset
if not __utils__["zfs.is_dataset"](name):
ret["result"] = False
ret["comment"] = "invalid dataset name: {}".format(name)
ret["comment"] = f"invalid dataset name: {name}"
if not __salt__["zfs.exists"](name, **{"type": "filesystem,volume"}):
ret["comment"] = "dataset {} does not exist".format(name)
ret["comment"] = f"dataset {name} does not exist"
ret["result"] = False
## NOTE: prefix must be 4 or longer
if not prefix or len(prefix) < 4:
ret["comment"] = "prefix ({}) must be at least 4 long".format(prefix)
ret["comment"] = f"prefix ({prefix}) must be at least 4 long"
ret["result"] = False
## NOTE: validate schedule
@ -1015,7 +1015,7 @@ def scheduled_snapshot(name, prefix, recursive=True, schedule=None):
if not mod_res["snapshotted"]:
ret["result"] = False
ret["comment"] = "error creating snapshot ({})".format(snapshot_name)
ret["comment"] = f"error creating snapshot ({snapshot_name})"
else:
## NOTE: create holds (if we have a snapshot)
for hold in snapshot_holds:

View file

@ -238,7 +238,7 @@ def property_absent(name, property):
elif zonecfg[property] != zonecfg_new[property]:
ret["changes"][property] = zonecfg_new[property]
if ret["comment"] == "":
ret["comment"] = "The property {} was cleared!".format(property)
ret["comment"] = f"The property {property} was cleared!"
elif ret["comment"] == "":
if ret["comment"] == "":
ret["comment"] = "The property {} did not get cleared!".format(
@ -246,7 +246,7 @@ def property_absent(name, property):
)
else:
ret["result"] = True
ret["comment"] = "The property {} does not exist!".format(property)
ret["comment"] = f"The property {property} does not exist!"
else:
## zone does not exist
ret["result"] = False
@ -336,7 +336,7 @@ def resource_present(
)
# note: something odd with ncpus property, we fix it here for now
if key == "ncpus" and key in kwargs:
kwargs[key] = "{:.2f}".format(float(kwargs[key]))
kwargs[key] = f"{float(kwargs[key]):.2f}"
if key not in resource:
ret["result"] = None
@ -568,7 +568,7 @@ def booted(name, single=False):
if zones[name]["state"] == "running":
## zone is running
ret["result"] = True
ret["comment"] = "Zone {} already booted".format(name)
ret["comment"] = f"Zone {name} already booted"
else:
## try and boot the zone
if not __opts__["test"]:
@ -576,15 +576,15 @@ def booted(name, single=False):
if __opts__["test"] or zoneadm_res["status"]:
ret["result"] = True
ret["changes"][name] = "booted"
ret["comment"] = "Zone {} booted".format(name)
ret["comment"] = f"Zone {name} booted"
else:
ret["result"] = False
ret["comment"] = "Failed to boot {}".format(name)
ret["comment"] = f"Failed to boot {name}"
else:
## zone does not exist
ret["comment"] = []
ret["comment"].append(
"The zone {} is not in the installed or booted state.".format(name)
f"The zone {name} is not in the installed or booted state."
)
for zone in zones:
if zones[zone]["uuid"] == name:
@ -619,7 +619,7 @@ def halted(name, graceful=True):
if zones[name]["state"] != "running":
## zone is not running
ret["result"] = True
ret["comment"] = "Zone {} already halted".format(name)
ret["comment"] = f"Zone {name} already halted"
else:
## try and halt the zone
if not __opts__["test"]:
@ -631,14 +631,14 @@ def halted(name, graceful=True):
if __opts__["test"] or zoneadm_res["status"]:
ret["result"] = True
ret["changes"][name] = "halted"
ret["comment"] = "Zone {} halted".format(name)
ret["comment"] = f"Zone {name} halted"
else:
ret["result"] = False
ret["comment"] = "Failed to halt {}".format(name)
ret["comment"] = f"Failed to halt {name}"
else:
## zone does not exist
ret["comment"] = []
ret["comment"].append("The zone {} is not in the installed state.".format(name))
ret["comment"].append(f"The zone {name} is not in the installed state.")
for zone in zones:
if zones[zone]["uuid"] == name:
ret["comment"].append(
@ -761,7 +761,7 @@ def export(name, path, replace=False):
else:
## zone does not exist
ret["comment"] = []
ret["comment"].append("The zone {} does not exist.".format(name))
ret["comment"].append(f"The zone {name} does not exist.")
for zone in zones:
if zones[zone]["uuid"] == name:
ret["comment"].append(
@ -820,9 +820,7 @@ def import_(name, path, mode="import", nodataset=False, brand_opts=None):
res_import = __salt__["zonecfg.import"](name, path)
if not res_import["status"]:
ret["result"] = False
ret[
"comment"
] = "Unable to import zone configuration for {}!".format(name)
ret["comment"] = f"Unable to import zone configuration for {name}!"
else:
ret["result"] = True
ret["changes"][name] = "imported"
@ -874,9 +872,7 @@ def import_(name, path, mode="import", nodataset=False, brand_opts=None):
ret["comment"] = "\n".join(ret["comment"])
else:
ret["result"] = False
ret[
"comment"
] = "The file {} does not exists, unable to import!".format(path)
ret["comment"] = f"The file {path} does not exists, unable to import!"
else:
## zone exist
ret["result"] = True
@ -944,7 +940,7 @@ def present(name, brand, zonepath, properties=None, resources=None):
if __opts__["test"]:
ret["result"] = None
ret["comment"].append(
"Cannot determine of changes would happen to the zone {}.".format(name)
f"Cannot determine of changes would happen to the zone {name}."
)
## create zone if needed
@ -959,7 +955,7 @@ def present(name, brand, zonepath, properties=None, resources=None):
if res_create["status"]:
ret["result"] = True
ret["changes"][name] = "created"
ret["comment"].append("The zone {} was created.".format(name))
ret["comment"].append(f"The zone {name} was created.")
if not __opts__["test"]:
ret["result"] = True
@ -1073,7 +1069,7 @@ def absent(name, uninstall=False):
if __opts__["test"]:
ret["result"] = True
ret["changes"][name] = "removed"
ret["comment"] = "Zone {} was removed.".format(name)
ret["comment"] = f"Zone {name} was removed."
else:
ret["result"] = True
if uninstall and zones[name]["state"] in ["running", "installed"]:
@ -1082,10 +1078,10 @@ def absent(name, uninstall=False):
ret["result"] = res_uninstall["status"]
if ret["result"]:
ret["changes"][name] = "uninstalled"
ret["comment"] = "The zone {} was uninstalled.".format(name)
ret["comment"] = f"The zone {name} was uninstalled."
else:
ret["comment"] = []
ret["comment"].append("Failed to uninstall zone {}!".format(name))
ret["comment"].append(f"Failed to uninstall zone {name}!")
if "message" in res_uninstall:
ret["comment"].append(res_uninstall["message"])
ret["comment"] = "\n".join(ret["comment"])
@ -1094,10 +1090,10 @@ def absent(name, uninstall=False):
ret["result"] = res_detach["status"]
if ret["result"]:
ret["changes"][name] = "detached"
ret["comment"] = "The zone {} was detached.".format(name)
ret["comment"] = f"The zone {name} was detached."
else:
ret["comment"] = []
ret["comment"].append("Failed to detach zone {}!".format(name))
ret["comment"].append(f"Failed to detach zone {name}!")
if "message" in res_detach:
ret["comment"].append(res_detach["message"])
ret["comment"] = "\n".join(ret["comment"])
@ -1106,16 +1102,16 @@ def absent(name, uninstall=False):
ret["result"] = res_delete["status"]
if ret["result"]:
ret["changes"][name] = "deleted"
ret["comment"] = "The zone {} was delete.".format(name)
ret["comment"] = f"The zone {name} was delete."
else:
ret["comment"] = []
ret["comment"].append("Failed to delete zone {}!".format(name))
ret["comment"].append(f"Failed to delete zone {name}!")
if "message" in res_delete:
ret["comment"].append(res_delete["message"])
ret["comment"] = "\n".join(ret["comment"])
else:
ret["result"] = True
ret["comment"] = "Zone {} does not exist.".format(name)
ret["comment"] = f"Zone {name} does not exist."
return ret
@ -1142,19 +1138,19 @@ def attached(name, force=False):
ret["result"] = res_attach["status"]
if ret["result"]:
ret["changes"][name] = "attached"
ret["comment"] = "The zone {} was attached.".format(name)
ret["comment"] = f"The zone {name} was attached."
else:
ret["comment"] = []
ret["comment"].append("Failed to attach zone {}!".format(name))
ret["comment"].append(f"Failed to attach zone {name}!")
if "message" in res_attach:
ret["comment"].append(res_attach["message"])
ret["comment"] = "\n".join(ret["comment"])
else:
ret["result"] = True
ret["comment"] = "zone {} already attached.".format(name)
ret["comment"] = f"zone {name} already attached."
else:
ret["result"] = False
ret["comment"] = "zone {} is not configured!".format(name)
ret["comment"] = f"zone {name} is not configured!"
return ret
@ -1179,20 +1175,20 @@ def detached(name):
ret["result"] = res_detach["status"]
if ret["result"]:
ret["changes"][name] = "detached"
ret["comment"] = "The zone {} was detached.".format(name)
ret["comment"] = f"The zone {name} was detached."
else:
ret["comment"] = []
ret["comment"].append("Failed to detach zone {}!".format(name))
ret["comment"].append(f"Failed to detach zone {name}!")
if "message" in res_detach:
ret["comment"].append(res_detach["message"])
ret["comment"] = "\n".join(ret["comment"])
else:
ret["result"] = True
ret["comment"] = "zone {} already detached.".format(name)
ret["comment"] = f"zone {name} already detached."
else:
## note: a non existing zone is not attached, we do not consider this a failure
ret["result"] = True
ret["comment"] = "zone {} is not configured!".format(name)
ret["comment"] = f"zone {name} is not configured!"
return ret
@ -1221,19 +1217,19 @@ def installed(name, nodataset=False, brand_opts=None):
ret["result"] = res_install["status"]
if ret["result"]:
ret["changes"][name] = "installed"
ret["comment"] = "The zone {} was installed.".format(name)
ret["comment"] = f"The zone {name} was installed."
else:
ret["comment"] = []
ret["comment"].append("Failed to install zone {}!".format(name))
ret["comment"].append(f"Failed to install zone {name}!")
if "message" in res_install:
ret["comment"].append(res_install["message"])
ret["comment"] = "\n".join(ret["comment"])
else:
ret["result"] = True
ret["comment"] = "zone {} already installed.".format(name)
ret["comment"] = f"zone {name} already installed."
else:
ret["result"] = False
ret["comment"] = "zone {} is not configured!".format(name)
ret["comment"] = f"zone {name} is not configured!"
return ret
@ -1258,19 +1254,19 @@ def uninstalled(name):
ret["result"] = res_uninstall["status"]
if ret["result"]:
ret["changes"][name] = "uninstalled"
ret["comment"] = "The zone {} was uninstalled.".format(name)
ret["comment"] = f"The zone {name} was uninstalled."
else:
ret["comment"] = []
ret["comment"].append("Failed to uninstall zone {}!".format(name))
ret["comment"].append(f"Failed to uninstall zone {name}!")
if "message" in res_uninstall:
ret["comment"].append(res_uninstall["message"])
ret["comment"] = "\n".join(ret["comment"])
else:
ret["result"] = True
ret["comment"] = "zone {} already uninstalled.".format(name)
ret["comment"] = f"zone {name} already uninstalled."
else:
## note: a non existing zone is not installed, we do not consider this a failure
ret["result"] = True
ret["comment"] = "zone {} is not configured!".format(name)
ret["comment"] = f"zone {name} is not configured!"
return ret

View file

@ -361,7 +361,7 @@ def present(
ret["result"] = mod_res["imported"]
if ret["result"]:
ret["changes"][name] = "imported"
ret["comment"] = "storage pool {} was imported".format(name)
ret["comment"] = f"storage pool {name} was imported"
# create pool
if not ret["result"] and vdevs:
@ -372,17 +372,17 @@ def present(
*vdevs,
force=config["force"],
properties=properties,
filesystem_properties=filesystem_properties
filesystem_properties=filesystem_properties,
)
ret["result"] = mod_res["created"]
if ret["result"]:
ret["changes"][name] = "created"
ret["comment"] = "storage pool {} was created".format(name)
ret["comment"] = f"storage pool {name} was created"
elif "error" in mod_res:
ret["comment"] = mod_res["error"]
else:
ret["comment"] = "could not create storage pool {}".format(name)
ret["comment"] = f"could not create storage pool {name}"
# give up, we cannot import the pool and we do not have a layout to create it
if not ret["result"] and not vdevs:
@ -439,6 +439,6 @@ def absent(name, export=False, force=False):
else: # we are looking good
ret["result"] = True
ret["comment"] = "storage pool {} is absent".format(name)
ret["comment"] = f"storage pool {name} is absent"
return ret

View file

@ -287,7 +287,7 @@ class CacheRegex:
pass
if len(self.cache) > self.size:
self.sweep()
regex = re.compile("{}{}{}".format(self.prepend, pattern, self.append))
regex = re.compile(f"{self.prepend}{pattern}{self.append}")
self.cache[pattern] = [1, regex, pattern, time.time()]
return regex
@ -298,7 +298,7 @@ class ContextCache:
Create a context cache
"""
self.opts = opts
self.cache_path = os.path.join(opts["cachedir"], "context", "{}.p".format(name))
self.cache_path = os.path.join(opts["cachedir"], "context", f"{name}.p")
def cache_context(self, context):
"""

View file

@ -117,11 +117,11 @@ def verify_socket(interface, pub_port, ret_port):
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((interface, int(port)))
except Exception as exc: # pylint: disable=broad-except
msg = "Unable to bind socket {}:{}".format(interface, port)
msg = f"Unable to bind socket {interface}:{port}"
if exc.args:
msg = "{}, error: {}".format(msg, str(exc))
msg = f"{msg}, error: {str(exc)}"
else:
msg = "{}, this might not be a problem.".format(msg)
msg = f"{msg}, this might not be a problem."
msg += "; Is there another salt-master running?"
log.warning(msg)
return False
@ -202,7 +202,7 @@ def verify_files(files, user):
except OSError as err:
if os.path.isfile(dirname):
msg = "Failed to create path {}, is {} a file?".format(fn_, dirname)
msg = f"Failed to create path {fn_}, is {dirname} a file?"
raise SaltSystemExit(msg=msg)
if err.errno != errno.EACCES:
raise
@ -212,7 +212,7 @@ def verify_files(files, user):
raise SaltSystemExit(msg=msg)
except OSError as err: # pylint: disable=duplicate-except
msg = 'Failed to create path "{}" - {}'.format(fn_, err)
msg = f'Failed to create path "{fn_}" - {err}'
raise SaltSystemExit(msg=msg)
stats = os.stat(fn_)
@ -271,7 +271,7 @@ def verify_env(
os.chown(dir_, uid, gid)
for subdir in [a for a in os.listdir(dir_) if "jobs" not in a]:
fsubdir = os.path.join(dir_, subdir)
if "{}jobs".format(os.path.sep) in fsubdir:
if f"{os.path.sep}jobs" in fsubdir:
continue
for root, dirs, files in salt.utils.path.os_walk(fsubdir):
for name in itertools.chain(files, dirs):
@ -396,7 +396,7 @@ def check_path_traversal(path, user="root", skip_perm_errors=False):
"""
for tpath in list_path_traversal(path):
if not os.access(tpath, os.R_OK):
msg = "Could not access {}.".format(tpath)
msg = f"Could not access {tpath}."
if not os.path.exists(tpath):
msg += " Path does not exist."
else:
@ -404,9 +404,9 @@ def check_path_traversal(path, user="root", skip_perm_errors=False):
# Make the error message more intelligent based on how
# the user invokes salt-call or whatever other script.
if user != current_user:
msg += " Try running as user {}.".format(user)
msg += f" Try running as user {user}."
else:
msg += " Please give {} read permissions.".format(user)
msg += f" Please give {user} read permissions."
# We don't need to bail on config file permission errors
# if the CLI
@ -603,7 +603,7 @@ def win_verify_env(path, dirs, permissive=False, pki_dir="", skip_extra=False):
allow_path = "\\".join([system_root, "TEMP"])
if not salt.utils.path.safe_path(path=path, allow_path=allow_path):
raise CommandExecutionError(
"`file_roots` set to a possibly unsafe location: {}".format(path)
f"`file_roots` set to a possibly unsafe location: {path}"
)
# Create the root path directory if missing

View file

@ -169,9 +169,9 @@ def _auto(direction, name, value, source="auto", convert_to_human=True):
# NOTE: convert
if value_type == "size" and direction == "to":
return globals()["{}_{}".format(direction, value_type)](value, convert_to_human)
return globals()[f"{direction}_{value_type}"](value, convert_to_human)
return globals()["{}_{}".format(direction, value_type)](value)
return globals()[f"{direction}_{value_type}"](value)
@real_memoize
@ -335,7 +335,7 @@ def has_feature_flags():
"""
# get man location
man = salt.utils.path.which("man")
return _check_retcode("{man} zpool-features".format(man=man)) if man else False
return _check_retcode(f"{man} zpool-features") if man else False
@real_memoize

View file

@ -43,9 +43,9 @@ def test_list_available_packages(modules, pip_version, tmp_path):
)
def test_list_available_packages_with_index_url(modules, pip_version, tmp_path):
if sys.version_info < (3, 6) and pip_version == "pip>=21.0":
pytest.skip("{} is not available on Py3.5".format(pip_version))
pytest.skip(f"{pip_version} is not available on Py3.5")
if sys.version_info >= (3, 10) and pip_version == "pip==9.0.3":
pytest.skip("{} is not available on Py3.10".format(pip_version))
pytest.skip(f"{pip_version} is not available on Py3.10")
with VirtualEnv(venv_dir=tmp_path, pip_requirement=pip_version) as virtualenv:
virtualenv.install("-U", pip_version)
package_name = "pep8"

View file

@ -289,14 +289,14 @@ def test_hold_unhold(grains, modules, states, test_pkg, refresh_db):
except AssertionError:
pass
else:
pytest.fail("Could not install versionlock package from {}".format(pkgs))
pytest.fail(f"Could not install versionlock package from {pkgs}")
modules.pkg.install(test_pkg)
try:
hold_ret = modules.pkg.hold(test_pkg)
if versionlock_pkg and "-versionlock is not installed" in str(hold_ret):
pytest.skip("{} `{}` is installed".format(hold_ret, versionlock_pkg))
pytest.skip(f"{hold_ret} `{versionlock_pkg}` is installed")
assert test_pkg in hold_ret
assert hold_ret[test_pkg]["result"] is True
@ -328,7 +328,7 @@ def test_refresh_db(grains, tmp_path, minion_opts, refresh_db):
loader = Loaders(minion_opts)
ret = loader.modules.pkg.refresh_db()
if not isinstance(ret, dict):
pytest.skip("Upstream repo did not return coherent results: {}".format(ret))
pytest.skip(f"Upstream repo did not return coherent results: {ret}")
if grains["os_family"] == "RedHat":
assert ret in (True, None)
@ -423,9 +423,7 @@ def test_pkg_upgrade_has_pending_upgrades(grains, modules, test_pkg, refresh_db)
ret = modules.pkg.install(target, version=old)
if not isinstance(ret, dict):
if ret.startswith("ERROR"):
pytest.skipTest(
"Could not install older {} to complete test.".format(target)
)
pytest.skipTest(f"Could not install older {target} to complete test.")
# Run a system upgrade, which should catch the fact that the
# targeted package needs upgrading, and upgrade it.
@ -466,19 +464,17 @@ def test_pkg_latest_version(grains, modules, states, test_pkg, refresh_db):
cmd_pkg = []
if grains["os_family"] == "RedHat":
cmd_pkg = modules.cmd.run("yum list {}".format(test_pkg))
cmd_pkg = modules.cmd.run(f"yum list {test_pkg}")
elif salt.utils.platform.is_windows():
cmd_pkg = modules.pkg.list_available(test_pkg)
elif grains["os_family"] == "Debian":
cmd_pkg = modules.cmd.run("apt list {}".format(test_pkg))
cmd_pkg = modules.cmd.run(f"apt list {test_pkg}")
elif grains["os_family"] == "Arch":
cmd_pkg = modules.cmd.run("pacman -Si {}".format(test_pkg))
cmd_pkg = modules.cmd.run(f"pacman -Si {test_pkg}")
elif grains["os_family"] == "FreeBSD":
cmd_pkg = modules.cmd.run(
"pkg search -S name -qQ version -e {}".format(test_pkg)
)
cmd_pkg = modules.cmd.run(f"pkg search -S name -qQ version -e {test_pkg}")
elif grains["os_family"] == "Suse":
cmd_pkg = modules.cmd.run("zypper info {}".format(test_pkg))
cmd_pkg = modules.cmd.run(f"zypper info {test_pkg}")
elif grains["os_family"] == "MacOS":
brew_bin = salt.utils.path.which("brew")
mac_user = modules.file.get_user(brew_bin)
@ -488,7 +484,7 @@ def test_pkg_latest_version(grains, modules, states, test_pkg, refresh_db):
os.listdir("/Users/")
)
)
cmd_pkg = modules.cmd.run("brew info {}".format(test_pkg), run_as=mac_user)
cmd_pkg = modules.cmd.run(f"brew info {test_pkg}", run_as=mac_user)
else:
pytest.skip("TODO: test not configured for {}".format(grains["os_family"]))
pkg_latest = modules.pkg.latest_version(test_pkg)
@ -530,12 +526,12 @@ def test_list_repos_duplicate_entries(preserve_rhel_yum_conf, grains, modules):
expected = "While reading from '/etc/yum.conf' [line 8]: option 'http_caching' in section 'main' already exists"
with pytest.raises(configparser.DuplicateOptionError) as exc_info:
result = modules.pkg.list_repos(strict_config=True)
assert "{}".format(exc_info.value) == expected
assert f"{exc_info.value}" == expected
# test implicitly strict_config
with pytest.raises(configparser.DuplicateOptionError) as exc_info:
result = modules.pkg.list_repos()
assert "{}".format(exc_info.value) == expected
assert f"{exc_info.value}" == expected
@pytest.mark.destructive_test

View file

@ -147,7 +147,7 @@ def test_archive_extracted_web_source_etag_operation(
minion_opts["cachedir"],
"extrn_files",
"base",
"localhost{free_port}".format(free_port=free_port),
f"localhost{free_port}",
"foo.tar.gz",
)
cached_etag = cached_file + ".etag"
@ -159,7 +159,7 @@ def test_archive_extracted_web_source_etag_operation(
# 127.0.0.1 - - [08/Mar/2022 13:07:10] "GET /foo.tar.gz HTTP/1.1" 200 -
states.archive.extracted(
name=web_root,
source="http://localhost:{free_port}/foo.tar.gz".format(free_port=free_port),
source=f"http://localhost:{free_port}/foo.tar.gz",
archive_format="tar",
options="z",
use_etag=True,
@ -177,7 +177,7 @@ def test_archive_extracted_web_source_etag_operation(
# 127.0.0.1 - - [08/Mar/2022 13:07:10] "GET /foo.tar.gz HTTP/1.1" 304 -
states.archive.extracted(
name=web_root,
source="http://localhost:{free_port}/foo.tar.gz".format(free_port=free_port),
source=f"http://localhost:{free_port}/foo.tar.gz",
archive_format="tar",
options="z",
use_etag=True,
@ -202,7 +202,7 @@ def test_archive_extracted_web_source_etag_operation(
# No call to the web server will be made.
states.archive.extracted(
name=web_root,
source="http://localhost:{free_port}/foo.tar.gz".format(free_port=free_port),
source=f"http://localhost:{free_port}/foo.tar.gz",
archive_format="tar",
options="z",
use_etag=False,
@ -216,7 +216,7 @@ def test_archive_extracted_web_source_etag_operation(
# 127.0.0.1 - - [08/Mar/2022 13:07:10] "GET /foo.tar.gz HTTP/1.1" 200 -
states.archive.extracted(
name=web_root,
source="http://localhost:{free_port}/foo.tar.gz".format(free_port=free_port),
source=f"http://localhost:{free_port}/foo.tar.gz",
archive_format="tar",
options="z",
use_etag=True,

View file

@ -76,8 +76,8 @@ def salt_minion_1(salt_master_1, salt_master_2):
master_2_addr = salt_master_2.config["interface"]
config_overrides = {
"master": [
"{}:{}".format(master_1_addr, master_1_port),
"{}:{}".format(master_2_addr, master_2_port),
f"{master_1_addr}:{master_1_port}",
f"{master_2_addr}:{master_2_port}",
],
"test.foo": "baz",
}

View file

@ -52,7 +52,7 @@ def client_opts():
def _fake_makedir(num=errno.EEXIST):
def _side_effect(*args, **kwargs):
raise OSError(num, "Errno {}".format(num))
raise OSError(num, f"Errno {num}")
return Mock(side_effect=_side_effect)

View file

@ -84,7 +84,7 @@ def _setup(fs_root, cache_root):
path = os.path.join(saltenv_root, "foo.txt")
with salt.utils.files.fopen(path, "w") as fp_:
fp_.write("This is a test file in the '{}' saltenv.\n".format(saltenv))
fp_.write(f"This is a test file in the '{saltenv}' saltenv.\n")
subdir_abspath = os.path.join(saltenv_root, SUBDIR)
os.makedirs(subdir_abspath)
@ -111,7 +111,7 @@ def test_cache_dir(mocked_opts, minion_opts):
with patch.dict(fileclient.__opts__, patched_opts):
client = fileclient.get_file_client(fileclient.__opts__, pillar=False)
for saltenv in _saltenvs():
assert client.cache_dir("salt://{}".format(SUBDIR), saltenv, cachedir=None)
assert client.cache_dir(f"salt://{SUBDIR}", saltenv, cachedir=None)
for subdir_file in _subdir_files():
cache_loc = os.path.join(
fileclient.__opts__["cachedir"],
@ -150,9 +150,7 @@ def test_cache_dir_with_alternate_cachedir_and_absolute_path(
with patch.dict(fileclient.__opts__, patched_opts):
client = fileclient.get_file_client(fileclient.__opts__, pillar=False)
for saltenv in _saltenvs():
assert client.cache_dir(
"salt://{}".format(SUBDIR), saltenv, cachedir=alt_cachedir
)
assert client.cache_dir(f"salt://{SUBDIR}", saltenv, cachedir=alt_cachedir)
for subdir_file in _subdir_files():
cache_loc = os.path.join(
alt_cachedir, "files", saltenv, SUBDIR, subdir_file
@ -185,9 +183,7 @@ def test_cache_dir_with_alternate_cachedir_and_relative_path(mocked_opts, minion
with patch.dict(fileclient.__opts__, patched_opts):
client = fileclient.get_file_client(fileclient.__opts__, pillar=False)
for saltenv in _saltenvs():
assert client.cache_dir(
"salt://{}".format(SUBDIR), saltenv, cachedir=alt_cachedir
)
assert client.cache_dir(f"salt://{SUBDIR}", saltenv, cachedir=alt_cachedir)
for subdir_file in _subdir_files():
cache_loc = os.path.join(
fileclient.__opts__["cachedir"],
@ -324,7 +320,7 @@ def test_cache_dest(mocked_opts, minion_opts):
return salt.utils.path.join(patched_opts["cachedir"], "files", saltenv, relpath)
def _check(ret, expected):
assert ret == expected, "{} != {}".format(ret, expected)
assert ret == expected, f"{ret} != {expected}"
with patch.dict(fileclient.__opts__, patched_opts):
client = fileclient.get_file_client(fileclient.__opts__, pillar=False)

View file

@ -118,7 +118,7 @@ def test_selinux_setcontext_persist_change(tfile2):
def test_file_check_perms(tfile3):
expected_result = (
{
"comment": "The file {} is set to be changed".format(tfile3),
"comment": f"The file {tfile3} is set to be changed",
"changes": {
"selinux": {"New": "Type: lost_found_t", "Old": "Type: user_tmp_t"},
"mode": "0664",

View file

@ -52,8 +52,8 @@ def test_file_tidied_for_file_remove(fake_remove):
file.tidied("/some/directory/tree")
call_root_file1 = "some root{}file1".format(os.sep)
call_root_file2 = "some root{}file2".format(os.sep)
call_root_file1 = f"some root{os.sep}file1"
call_root_file2 = f"some root{os.sep}file2"
fake_remove.assert_has_calls([call(call_root_file1), call(call_root_file2)])

View file

@ -114,4 +114,4 @@ def _getTerminalSize_linux():
if __name__ == "__main__":
sizex, sizey = getTerminalSize()
print("width = {} height = {}".format(sizex, sizey))
print(f"width = {sizex} height = {sizey}")