Skip to content

Commit

Permalink
Fix console output for management commands
Browse files Browse the repository at this point in the history
From Django's documentation:
  When you are using management commands and wish to provide console
  output, you should write to self.stdout and self.stderr, instead of
  printing to stdout and stderr directly.

This patch fixes the managements commands to use the proper
stdout/stderr objects.

Ref #3: Log all stdout/stderr for snf-manage invocations
  • Loading branch information
iliastsi committed Mar 17, 2014
1 parent 4d0684a commit 66c2390
Show file tree
Hide file tree
Showing 6 changed files with 142 additions and 124 deletions.
21 changes: 11 additions & 10 deletions snf-astakos-app/astakos/im/management/commands/user-modify.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,43 +198,44 @@ def handle(self, *args, **options):
reject_reason=reject_reason)
activation_backend.send_result_notifications(res, user)
if res.is_error():
print "Failed to reject.", res.message
self.stderr.write("Failed to reject: %s\n" % res.message)
else:
print "Account rejected"
self.stderr.write("Account rejected\n")

if options.get('verify'):
res = activation_backend.handle_verification(
user,
user.verification_code)
#activation_backend.send_result_notifications(res, user)
if res.is_error():
print "Failed to verify.", res.message
self.stderr.write("Failed to verify: %s\n" % res.message)
else:
print "Account verified (%s)" % res.status_display()
self.stderr.write("Account verified (%s)\n"
% res.status_display())

if options.get('accept'):
res = activation_backend.handle_moderation(user, accept=True)
activation_backend.send_result_notifications(res, user)
if res.is_error():
print "Failed to accept.", res.message
self.stderr.write("Failed to accept: %s\n" % res.message)
else:
print "Account accepted and activated"
self.stderr.write("Account accepted and activated\n")

if options.get('active'):
res = activation_backend.activate_user(user)
if res.is_error():
print "Failed to activate.", res.message
self.stderr.write("Failed to activate: %s\n" % res.message)
else:
print "Account %s activated" % user.username
self.stderr.write("Account %s activated\n" % user.username)

elif options.get('inactive'):
res = activation_backend.deactivate_user(
user,
reason=options.get('inactive_reason', None))
if res.is_error():
print "Failed to deactivate,", res.message
self.stderr.write("Failed to deactivate: %s\n" % res.message)
else:
print "Account %s deactivated" % user.username
self.stderr.write("Account %s deactivated\n" % user.username)

invitations = options.get('invitations')
if invitations is not None:
Expand Down
143 changes: 72 additions & 71 deletions snf-cyclades-app/synnefo/logic/management/commands/backend-add.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Copyright 2011-2013 GRNET S.A. All rights reserved.
# Copyright 2011-2014 GRNET S.A. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
Expand Down Expand Up @@ -27,7 +27,6 @@
# those of the authors and should not be interpreted as representing official
# policies, either expressed or implied, of GRNET S.A.
#
import sys
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError

Expand Down Expand Up @@ -85,72 +84,74 @@ def handle(self, *args, **options):
if options['check']:
check_backend_credentials(clustername, port, username, password)

create_backend(clustername, port, username, password,
hypervisor=options["hypervisor"],
initialize=options["init"])


def create_backend(clustername, port, username, password, hypervisor=None,
initialize=True, stream=sys.stdout):
kw = {"clustername": clustername,
"port": port,
"username": username,
"password": password,
"drained": True}

if hypervisor:
kw["hypervisor"] = hypervisor

# Create the new backend in database
try:
backend = Backend.objects.create(**kw)
except IntegrityError as e:
raise CommandError("Cannot create backend: %s\n" % e)

stream.write("Successfully created backend with id %d\n" % backend.id)

if not initialize:
return

stream.write("Retrieving backend resources:\n")
resources = backend_mod.get_physical_resources(backend)
attr = ['mfree', 'mtotal', 'dfree', 'dtotal', 'pinst_cnt', 'ctotal']

table = [[str(resources[x]) for x in attr]]
pprint_table(stream, table, attr)

backend_mod.update_backend_resources(backend, resources)
backend_mod.update_backend_disk_templates(backend)

networks = Network.objects.filter(deleted=False, public=True)
if not networks:
return

stream.write("Creating the following public:\n")
headers = ("ID", "Name", 'IPv4 Subnet', "IPv6 Subnet", 'Mac Prefix')
table = []

for net in networks:
subnet4 = net.subnet4.cidr if net.subnet4 else None
subnet6 = net.subnet6.cidr if net.subnet6 else None
table.append((net.id, net.backend_id, subnet4,
subnet6, str(net.mac_prefix)))
pprint_table(stream, table, headers)

for net in networks:
net.create_backend_network(backend)
result = backend_mod.create_network_synced(net, backend)
if result[0] != "success":
stream.write('\nError Creating Network %s: %s\n' %
(net.backend_id, result[1]))
else:
stream.write('Successfully created Network: %s\n' %
net.backend_id)
result = backend_mod.connect_network_synced(network=net,
backend=backend)
if result[0] != "success":
stream.write('\nError Connecting Network %s: %s\n' %
(net.backend_id, result[1]))
else:
stream.write('Successfully connected Network: %s\n' %
net.backend_id)
self.create_backend(clustername, port, username, password,
hypervisor=options["hypervisor"],
initialize=options["init"])

def create_backend(self, clustername, port, username, password,
hypervisor=None, initialize=True):
kw = {"clustername": clustername,
"port": port,
"username": username,
"password": password,
"drained": True}

if hypervisor:
kw["hypervisor"] = hypervisor

# Create the new backend in database
try:
backend = Backend.objects.create(**kw)
except IntegrityError as e:
raise CommandError("Cannot create backend: %s\n" % e)

self.stderr.write("Successfully created backend with id %d\n"
% backend.id)

if not initialize:
return

self.stderr.write("Retrieving backend resources:\n")
resources = backend_mod.get_physical_resources(backend)
attr = ['mfree', 'mtotal', 'dfree',
'dtotal', 'pinst_cnt', 'ctotal']

table = [[str(resources[x]) for x in attr]]
pprint_table(self.stdout, table, attr)

backend_mod.update_backend_resources(backend, resources)
backend_mod.update_backend_disk_templates(backend)

networks = Network.objects.filter(deleted=False, public=True)
if not networks:
return

self.stderr.write("Creating the following public:\n")
headers = ("ID", "Name", 'IPv4 Subnet',
"IPv6 Subnet", 'Mac Prefix')
table = []

for net in networks:
subnet4 = net.subnet4.cidr if net.subnet4 else None
subnet6 = net.subnet6.cidr if net.subnet6 else None
table.append((net.id, net.backend_id, subnet4,
subnet6, str(net.mac_prefix)))
pprint_table(self.stdout, table, headers)

for net in networks:
net.create_backend_network(backend)
result = backend_mod.create_network_synced(net, backend)
if result[0] != "success":
self.stderr.write('\nError Creating Network %s: %s\n'
% (net.backend_id, result[1]))
else:
self.stderr.write('Successfully created Network: %s\n'
% net.backend_id)
result = backend_mod.connect_network_synced(network=net,
backend=backend)
if result[0] != "success":
self.stderr.write('\nError Connecting Network %s: %s\n'
% (net.backend_id, result[1]))
else:
self.stderr.write('Successfully connected Network: %s\n'
% net.backend_id)
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def handle(self, *args, **options):
client = AMQPClient()
client.connect()

pp = pprint.PrettyPrinter(indent=4, width=4)
pp = pprint.PrettyPrinter(indent=4, width=4, stream=self.stdout)

more_msgs = True
counter = 0
Expand All @@ -68,9 +68,9 @@ def handle(self, *args, **options):
msg = client.basic_get(queue=queue)
if msg:
counter += 1
print sep
print 'Message %d:' % counter
print sep
self.stderr.write(sep + "\n")
self.stderr.write('Message %d:\n' % counter)
self.stderr.write(sep + "\n")
pp.pprint(msg)
if not requeue or interactive:
if interactive and not get_user_confirmation():
Expand Down
26 changes: 12 additions & 14 deletions snf-cyclades-app/synnefo/logic/management/commands/server-import.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Copyright 2012 GRNET S.A. All rights reserved.
# Copyright 2012-2014 GRNET S.A. All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
Expand Down Expand Up @@ -43,8 +43,6 @@
from synnefo.logic import servers
from synnefo import quotas

