Commit 3a24c527 authored by Iustin Pop's avatar Iustin Pop

Convert the gnt scripts to ToStdout/err

Currently the gnt-* scripts are using a mix of print, logger.ToStd* and
sys.stderr.write. We convert them all to using cli.ToStdout/err. This
way, we can easily change the implementation for all at once.

Reviewed-by: imsnah
parent 46fbdd04
......@@ -43,13 +43,13 @@ def PrintExportList(opts, args):
"""
exports = GetClient().QueryExports(opts.nodes)
for node in exports:
print ("Node: %s" % node)
print ("Exports:")
ToStdout("Node: %s", node)
ToStdout("Exports:")
if isinstance(exports[node], list):
for instance_name in exports[node]:
print ("\t%s" % instance_name)
ToStdout("\t%s", instance_name)
else:
print (" Could not get exports list")
ToStdout(" Could not get exports list")
def ExportInstance(opts, args):
......
......@@ -21,7 +21,6 @@
import sys
from optparse import make_option
import pprint
import os.path
from ganeti.cli import *
......@@ -43,7 +42,7 @@ def InitCluster(opts, args):
"""
if not opts.lvm_storage and opts.vg_name:
print ("Options --no-lvm-storage and --vg-name conflict.")
ToStderr("Options --no-lvm-storage and --vg-name conflict.")
return 1
vg_name = opts.vg_name
......@@ -119,8 +118,8 @@ def DestroyCluster(opts, args):
"""
if not opts.yes_do_it:
print ("Destroying a cluster is irreversibly. If you really want destroy"
" this cluster, supply the --yes-do-it option.")
ToStderr("Destroying a cluster is irreversible. If you really want"
" destroy this cluster, supply the --yes-do-it option.")
return 1
op = opcodes.OpDestroyCluster()
......@@ -162,11 +161,11 @@ def ShowClusterVersion(opts, args):
"""
op = opcodes.OpQueryClusterInfo()
result = SubmitOpCode(op)
print ("Software version: %s" % result["software_version"])
print ("Internode protocol: %s" % result["protocol_version"])
print ("Configuration format: %s" % result["config_version"])
print ("OS api version: %s" % result["os_api_version"])
print ("Export interface: %s" % result["export_version"])
ToStdout("Software version: %s", result["software_version"])
ToStdout("Internode protocol: %s", result["protocol_version"])
ToStdout("Configuration format: %s", result["config_version"])
ToStdout("OS api version: %s", result["os_api_version"])
ToStdout("Export interface: %s", result["export_version"])
return 0
......@@ -177,7 +176,7 @@ def ShowClusterMaster(opts, args):
opts - class with options as members
"""
print GetClient().QueryConfigValues(["master_node"])[0]
ToStdout("%s", GetClient().QueryConfigValues(["master_node"])[0])
return 0
......@@ -188,27 +187,27 @@ def ShowClusterConfig(opts, args):
op = opcodes.OpQueryClusterInfo()
result = SubmitOpCode(op)
print ("Cluster name: %s" % result["name"])
ToStdout("Cluster name: %s", result["name"])
print ("Master node: %s" % result["master"])
ToStdout("Master node: %s", result["master"])
print ("Architecture (this node): %s (%s)" %
(result["architecture"][0], result["architecture"][1]))
ToStdout("Architecture (this node): %s (%s)",
result["architecture"][0], result["architecture"][1])
print ("Default hypervisor: %s" % result["hypervisor_type"])
print ("Enabled hypervisors: %s" % ", ".join(result["enabled_hypervisors"]))
ToStdout("Default hypervisor: %s", result["hypervisor_type"])
ToStdout("Enabled hypervisors: %s", ", ".join(result["enabled_hypervisors"]))
print "Hypervisor parameters:"
ToStdout("Hypervisor parameters:")
for hv_name, hv_dict in result["hvparams"].items():
print " - %s:" % hv_name
ToStdout(" - %s:", hv_name)
for item, val in hv_dict.iteritems():
print " %s: %s" % (item, val)
ToStdout(" %s: %s", item, val)
print "Cluster parameters:"
ToStdout("Cluster parameters:")
for gr_name, gr_dict in result["beparams"].items():
print " - %s:" % gr_name
ToStdout(" - %s:", gr_name)
for item, val in gr_dict.iteritems():
print " %s: %s" % (item, val)
ToStdout(" %s: %s", item, val)
return 0
......@@ -239,8 +238,7 @@ def ClusterCopyFile(opts, args):
srun = ssh.SshRunner(cluster_name=cluster_name)
for node in results:
if not srun.CopyFileToNode(node, filename):
print >> sys.stderr, ("Copy of file %s to node %s failed" %
(filename, node))
ToStderr("Copy of file %s to node %s failed", filename, node)
return 0
......@@ -273,10 +271,10 @@ def RunClusterCommand(opts, args):
for name in nodes:
result = srun.Run(name, "root", command)
print ("------------------------------------------------")
print ("node: %s" % name)
print ("%s" % result.output)
print ("return code = %s" % result.exit_code)
ToStdout("------------------------------------------------")
ToStdout("node: %s", name)
ToStdout("%s", result.output)
ToStdout("return code = %s", result.exit_code)
return 0
......@@ -313,17 +311,17 @@ def VerifyDisks(opts, args):
nodes, nlvm, instances, missing = result
if nodes:
print "Nodes unreachable or with bad data:"
ToStdout("Nodes unreachable or with bad data:")
for name in nodes:
print "\t%s" % name
ToStdout("\t%s", name)
retcode = constants.EXIT_SUCCESS
if nlvm:
for node, text in nlvm.iteritems():
print ("Error on node %s: LVM error: %s" %
(node, text[-400:].encode('string_escape')))
ToStdout("Error on node %s: LVM error: %s",
node, text[-400:].encode('string_escape'))
retcode |= 1
print "You need to fix these nodes first before fixing instances"
ToStdout("You need to fix these nodes first before fixing instances")
if instances:
for iname in instances:
......@@ -331,29 +329,28 @@ def VerifyDisks(opts, args):
continue
op = opcodes.OpActivateInstanceDisks(instance_name=iname)
try:
print "Activating disks for instance '%s'" % iname
ToStdout("Activating disks for instance '%s'", iname)
SubmitOpCode(op)
except errors.GenericError, err:
nret, msg = FormatError(err)
retcode |= nret
print >> sys.stderr, ("Error activating disks for instance %s: %s" %
(iname, msg))
ToStderr("Error activating disks for instance %s: %s", iname, msg)
if missing:
for iname, ival in missing.iteritems():
all_missing = utils.all(ival, lambda x: x[0] in nlvm)
if all_missing:
print ("Instance %s cannot be verified as it lives on"
" broken nodes" % iname)
ToStdout("Instance %s cannot be verified as it lives on"
" broken nodes", iname)
else:
print "Instance %s has missing logical volumes:" % iname
ToStdout("Instance %s has missing logical volumes:", iname)
ival.sort()
for node, vol in ival:
if node in nlvm:
print ("\tbroken node %s /dev/xenvg/%s" % (node, vol))
ToStdout("\tbroken node %s /dev/xenvg/%s", node, vol)
else:
print ("\t%s /dev/xenvg/%s" % (node, vol))
print ("You need to run replace_disks for all the above"
ToStdout("\t%s /dev/xenvg/%s", node, vol)
ToStdout("You need to run replace_disks for all the above"
" instances, if this message persist after fixing nodes.")
retcode |= 1
......@@ -382,7 +379,7 @@ def SearchTags(opts, args):
result = list(result)
result.sort()
for path, tag in result:
print "%s %s" % (path, tag)
ToStdout("%s %s", path, tag)
def SetClusterParams(opts, args):
......@@ -395,12 +392,12 @@ def SetClusterParams(opts, args):
if not (not opts.lvm_storage or opts.vg_name or
opts.enabled_hypervisors or opts.hvparams or
opts.beparams):
print "Please give at least one of the parameters."
ToStderr("Please give at least one of the parameters.")
return 1
vg_name = opts.vg_name
if not opts.lvm_storage and opts.vg_name:
print ("Options --no-lvm-storage and --vg-name conflict.")
ToStdout("Options --no-lvm-storage and --vg-name conflict.")
return 1
hvlist = opts.enabled_hypervisors
......@@ -433,11 +430,11 @@ def QueueOps(opts, args):
client.SetQueueDrainFlag(drain_flag)
elif command == "info":
result = client.QueryConfigValues(["drain_flag"])
print "The drain flag is",
if result[0]:
print "set"
val = "set"
else:
print "unset"
val = "unset"
ToStdout("The drain flag is %s" % val)
return 0
# this is an option common to more than one command, so we declare
......
......@@ -30,7 +30,6 @@ from cStringIO import StringIO
from ganeti.cli import *
from ganeti import opcodes
from ganeti import logger
from ganeti import constants
from ganeti import utils
from ganeti import errors
......@@ -58,7 +57,7 @@ def GenericOpCodes(opts, args):
op_list = [opcodes.OpCode.LoadOpCode(val) for val in op_data]
job = opcodes.Job(op_list=op_list)
jid = SubmitJob(job)
print "Job id:", jid
ToStdout("Job id: %s", jid)
query = {
"object": "jobs",
"fields": ["status"],
......@@ -70,11 +69,11 @@ def GenericOpCodes(opts, args):
jdata = SubmitQuery(query)
if not jdata:
# job not found, gone away!
print "Job lost!"
ToStderr("Job lost!")
return 1
status = jdata[0][0]
print status
ToStdout(status)
if status in (opcodes.Job.STATUS_SUCCESS, opcodes.Job.STATUS_FAIL):
break
......@@ -86,12 +85,12 @@ def GenericOpCodes(opts, args):
jdata = SubmitQuery(query)
if not jdata:
# job not found, gone away!
print "Job lost!"
ToStderr("Job lost!")
return 1
print jdata[0]
ToStdout(jdata[0])
status, op_list, op_status, op_result = jdata[0]
for idx, op in enumerate(op_list):
print idx, op.OP_ID, op_status[idx], op_result[idx]
ToStdout("%s %s %s %s", idx, op.OP_ID, op_status[idx], op_result[idx])
return 0
......@@ -102,7 +101,7 @@ def TestAllocator(opts, args):
disks = [{"size": utils.ParseUnit(val), "mode": 'w'}
for val in opts.disks.split(",")]
except errors.UnitParseError, err:
print >> sys.stderr, "Invalid disks parameter '%s': %s" % (opts.disks, err)
ToStderr("Invalid disks parameter '%s': %s", opts.disks, err)
return 1
nics = [val.split("/") for val in opts.nics.split(",")]
......@@ -132,7 +131,7 @@ def TestAllocator(opts, args):
allocator=opts.allocator,
)
result = SubmitOpCode(op)
print result
ToStdout("%s" % result)
return 0
......
......@@ -29,7 +29,6 @@ from cStringIO import StringIO
from ganeti.cli import *
from ganeti import cli
from ganeti import opcodes
from ganeti import logger
from ganeti import constants
from ganeti import utils
from ganeti import errors
......@@ -252,7 +251,7 @@ def ListInstances(opts, args):
numfields=numfields, data=output)
for line in data:
logger.ToStdout(line)
ToStdout(line)
return 0
......@@ -418,7 +417,7 @@ def BatchCreate(opts, args):
file_storage_dir=specs['file_storage_dir'],
file_driver=specs['file_driver'])
print '%s: %s' % (name, cli.SendJob([op]))
ToStdout("%s: %s", name, cli.SendJob([op]))
return 0
......@@ -438,14 +437,14 @@ def ReinstallInstance(opts, args):
result = SubmitOpCode(op)
if not result:
logger.ToStdout("Can't get the OS list")
ToStdout("Can't get the OS list")
return 1
logger.ToStdout("Available OS templates:")
ToStdout("Available OS templates:")
number = 0
choices = []
for entry in result:
logger.ToStdout("%3s: %s" % (number, entry[0]))
ToStdout("%3s: %s", number, entry[0])
choices.append(("%s" % number, entry[0], entry[0]))
number = number + 1
......@@ -454,7 +453,7 @@ def ReinstallInstance(opts, args):
choices)
if selected == 'exit':
logger.ToStdout("User aborted reinstall, exiting")
ToStdout("User aborted reinstall, exiting")
return 1
os = selected
......@@ -526,7 +525,7 @@ def ActivateDisks(opts, args):
op = opcodes.OpActivateInstanceDisks(instance_name=instance_name)
disks_info = SubmitOrSend(op, opts)
for host, iname, nname in disks_info:
print "%s:%s:%s" % (host, iname, nname)
ToStdout("%s:%s:%s", host, iname, nname)
return 0
......@@ -581,12 +580,12 @@ def StartupInstance(opts, args):
force=opts.force,
extra_args=opts.extra_args)
if multi_on:
logger.ToStdout("Starting up %s" % name)
ToStdout("Starting up %s", name)
try:
SubmitOrSend(op, opts)
except JobSubmittedException, err:
_, txt = FormatError(err)
logger.ToStdout("%s" % txt)
ToStdout("%s", txt)
return 0
......@@ -636,12 +635,12 @@ def ShutdownInstance(opts, args):
for name in inames:
op = opcodes.OpShutdownInstance(instance_name=name)
if multi_on:
logger.ToStdout("Shutting down %s" % name)
ToStdout("Shutting down %s", name)
try:
SubmitOrSend(op, opts)
except JobSubmittedException, err:
_, txt = FormatError(err)
logger.ToStdout("%s" % txt)
ToStdout("%s", txt)
return 0
......@@ -721,13 +720,13 @@ def ConnectToInstanceConsole(opts, args):
cmd = SubmitOpCode(op)
if opts.show_command:
print utils.ShellQuoteArgs(cmd)
ToStdout("%s", utils.ShellQuoteArgs(cmd))
else:
try:
os.execvp(cmd[0], cmd)
finally:
sys.stderr.write("Can't run console command %s with arguments:\n'%s'" %
(cmd, " ".join(argv)))
ToStderr("Can't run console command %s with arguments:\n'%s'",
cmd, " ".join(argv))
os._exit(1)
......@@ -812,7 +811,7 @@ def ShowInstanceConfig(opts, args):
op = opcodes.OpQueryInstanceData(instances=args, static=opts.static)
result = SubmitOpCode(op)
if not result:
logger.ToStdout("No instances.")
ToStdout("No instances.")
return 1
buf = StringIO()
......@@ -883,7 +882,7 @@ def ShowInstanceConfig(opts, args):
for device in instance["disks"]:
_FormatBlockDevInfo(buf, device, 1, opts.static)
logger.ToStdout(buf.getvalue().rstrip('\n'))
ToStdout(buf.getvalue().rstrip('\n'))
return retcode
......@@ -901,7 +900,7 @@ def SetInstanceParams(opts, args):
"""
if not (opts.ip or opts.bridge or opts.mac or
opts.hypervisor or opts.beparams):
logger.ToStdout("Please give at least one of the parameters.")
ToStderr("Please give at least one of the parameters.")
return 1
if constants.BE_MEMORY in opts.beparams:
......@@ -919,11 +918,11 @@ def SetInstanceParams(opts, args):
result = SubmitOrSend(op, opts)
if result:
logger.ToStdout("Modified instance %s" % args[0])
ToStdout("Modified instance %s", args[0])
for param, data in result:
logger.ToStdout(" - %-5s -> %s" % (param, data))
logger.ToStdout("Please don't forget that these parameters take effect"
" only at the next start of the instance.")
ToStdout(" - %-5s -> %s", param, data)
ToStdout("Please don't forget that these parameters take effect"
" only at the next start of the instance.")
return 0
......
......@@ -28,7 +28,6 @@ from cStringIO import StringIO
from ganeti.cli import *
from ganeti import opcodes
from ganeti import logger
from ganeti import constants
from ganeti import utils
from ganeti import errors
......@@ -103,7 +102,7 @@ def ListJobs(opts, args):
fields=selected_fields, unitfields=unitfields,
numfields=numfields, data=output)
for line in data:
print line
ToStdout(line)
return 0
......@@ -146,7 +145,7 @@ def ShowJobs(opts, args):
"""
def format(level, text):
"""Display the text indented."""
print "%s%s" % (" " * level, text)
ToStdout("%s%s", " " * level, text)
def result_helper(value):
"""Format a result field in a nice way."""
......
......@@ -24,7 +24,6 @@ from optparse import make_option
from ganeti.cli import *
from ganeti import opcodes
from ganeti import logger
from ganeti import utils
from ganeti import constants
from ganeti import errors
......@@ -52,14 +51,16 @@ def AddNode(opts, args):
except (errors.OpPrereqError, errors.OpExecError):
pass
else:
logger.ToStderr("Node %s already in the cluster (as %s)"
" - please use --readd" % (args[0], output[0][0]))
ToStderr("Node %s already in the cluster (as %s)"
" - please use --readd", args[0], output[0][0])
return 1
logger.ToStderr("-- WARNING -- \n"
"Performing this operation is going to replace the ssh daemon keypair\n"
"on the target machine (%s) with the ones of the current one\n"
"and grant full intra-cluster ssh root access to/from it\n" % node)
ToStderr("-- WARNING -- \n"
"Performing this operation is going to replace the ssh daemon"
" keypair\n"
"on the target machine (%s) with the ones of the"
" current one\n"
"and grant full intra-cluster ssh root access to/from it\n", node)
bootstrap.SetupNodeDaemon(node, opts.ssh_key_check)
......@@ -121,7 +122,7 @@ def ListNodes(opts, args):
fields=selected_fields, unitfields=unitfields,
numfields=numfields, data=output)
for line in data:
logger.ToStdout(line)
ToStdout(line)
return 0
......@@ -147,7 +148,7 @@ def EvacuateNode(opts, args):
src_node)
if not sinst:
logger.ToStderr("No secondary instances on node %s, exiting." % src_node)
ToStderr("No secondary instances on node %s, exiting.", src_node)
return constants.EXIT_SUCCESS
sinst = utils.NiceSort(sinst)
......@@ -167,23 +168,21 @@ def EvacuateNode(opts, args):
mode=constants.REPLACE_DISK_ALL,
disks=["sda", "sdb"])
try:
logger.ToStdout("Replacing disks for instance %s" % iname)
ToStdout("Replacing disks for instance %s", iname)
SubmitOpCode(op)
logger.ToStdout("Instance %s has been relocated" % iname)
ToStdout("Instance %s has been relocated", iname)
good_cnt += 1
except errors.GenericError, err:
nret, msg = FormatError(err)
retcode |= nret
logger.ToStderr("Error replacing disks for instance %s: %s" %
(iname, msg))
ToStderr("Error replacing disks for instance %s: %s", iname, msg)
bad_cnt += 1
if retcode == constants.EXIT_SUCCESS:
logger.ToStdout("All %d instance(s) relocated successfully." % good_cnt)
ToStdout("All %d instance(s) relocated successfully.", good_cnt)
else:
logger.ToStdout("There were errors during the relocation:\n"
"%d error(s) out of %d instance(s)." %
(bad_cnt, good_cnt + bad_cnt))
ToStdout("There were errors during the relocation:\n"
"%d error(s) out of %d instance(s).", bad_cnt, good_cnt + bad_cnt)
return retcode
......@@ -199,7 +198,7 @@ def FailoverNode(opts, args):
node, pinst = result[0]
if not pinst:
logger.ToStderr("No primary instances on node %s, exiting." % node)
ToStderr("No primary instances on node %s, exiting.", node)
return 0
pinst = utils.NiceSort(pinst)
......@@ -215,22 +214,21 @@ def FailoverNode(opts, args):
op = opcodes.OpFailoverInstance(instance_name=iname,
ignore_consistency=opts.ignore_consistency)
try:
logger.ToStdout("Failing over instance %s" % iname)
ToStdout("Failing over instance %s", iname)
SubmitOpCode(op)
logger.ToStdout("Instance %s has been failed over" % iname)
ToStdout("Instance %s has been failed over", iname)
good_cnt += 1
except errors.GenericError, err:
nret, msg = FormatError(err)
retcode |= nret
logger.ToStderr("Error failing over instance %s: %s" % (iname, msg))
ToStderr("Error failing over instance %s: %s", iname, msg)
bad_cnt += 1
if retcode == 0:
logger.ToStdout("All %d instance(s) failed over successfully." % good_cnt)
ToStdout("All %d instance(s) failed over successfully.", good_cnt)
else:
logger.ToStdout("There were errors during the failover:\n"
"%d error(s) out of %d instance(s)." %
(bad_cnt, good_cnt + bad_cnt))
ToStdout("There were errors during the failover:\n"
"%d error(s) out of %d instance(s).", bad_cnt, good_cnt + bad_cnt)
return retcode
......@@ -244,21 +242,21 @@ def ShowNodeConfig(opts, args):
result = SubmitOpCode(op)
for name, primary_ip, secondary_ip, pinst, sinst in result:
logger.ToStdout("Node name: %s" % name)
logger.ToStdout(" primary ip: %s" % primary_ip)
logger.ToStdout(" secondary ip: %s" % secondary_ip)
ToStdout("Node name: %s", name)
ToStdout(" primary ip: %s", primary_ip)
ToStdout(" secondary ip: %s", secondary_ip)
if pinst:
logger.ToStdout(" primary for instances:")
ToStdout(" primary for instances:")
for iname in pinst:
logger.ToStdout(" - %s" % iname)
ToStdout(" - %s", iname)
else:
logger.ToStdout(" primary for no instances")
ToStdout(" primary for no instances")
if sinst:
logger.ToStdout(" secondary for instances:")
ToStdout(" secondary for instances:")
for iname in sinst:
logger.ToStdout(" - %s" % iname)
ToStdout(" - %s", iname)
else:
logger.ToStdout(" secondary for no instances")
ToStdout(" secondary for no instances")
return 0
......@@ -301,7 +299,7 @@ def ListVolumes(opts, args):
numfields=numfields, data=output)
for line in data:
logger.ToStdout(line)
ToStdout(line)
return 0
......
......@@ -24,7 +24,6 @@ from optparse import make_option