commit b47f167a58d22578ea9dc90e093f43fd935f8706
Author: Christos Stavrakakis <cstavr@grnet.gr>
Date:   Tue Jul 23 11:49:37 2013 +0300

    cyclades: Fixes in network management commands
    
    Merge code from logic/networks.py and network management commands.

diff --git a/snf-cyclades-app/synnefo/api/management/commands/network-create.py b/snf-cyclades-app/synnefo/api/management/commands/network-create.py
index 2a2434c..2b5fdd2 100644
--- a/snf-cyclades-app/synnefo/api/management/commands/network-create.py
+++ b/snf-cyclades-app/synnefo/api/management/commands/network-create.py
@@ -37,9 +37,8 @@ from django.core.management.base import BaseCommand, CommandError
 from synnefo.management.common import get_backend, convert_api_faults
 from synnefo.webproject.management.utils import parse_bool
 
-from synnefo.db.models import Network, Backend
+from synnefo.db.models import Network
 from synnefo.logic import networks
-from synnefo.logic.backend import create_network
 
 NETWORK_FLAVORS = Network.FLAVORS.keys()
 
@@ -177,30 +176,17 @@ class Command(BaseCommand):
             try:
                 backend_id = int(backend_id)
             except ValueError:
-                raise CommandError("Invalid backend-id: %s", backend_id)
+                raise CommandError("Invalid backend-id: %s" % backend_id)
             backend = get_backend(backend_id)
+        else:
+            backend = None
 
         network = networks.create(user_id=userid, name=name, flavor=flavor,
                                   subnet=subnet, gateway=gateway,
                                   subnet6=subnet6, gateway6=gateway6,
                                   dhcp=dhcp, public=public, mode=mode,
                                   link=link, mac_prefix=mac_prefix, tags=tags,
-                                  floating_ip_pool=floating_ip_pool)
-
-        self.stdout.write("Successfully created network '%s' in DB.\n",
-                          network)
-        # Create network in Backend if needed
-        if floating_ip_pool:
-            backends = Backend.objects.filter(offline=False)
-        elif backend_id:
-            backends = [backend]
-        else:
-            backends = []
-
-        for backend in backends:
-            self.stdout.write("Creating network in backend '%s'\n", backend)
-            network.create_backend_network(backend)
-            jobs = create_network(network=network, backend=backend,
-                                  connect=True)
-            self.stdout.write("Successfully issued jobs: %s\n" %
-                              ",".join(map(str, jobs)))
+                                  floating_ip_pool=floating_ip_pool,
+                                  backend=backend, lazy_create=False)
+
+        self.stdout.write("Created network '%s' in DB.\n" % network)
diff --git a/snf-cyclades-app/synnefo/api/management/commands/network-modify.py b/snf-cyclades-app/synnefo/api/management/commands/network-modify.py
index bf7a681..bd87dac 100644
--- a/snf-cyclades-app/synnefo/api/management/commands/network-modify.py
+++ b/snf-cyclades-app/synnefo/api/management/commands/network-modify.py
@@ -31,7 +31,6 @@
 # interpreted as representing official policies, either expressed
 # or implied, of GRNET S.A.
 
-import re
 from optparse import make_option
 
 from django.core.management.base import BaseCommand, CommandError
@@ -157,10 +156,12 @@ class Command(BaseCommand):
                 raise CommandError(msg)
 
         floating_ip_pool = options["floating_ip_pool"]
+        if floating_ip_pool is not None:
+            floating_ip_pool = parse_bool(floating_ip_pool)
         if floating_ip_pool is False and network.floating_ip_pool is True:
             if network.floating_ips.filter(deleted=False).exists():
-                msg = "Can not make network a non floating IP pool. There are"\
-                      " still reserved floating IPs."
+                msg = ("Can not make network a non floating IP pool. There are"
+                       " still reserved floating IPs.")
                 raise CommandError(msg)
         elif floating_ip_pool is True:
             for backend in Backend.objects.filter(offline=False):
@@ -202,7 +203,7 @@ class Command(BaseCommand):
                     bnet = network.backend_networks.get(backend=backend)
                 except BackendNetwork.DoesNotExist:
                     bnet = network.create_backend_network(backend=backend)
-                if bnet.operstate != "ACTVE":
+                if bnet.operstate != "ACTIVE":
                     create_network(network, backend, connect=True)
                     msg = "Sent job to create network '%s' in backend '%s'\n"
                     self.stdout.write(msg % (network, backend))
@@ -238,8 +239,8 @@ def check_link_availability(backend, network):
     mode = network.mode
     link = network.link
     for gnet in ganeti_networks:
-        if gnet["name"] != name and\
-           re.search("(%s, %s)" % (mode, link), gnet["group_list"]):
+        if (gnet["name"] != name and
+           (mode, link) in [(m, l) for (_, m, l) in gnet["group_list"]]):
             msg = "Can not create network '%s' in backend '%s'. Link '%s'" \
                   " is already used by network '%s" % \
                   (network, backend, gnet["name"])
diff --git a/snf-cyclades-app/synnefo/api/management/commands/network-remove.py b/snf-cyclades-app/synnefo/api/management/commands/network-remove.py
index 53592f2..4c10bd6 100644
--- a/snf-cyclades-app/synnefo/api/management/commands/network-remove.py
+++ b/snf-cyclades-app/synnefo/api/management/commands/network-remove.py
@@ -1,4 +1,4 @@
-# Copyright 2011-2012 GRNET S.A. All rights reserved.
+# Copyright 2011-2013 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
@@ -29,41 +29,20 @@
 #
 
 from django.core.management.base import BaseCommand, CommandError
-from synnefo.logic.backend import delete_network
+from synnefo.logic import networks
 from synnefo.management.common import get_network
-from synnefo import quotas
 
 
 class Command(BaseCommand):
     can_import_settings = True
-
     help = "Remove a network from the Database, and Ganeti"
 
-    output_transaction = True  # The management command runs inside
-                               # an SQL transaction
-
     def handle(self, *args, **options):
         if len(args) < 1:
             raise CommandError("Please provide a network ID")
 
         network = get_network(args[0])
 
-        self.stdout.write('Trying to remove network: %s\n' % str(network))
-
-        if network.machines.exists():
-            raise CommandError('Can not delete: Network has connected VMs.')
-        if network.floating_ips.filter(deleted=False).exists():
-            raise CommandError("Can not delete: Network has reserved floating"
-                               " IP addresses.")
-
-        network.action = 'DESTROY'
-        network.save()
-
-        if network.userid:
-            quotas.issue_and_accept_commission(network, delete=True)
-
-        for bnet in network.backend_networks.exclude(operstate="DELETED"):
-            delete_network(network, bnet.backend)
+        self.stdout.write('Removing network: %s\n' % network.backend_id)
 
-        self.stdout.write("Successfully submitted Ganeti jobs to"
-                          " remove network %s" % network.backend_id)
+        networks.delete(network)
diff --git a/snf-cyclades-app/synnefo/logic/networks.py b/snf-cyclades-app/synnefo/logic/networks.py
index 6d6c776..1d00273 100644
--- a/snf-cyclades-app/synnefo/logic/networks.py
+++ b/snf-cyclades-app/synnefo/logic/networks.py
@@ -36,10 +36,10 @@ from django.db import transaction
 from snf_django.lib.api import faults
 from synnefo.api import util
 from synnefo import quotas
-from synnefo.db.models import Network
+from synnefo.db.models import Network, Backend
 from synnefo.db.utils import validate_mac
 from synnefo.db.pools import EmptyPool
-from synnefo.logic import backend
+from synnefo.logic import backend as backend_mod
 
 from logging import getLogger
 log = getLogger(__name__)
@@ -64,7 +64,8 @@ def network_command(action):
 @transaction.commit_on_success
 def create(user_id, name, flavor, subnet=None, gateway=None, subnet6=None,
            gateway6=None, public=False, dhcp=True, link=None, mac_prefix=None,
-           mode=None, floating_ip_pool=False, tags=None):
+           mode=None, floating_ip_pool=False, tags=None, backend=None,
+           lazy_create=True):
     if flavor is None:
         raise faults.BadRequest("Missing request parameter 'type'")
     elif flavor not in Network.FLAVORS.keys():
@@ -124,6 +125,19 @@ def create(user_id, name, flavor, subnet=None, gateway=None, subnet6=None,
     # Note: the following call does a commit!
     if not public:
         quotas.issue_and_accept_commission(network)
+
+    if not lazy_create:
+        if floating_ip_pool:
+            backends = Backend.objects.filter(offline=False)
+        elif backend is not None:
+            backends = [backend]
+        else:
+            backends = []
+
+        for bend in backends:
+            network.create_backend_network(bend)
+            backend_mod.create_network(network=network, backend=bend,
+                                       connect=True)
     return network
 
 
@@ -147,10 +161,9 @@ def delete(network):
     network.save()
 
     # Delete network to all backends that exists
-    backend_networks = network.backend_networks.exclude(operstate="DELETED")
-    for bnet in backend_networks:
-        backend.delete_network(network, bnet.backend)
-    # If network does not exist in any backend, update the network state
-    if not backend_networks:
-        backend.update_network_state(network)
+    for bnet in network.backend_networks.exclude(operstate="DELETED"):
+        backend_mod.delete_network(network, bnet.backend)
+    else:
+        # If network does not exist in any backend, update the network state
+        backend_mod.update_network_state(network)
     return network
