Commit 8c79976a authored by Christos Stavrakakis's avatar Christos Stavrakakis
Browse files

Add function for pretty printing tables

parent 4dd9c12e
......@@ -34,7 +34,8 @@
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from synnefo.management.common import format_bool, filter_results
from synnefo.management.common import (format_bool, filter_results,
pprint_table)
from synnefo.db.models import Flavor
......@@ -67,15 +68,6 @@ class Command(BaseCommand):
if args:
raise CommandError("Command doesn't accept any arguments")
labels = ('id', 'name', 'cpus', 'ram', 'disk', 'template', 'deleted')
columns = (3, 12, 6, 6, 6, 10, 7)
if not options['csv']:
line = ' '.join(l.rjust(w) for l, w in zip(labels, columns))
self.stdout.write(line + '\n')
sep = '-' * len(line)
self.stdout.write(sep + '\n')
if options['deleted']:
flavors = Flavor.objects.all()
else:
......@@ -85,7 +77,8 @@ class Command(BaseCommand):
if filter_by:
flavors = filter_results(flavors, filter_by)
headers = ('id', 'name', 'cpus', 'ram', 'disk', 'template', 'deleted')
table = []
for flavor in flavors.order_by('id'):
id = str(flavor.id)
cpu = str(flavor.cpu)
......@@ -95,9 +88,7 @@ class Command(BaseCommand):
fields = (id, flavor.name, cpu, ram, disk, flavor.disk_template,
deleted)
if options['csv']:
line = '|'.join(fields)
else:
line = ' '.join(f.rjust(w) for f, w in zip(fields, columns))
table.append(fields)
self.stdout.write(line.encode('utf8') + '\n')
separator = " | " if options['csv'] else None
pprint_table(self.stdout, table, headers, separator)
......@@ -36,6 +36,7 @@ from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from synnefo.management.common import format_bool, filter_results
from synnefo.db.models import Network
from synnefo.management.common import pprint_table
FIELDS = Network._meta.get_all_field_names()
......@@ -89,23 +90,15 @@ class Command(BaseCommand):
if filter_by:
networks = filter_results(networks, filter_by)
labels = ['id', 'name', 'type', 'owner',
headers = ['id', 'name', 'type', 'owner',
'mac_prefix', 'dhcp', 'state', 'link', 'vms', 'public']
columns = [3, 16, 22, 30, 10, 6, 8, 12, 4, 6]
if options['ipv6']:
labels.extend(['IPv6 Subnet', 'IPv6 Gateway'])
columns.extend([16, 16])
headers.extend(['IPv6 Subnet', 'IPv6 Gateway'])
else:
labels.extend(['IPv4 Subnet', 'IPv4 Gateway'])
columns.extend([14, 14])
if not options['csv']:
line = ' '.join(l.rjust(w) for l, w in zip(labels, columns))
self.stdout.write(line + '\n')
sep = '-' * len(line)
self.stdout.write(sep + '\n')
headers.extend(['IPv4 Subnet', 'IPv4 Gateway'])
table = []
for network in networks.order_by("id"):
fields = [str(network.id),
network.name,
......@@ -122,10 +115,7 @@ class Command(BaseCommand):
fields.extend([network.subnet6 or '', network.gateway6 or ''])
else:
fields.extend([network.subnet, network.gateway or ''])
table.append(fields)
if options['csv']:
line = '|'.join(fields)
else:
line = ' '.join(f.rjust(w) for f, w in zip(fields, columns))
self.stdout.write(line.encode('utf8') + '\n')
separator = " | " if options['csv'] else None
pprint_table(self.stdout, table, headers, separator)
......@@ -35,7 +35,7 @@ from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from synnefo.management.common import (format_vm_state, get_backend,
filter_results)
filter_results, pprint_table)
from synnefo.api.util import get_image
from synnefo.db.models import VirtualMachine
......@@ -103,40 +103,33 @@ class Command(BaseCommand):
if filter_by:
servers = filter_results(servers, filter_by)
labels = ('id', 'name', 'owner', 'flavor', 'image', 'state',
'backend')
columns = (3, 12, 20, 11, 12, 9, 40)
if not options['csv']:
line = ' '.join(l.rjust(w) for l, w in zip(labels, columns))
self.stdout.write(line + '\n')
sep = '-' * len(line)
self.stdout.write(sep + '\n')
cache = ImageCache()
headers = ('id', 'name', 'owner', 'flavor', 'image', 'state',
'backend')
table = []
for server in servers.order_by('id'):
id = str(server.id)
try:
name = server.name.decode('utf8')
except UnicodeEncodeError:
name = server.name
flavor = server.flavor.name
try:
image = cache.get_image(server.imageid, server.userid)['name']
except:
image = server.imageid
state = format_vm_state(server)
fields = (id, name, server.userid, flavor, image, state,
str(server.backend))
if options['csv']:
line = '|'.join(fields)
else:
line = ' '.join(f.rjust(w) for f, w in zip(fields, columns))
fields = (str(server.id), name, server.userid, flavor, image,
state, str(server.backend))
table.append(fields)
self.stdout.write(line.encode('utf8') + '\n')
separator = " | " if options['csv'] else None
pprint_table(self.stdout, table, headers, separator)
class ImageCache(object):
......
......@@ -33,6 +33,7 @@
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from synnefo.management.common import pprint_table
from synnefo.db.models import Backend
......@@ -54,27 +55,16 @@ class Command(BaseCommand):
backends = Backend.objects.order_by('id')
labels = ('id', 'clustername', 'port', 'username', "VMs", 'drained',
'offline')
columns = (3, 50, 5, 10, 4, 6, 6)
if not options['csv']:
line = ' '.join(l.rjust(w) for l, w in zip(labels, columns))
sep = '-' * len(line)
self.stdout.write(sep + '\n')
self.stdout.write(line + '\n')
self.stdout.write(sep + '\n')
headers = ('id', 'clustername', 'port', 'username', "VMs", 'drained',
'offline')
table = []
for backend in backends:
id = str(backend.id)
vms = str(backend.virtual_machines.filter(deleted=False).count())
fields = (id, backend.clustername, str(backend.port),
backend.username, vms, str(backend.drained),
str(backend.offline))
table.append(fields)
if options['csv']:
line = '|'.join(fields)
else:
line = ' '.join(f.rjust(w) for f, w in zip(fields, columns))
self.stdout.write(line.encode('utf8') + '\n')
separator = " | " if options['csv'] else None
pprint_table(self.stdout, table, headers, separator)
......@@ -217,3 +217,33 @@ def check_backend_credentials(clustername, port, username, password):
if info_name != clustername:
raise CommandError("Invalid clustername value. Please use the"
" Ganeti Cluster name: %s" % info_name)
def pprint_table(out, table, headers=None, separator=None):
"""Print a pretty, aligned string representation of table.
Works by finding out the max width of each column and padding to data
to this value.
"""
sep = separator if separator else " "
if headers:
table.insert(0, headers)
# Find out the max width of each column
widths = [max(map(len, col)) for col in zip(*table)]
t_length = sum(widths) + len(sep) * (len(widths) - 1)
if headers:
# pretty print the headers
print >> out, sep.join((val.rjust(width) for val, width \
in zip(headers, widths)))
print >> out, "-" * t_length
# remove headers
table = table[1:]
# print the rest table
for row in table:
print >> out, sep.join((val.rjust(width).encode('utf8') \
for val, width in zip(row, widths)))
......@@ -31,6 +31,7 @@
from django.core.management.base import BaseCommand
from optparse import make_option
from synnefo.management.common import pprint_table
from synnefo.plankton.backend import ImageBackend
......@@ -42,19 +43,14 @@ class Command(BaseCommand):
def handle(self, **options):
userid = options['userid']
write = self.stdout.write
c = ImageBackend(userid) if userid else ImageBackend("")
images = c.list()
images.sort(key=lambda x: x['created_at'], reverse=True)
fields = ("id", "name", "owner", "public")
columns = (40, 30, 30, 7)
sep = "-" * 107
line = "".join(f.rjust(c) for f, c in zip(fields, columns))
write(line + "\n")
write(sep + "\n")
headers = ("id", "name", "owner", "public")
table = []
for img in images:
fields = (img["id"], img["name"], img["owner"], img["is_public"])
line = "".join(str(f).rjust(c) for f, c in zip(fields, columns))
write(line + "\n")
fields = (img["id"], img["name"], img["owner"], str(img["is_public"]))
table.append(fields)
pprint_table(self.stdout, table, headers)
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment