From 3c9c571da2a639cbd5cb01a18db447a085c345a2 Mon Sep 17 00:00:00 2001
From: Iustin Pop <iustin@google.com>
Date: Wed, 7 Jan 2009 17:01:58 +0000
Subject: [PATCH] Remove instance's symlinks

This is a forward-port of commits 1150 and 1151 on the 1.2 branch:
  Add _RemoveBlockDevLinks auxiliary function, called when an instance
  fails to start and when it is shut down.

  Reviewed-by: iustinp

and:
  Fix cut&paste error when removing symlinks

  It's just whitespace... isn't it? uhm... :) Anyway, fixing an error made
  when reformatting the code for the new "safer" behaviour.

  Reviewed-by: iustinp

Original-Author: ultrotter
---
 lib/backend.py | 15 +++++++++++++++
 1 file changed, 15 insertions(+)

diff --git a/lib/backend.py b/lib/backend.py
index 4839c6162..419b9a7d0 100644
--- a/lib/backend.py
+++ b/lib/backend.py
@@ -764,6 +764,18 @@ def _SymlinkBlockDev(instance_name, device_path, device_name):
   return link_name
 
 
+def _RemoveBlockDevLinks(instance_name):
+  """Remove the block device symlinks belonging to the given instance.
+
+  """
+  for i in os.listdir(constants.DISK_LINKS_DIR):
+    if os.path.islink(i) and i.startswith('%s-' % instance_name):
+      try:
+        os.remove(link)
+      except OSError, e:
+        pass # Ignore errors when removing the symlinks
+
+
 def _GatherAndLinkBlockDevs(instance):
   """Set up an instance's block device(s).
 
@@ -818,6 +830,7 @@ def StartInstance(instance, extra_args):
     return False
   except errors.HypervisorError, err:
     logging.exception("Failed to start instance")
+    _RemoveBlockDevLinks(instance.name)
     return False
 
   return True
@@ -870,6 +883,8 @@ def ShutdownInstance(instance):
                     instance.name)
       return False
 
+  _RemoveBlockDevLinks(instance.name)
+
   return True
 
 
-- 
GitLab