import sys


HELP_MSG = """
Expand Down Expand Up @@ -124,11 +122,11 @@ def handle(self, *args, **options):
raise CommandError(field + " is mandatory")

import_server(instance_name, backend_id, flavor_id, image_id, user_id,
new_public_nic, self.stdout)
new_public_nic, self.stderr)


def import_server(instance_name, backend_id, flavor_id, image_id, user_id,
new_public_nic, stream=sys.stdout):
new_public_nic, stream):
flavor = common.get_resource("flavor", flavor_id)
backend = common.get_resource("backend", backend_id)

Expand All @@ -144,7 +142,7 @@ def import_server(instance_name, backend_id, flavor_id, image_id, user_id,
raise CommandError("Unexpected error" + str(e))

if not new_public_nic:
check_instance_nics(instance)
check_instance_nics(instance, stream)

shutdown_instance(instance, backend_client, stream=stream)

Expand Down Expand Up @@ -180,7 +178,7 @@ def import_server(instance_name, backend_id, flavor_id, image_id, user_id,
return


def flavor_from_instance(instance, flavor, stream=sys.stdout):
def flavor_from_instance(instance, flavor, stream):
beparams = instance['beparams']
disk_sizes = instance['disk.sizes']
if len(disk_sizes) != 1:
Expand All @@ -195,10 +193,10 @@ def flavor_from_instance(instance, flavor, stream=sys.stdout):
cpu=cpu, ram=ram)


def check_instance_nics(instance):
def check_instance_nics(instance, stream):
instance_name = instance['name']
networks = instance['nic.networks.names']
print networks
stream.write(str(networks) + "\n")
try:
networks = map(id_from_network_name, networks)
except Network.InvalidBackendIdError:
Expand All @@ -209,7 +207,7 @@ def check_instance_nics(instance):
" a public network of synnefo." % instance_name)


def remove_instance_nics(instance, backend_client, stream=sys.stdout):
def remove_instance_nics(instance, backend_client, stream):
instance_name = instance['name']
ips = instance['nic.ips']
nic_indexes = xrange(0, len(ips))
Expand All @@ -222,15 +220,15 @@ def remove_instance_nics(instance, backend_client, stream=sys.stdout):
raise CommandError("Cannot remove instance NICs: %s" % error)


def add_public_nic(instance_name, nic, backend_client, stream=sys.stdout):
def add_public_nic(instance_name, nic, backend_client, stream):
stream.write("Adding public NIC %s\n" % nic)
jobid = backend_client.ModifyInstance(instance_name, nics=[('add', nic)])
(status, error) = wait_for_job(backend_client, jobid)
if status != 'success':
raise CommandError("Cannot rename instance: %s" % error)


def shutdown_instance(instance, backend_client, stream=sys.stdout):
def shutdown_instance(instance, backend_client, stream):
instance_name = instance['name']
if instance['status'] != 'ADMIN_down':
stream.write("Instance is not down. Shutting down instance...\n")
Expand All @@ -240,7 +238,7 @@ def shutdown_instance(instance, backend_client, stream=sys.stdout):
raise CommandError("Cannot shutdown instance: %s" % error)


def rename_instance(old_name, new_name, backend_client, stream=sys.stdout):
def rename_instance(old_name, new_name, backend_client, stream):
stream.write("Renaming instance to %s\n" % new_name)

jobid = backend_client.RenameInstance(old_name, new_name,
Expand All @@ -250,7 +248,7 @@ def rename_instance(old_name, new_name, backend_client, stream=sys.stdout):
raise CommandError("Cannot rename instance: %s" % error)


def startup_instance(name, backend_client, stream=sys.stdout):
def startup_instance(name, backend_client, stream):
stream.write("Starting instance %s\n" % name)
jobid = backend_client.StartupInstance(name)
(status, error) = wait_for_job(backend_client, jobid)
Expand Down
Loading

0 comments on commit 66c2390

Please sign in to comment.