Skip to contentSkip to conversation

Lifecycle Patches 4/7

RFC New Ewan Mellor 1 participant 1 message Jul 14, 2006

lore
Share & tools
lore
#0 lore raw

RFC 1/1 Lifecycle Patches 4/7

Xend lifecycle autostart functionality.

 xend/XendDomain.py          |   41 ++++++++++++++++++++++++++++++++++++++---
 xend/XendDomainInfo.py      |   19 +++++++++++++++++--
 xend/server/SrvDaemon.py    |    4 ++++
 xend/server/SrvServer.py    |   26 ++++++++++++++++++++++++--
 xend/server/XMLRPCServer.py |   20 +++++++++++++++++++-
 xm/create.py                |   17 ++++++++++++++++-
 xm/main.py                  |    2 +-
 7 files changed, 119 insertions(+), 10 deletions(-)
tools/python/xen/xm/create.py +16 -1
Index: xen/tools/python/xen/xm/create.py
===================================================================
@@ -429,6 +429,20 @@
           addresses for virtual network interfaces.  This must be a unique 
           value across the entire cluster.""")
 
+gopts.var('autostart', val='no|yes',
+          fn=set_bool, default=0,
+          use="Should the start VM automatically when Xend starts.")
+
+gopts.var('autostop', val='no|yes',
+          fn=set_bool, default=0,
+          use="Should stop VM automatically when Xend stops.")
+
+gopts.var('on_xend_stop', val='shtudown|suspend',
+          fn=set_value, default="shutdown",
+          use="""Behaviour when Xend stops and autostop is on:
+          - shutdown:       Domain is shutdown;
+          - suspend:        Domain is suspended;
+          """)
 
 def err(msg):
     """Print an error to stderr and exit.
@@ -660,7 +674,8 @@
                 config.append([n, v])
 
     map(add_conf, ['name', 'memory', 'maxmem', 'restart', 'on_poweroff',
-                   'on_reboot', 'on_crash', 'vcpus', 'features'])
+                   'on_reboot', 'on_crash', 'vcpus', 'features',
+                   'autostart', 'autostop', 'on_xend_stop'])
 
     if vals.uuid is not None:
         config.append(['uuid', vals.uuid])
tools/python/xen/xend/XendDomain.py +38 -3

65 lines not on this page · raw message

tools/python/xen/xend/server/SrvServer.py +24 -2
Index: xen/tools/python/xen/xend/server/SrvServer.py
===================================================================
@@ -42,6 +42,7 @@
 
 import fcntl
 import time
+import signal
 from threading import Thread
 
 from xen.web.httpserver import HttpServer, UnixHttpServer
@@ -66,6 +67,14 @@
     def add(self, server):
         self.servers.append(server)
 
+    def cleanup(self, signum = 0, frame = None):
+        log.debug("SrvServer.cleanup()")
+        for server in self.servers:
+            try:
+                server.shutdown()
+            except:
+                pass
+
     def start(self, status):
         # Running the network script will spawn another process, which takes
         # the status fd with it unless we set FD_CLOEXEC.  Failing to do this
@@ -100,8 +109,21 @@
             status.write('0')
             status.close()
 
-        for t in threads:
-            t.join()
+        # Prepare to catch SIGTERM (received when 'xend stop' is executed)
+        # and call each server's cleanup if possible
+        signal.signal(signal.SIGTERM, self.cleanup)
+
+        # Interruptible Thread.join - Python Bug #1167930
+        #   Replaces: for t in threads: t.join()
+        #   Reason:   The above will cause python signal handlers to be
+        #             blocked so we're not able to catch SIGTERM in any
+        #             way for cleanup
+        runningThreads = len([t for t in threads if t.isAlive()])
+        while runningThreads > 0:
+            for t in threads:
+                t.join(1.0)
+            runningThreads = len([t for t in threads if t.isAlive()])
+
 
 def create():
     root = SrvDir()
tools/python/xen/xend/XendDomainInfo.py +17 -2
Index: xen/tools/python/xen/xend/XendDomainInfo.py
===================================================================
@@ -179,6 +179,8 @@
     ('maxmem',     int),
     ('start_time', float),
     ('autostart',  int),
