diff --git a/daemons/ganeti-masterd b/daemons/ganeti-masterd
index 9d8635a5ce36ecbe6b8b4c40cf34bb29c5ea5333..c2623b9afd3f4dc53c36a7fb0f0fdf35099843ef 100755
--- a/daemons/ganeti-masterd
+++ b/daemons/ganeti-masterd
@@ -446,27 +446,28 @@ def main():
                     noclose_fds=[master.fileno()])
 
   utils.WritePidFile(constants.MASTERD_PID)
-
-  utils.SetupLogging(constants.LOG_MASTERDAEMON, debug=options.debug,
-                     stderr_logging=not options.fork)
-
-  rpc.Init()
   try:
-    logging.info("ganeti master daemon startup")
+    utils.SetupLogging(constants.LOG_MASTERDAEMON, debug=options.debug,
+                       stderr_logging=not options.fork)
 
-    # activate ip
-    master_node = ssconf.SimpleConfigReader().GetMasterNode()
-    if not rpc.RpcRunner.call_node_start_master(master_node, False):
-      logging.error("Can't activate master IP address")
+    logging.info("Ganeti master daemon startup")
 
-    master.setup_queue()
+    rpc.Init()
     try:
-      master.serve_forever()
+      # activate ip
+      master_node = ssconf.SimpleConfigReader().GetMasterNode()
+      if not rpc.RpcRunner.call_node_start_master(master_node, False):
+        logging.error("Can't activate master IP address")
+
+      master.setup_queue()
+      try:
+        master.serve_forever()
+      finally:
+        master.server_cleanup()
     finally:
-      master.server_cleanup()
-      utils.RemovePidFile(constants.MASTERD_PID)
+      rpc.Shutdown()
   finally:
-    rpc.Shutdown()
+    utils.RemovePidFile(constants.MASTERD_PID)
 
 
 if __name__ == "__main__":