+    ('autostop',   int),
+    ('on_xend_stop', str),
     ]
 
 VM_STORE_ENTRIES += VM_CONFIG_PARAMS
@@ -339,6 +341,14 @@
         result['autostart'] = get_cfg('autostart', int)
     except:
         result['autostart'] = 0
+
+    try:
+        result['autostop'] = get_cfg('autostop', int)
+    except:
+        result['autostop'] = 0
+
+
+    result['on_xend_stop'] = get_cfg('on_xend_stop', str)
     
     tmp_security = get_cfg('security')
     if tmp_security:
@@ -624,6 +634,8 @@
             defaultInfo('image',        lambda: None)
             defaultInfo('security',     lambda: None)
             defaultInfo('autostart',    lambda: 0)
+            defaultInfo('autostop',     lambda: 0)
+            defaultInfo('on_xend_stop', lambda: 'shutdown')
 
             self.check_name(self.info['name'])
 
@@ -1228,6 +1240,9 @@
             sxpr.append(['console_mfn', self.console_mfn])
 
         sxpr.append(['autostart', self.info.get('autostart', 0)])
+        sxpr.append(['autostop', self.info.get('autostop', 0)])        
+        sxpr.append(['on_xend_stop', self.info.get('on_xend_stop',
+                                                   'shutdown')])
 
         return sxpr
 
@@ -1472,7 +1487,7 @@
     def destroy(self):
         """Cleanup VM and destroy domain.  Nothrow guarantee."""
 
-        log.debug("XendDomainInfo.destroy: domid=%s", self.domid)
+        log.debug("XendDomainInfo.destroy: domid=%s", str(self.domid))
 
         self.cleanupVm()
         if self.dompath is not None:
@@ -1480,7 +1495,7 @@
 
 
     def destroyDomain(self):
-        log.debug("XendDomainInfo.destroyDomain(%s)", self.domid)
+        log.debug("XendDomainInfo.destroyDomain(%s)", str(self.domid))
 
         try:
             if self.domid is not None:
tools/python/xen/xm/main.py +1 -1
Index: xen/tools/python/xen/xm/main.py
===================================================================
@@ -285,7 +285,7 @@
 
 for command in all_commands:
     # create is handled specially
-    if (command not in ('create', 'new')):
+    if command not in ('create', 'new'):
         help[command] = commandToHelp(command)
 
 
tools/python/xen/xend/server/SrvDaemon.py +4 -0
Index: xen/tools/python/xen/xend/server/SrvDaemon.py
===================================================================
@@ -195,6 +195,8 @@
                                 sig)
                 else:
                     self.run(w and os.fdopen(w, 'w') or None)
+                    # if we reach here, the child should quit.
+                    os._exit(0)
 
         return ret
 
@@ -290,6 +292,8 @@
             relocate.listenRelocation()
             servers = SrvServer.create()
             servers.start(status)
+            del servers
+            
         except Exception, ex:
             print >>sys.stderr, 'Exception starting xend:', ex
             if XEND_DEBUG:
tools/python/xen/xend/server/XMLRPCServer.py +19 -1
Index: xen/tools/python/xen/xend/server/XMLRPCServer.py
===================================================================
@@ -24,6 +24,8 @@
 
 from xen.xend.XendClient import XML_RPC_SOCKET, ERROR_INVALID_DOMAIN
 from xen.xend.XendError import *
+from xen.xend.XendLogging import log
+
 from types import ListType
 
 def lookup(domid):
@@ -84,6 +86,7 @@
     def __init__(self, use_tcp=False):
         self.ready = False
         self.use_tcp = use_tcp
+        self.running = True
         
     def run(self):
         if self.use_tcp:
@@ -123,4 +126,19 @@
 
         self.server.register_introspection_functions()
         self.ready = True
-        self.server.serve_forever()
+
+        # Custom abortable run loop
+        try:
+            self.server.socket.settimeout(1.0)
+            while self.running:
+                self.server.handle_request()
+        finally:
+            self.cleanup()
+
+    def cleanup(self):
+        log.debug("XMLRPCServer.cleanup()")
+        XendDomain.instance().cleanup_domains()
+
+    def shutdown(self):
+        self.running = False
+        

_______________________________________________
Xen-devel mailing list
[email protected]
http://lists.xensource.com/xen-devel