Exemplo n.º 1
0
def listenRelocation():
    xoptions = XendOptions.instance()
    if xoptions.get_xend_unix_server():
        path = '/var/lib/xend/relocation-socket'
        unix.UnixListener(path, RelocationProtocol)

    interface = xoptions.get_xend_relocation_address()

    hosts_allow = xoptions.get_xend_relocation_hosts_allow()
    if hosts_allow == '':
        hosts_allow = None
    else:
        hosts_allow = map(re.compile, hosts_allow.split(" "))

    if xoptions.get_xend_relocation_server():
        port = xoptions.get_xend_relocation_port()
        tcp.TCPListener(RelocationProtocol, port, interface = interface,
                        hosts_allow = hosts_allow)

    if xoptions.get_xend_relocation_ssl_server():
        port = xoptions.get_xend_relocation_ssl_port()
        ssl_key_file = xoptions.get_xend_relocation_server_ssl_key_file()
        ssl_cert_file = xoptions.get_xend_relocation_server_ssl_cert_file()

        if ssl_key_file and ssl_cert_file:
            tcp.SSLTCPListener(RelocationProtocol, port, interface = interface,
                               hosts_allow = hosts_allow,
                               ssl_key_file = ssl_key_file,
                               ssl_cert_file = ssl_cert_file)
        else:
            raise XendError("ssl_key_file or ssl_cert_file for ssl relocation server is missing.")
Exemplo n.º 2
0
def listenRelocation():
    xoptions = XendOptions.instance()
    if xoptions.get_xend_unix_server():
        path = '/var/lib/xend/relocation-socket'
        unix.UnixListener(path, RelocationProtocol)
    if xoptions.get_xend_relocation_server():
        port = xoptions.get_xend_relocation_port()
        interface = xoptions.get_xend_relocation_address()

        hosts_allow = xoptions.get_xend_relocation_hosts_allow()
        if hosts_allow == '':
            hosts_allow = None
        else:
            hosts_allow = map(re.compile, hosts_allow.split(" "))

        tcp.TCPListener(RelocationProtocol, port, interface = interface,
                        hosts_allow = hosts_allow)
Exemplo n.º 3
0
def listenRelocation():
    xoptions = XendOptions.instance()
    if xoptions.get_xend_unix_server():
        path = '/var/lib/xend/relocation-socket'
        unix.UnixListener(path, RelocationProtocol)
    if xoptions.get_xend_relocation_server():
        port = xoptions.get_xend_relocation_port()
        interface = xoptions.get_xend_relocation_address()

        hosts_allow = xoptions.get_xend_relocation_hosts_allow()
        if hosts_allow == '':
            hosts_allow = None
        else:
            hosts_allow = map(re.compile, hosts_allow.split(" "))

        tcp.TCPListener(RelocationProtocol,
                        port,
                        interface=interface,
                        hosts_allow=hosts_allow)
Exemplo n.º 4
0
def listenRelocation():
    xoptions = XendOptions.instance()
    if xoptions.get_xend_unix_server():
        path = '/var/lib/xend/relocation-socket'
        unix.UnixListener(path, RelocationProtocol)

    interface = xoptions.get_xend_relocation_address()

    hosts_allow = xoptions.get_xend_relocation_hosts_allow()
    if hosts_allow == '':
        hosts_allow = None
    else:
        hosts_allow = map(re.compile, hosts_allow.split(" "))

    if xoptions.get_xend_relocation_server():
        port = xoptions.get_xend_relocation_port()
        tcp.TCPListener(RelocationProtocol,
                        port,
                        interface=interface,
                        hosts_allow=hosts_allow)

    if xoptions.get_xend_relocation_ssl_server():
        port = xoptions.get_xend_relocation_ssl_port()
        ssl_key_file = xoptions.get_xend_relocation_server_ssl_key_file()
        ssl_cert_file = xoptions.get_xend_relocation_server_ssl_cert_file()

        if ssl_key_file and ssl_cert_file:
            tcp.SSLTCPListener(RelocationProtocol,
                               port,
                               interface=interface,
                               hosts_allow=hosts_allow,
                               ssl_key_file=ssl_key_file,
                               ssl_cert_file=ssl_cert_file)
        else:
            raise XendError(
                "ssl_key_file or ssl_cert_file for ssl relocation server is missing."
            )
Exemplo n.º 5
0
"""Support for virtual network interfaces.
"""

import os
import random
import re

from xen.xend import XendOptions
from xen.xend.server.DevController import DevController
from xen.xend.XendError import VmError
from xen.xend.XendXSPolicyAdmin import XSPolicyAdminInstance
import xen.util.xsm.xsm as security

from xen.xend.XendLogging import log

xoptions = XendOptions.instance()


def randomMAC():
    """Generate a random MAC address.

    Uses OUI (Organizationally Unique Identifier) 00-16-3E, allocated to
    Xensource, Inc. The OUI list is available at
    http://standards.ieee.org/regauth/oui/oui.txt.

    The remaining 3 fields are random, with the first bit of the first
    random field set 0.

    @return: MAC address string
    """
    mac = [
Exemplo n.º 6
0
    def createDeviceModel(self, restore = False):
        if self.device_model is None:
            return
        if self.pid:
            return
        # Execute device model.
        #todo: Error handling
        args = self.getDeviceModelArgs(restore)
        env = dict(os.environ)
        if self.display:
            env['DISPLAY'] = self.display
        if self.xauthority:
            env['XAUTHORITY'] = self.xauthority
        unique_id = "%i-%i" % (self.vm.getDomid(), time.time())
        sentinel_path = sentinel_path_prefix + unique_id
        sentinel_path_fifo = sentinel_path + '.fifo'
        os.mkfifo(sentinel_path_fifo, 0600)
        sentinel_write = file(sentinel_path_fifo, 'r+')
        self._openSentinel(sentinel_path_fifo)
        self.vm.storeDom("image/device-model-fifo", sentinel_path_fifo)
        xstransact.Mkdir("/local/domain/0/device-model/%i" % self.vm.getDomid())
        xstransact.SetPermissions("/local/domain/0/device-model/%i" % self.vm.getDomid(),
                        { 'dom': self.vm.getDomid(), 'read': True, 'write': True })
        log.info("spawning device models: %s %s", self.device_model, args)
        # keep track of pid and spawned options to kill it later

        self.logfile = "/var/log/xen/qemu-dm-%s.log" %  str(self.vm.info['name_label'])

        # rotate log
        logfile_mode = os.O_WRONLY|os.O_CREAT|os.O_APPEND
        logrotate_count = XendOptions.instance().get_qemu_dm_logrotate_count()
        if logrotate_count > 0:
            logfile_mode |= os.O_TRUNC
            if os.path.exists("%s.%d" % (self.logfile, logrotate_count)):
                os.unlink("%s.%d" % (self.logfile, logrotate_count))
            for n in range(logrotate_count - 1, 0, -1):
                if os.path.exists("%s.%d" % (self.logfile, n)):
                    os.rename("%s.%d" % (self.logfile, n),
                              "%s.%d" % (self.logfile, (n + 1)))
            if os.path.exists(self.logfile):
                os.rename(self.logfile, self.logfile + ".1")

        null = os.open("/dev/null", os.O_RDONLY)
        logfd = os.open(self.logfile, logfile_mode, 0666)
        
        sys.stderr.flush()
        contract = osdep.prefork("%s:%d" %
                                 (self.vm.getName(), self.vm.getDomid()))
        pid = os.fork()
        if pid == 0: #child
            try:
                osdep.postfork(contract)
                os.dup2(null, 0)
                os.dup2(logfd, 1)
                os.dup2(logfd, 2)
                oshelp.close_fds((sentinel_write.fileno(),))
                try:
                    os.execve(self.device_model, args, env)
                except Exception, e:
                    print >>sys.stderr, (
                        'failed to set up fds or execute dm %s: %s' %
                        (self.device_model, utils.exception_string(e)))
                    os._exit(126)
            except:
                os._exit(127)
        else:
            osdep.postfork(contract, abandon=True)
            self.pid = pid
            os.close(null)
            os.close(logfd)
        sentinel_write.close()
        self.vm.storeDom("image/device-model-pid", self.pid)
        log.info("device model pid: %d", self.pid)
        # we would very much prefer not to have a thread here and instead
        #  have a callback but sadly we don't have Twisted in xend
        self.sentinel_thread = thread.start_new_thread(self._sentinel_watch,())
        if self.device_model.find('stubdom-dm') > -1 :
            from xen.xend import XendDomain
            domains = XendDomain.instance()
            domains.domains_lock.release()

            count = 0
            while True:
                orig_state = xstransact.Read("/local/domain/0/device-model/%i/state"
                                    % self.vm.getDomid())
                # This can occur right after start-up
                if orig_state != None:
                    break

                log.debug('createDeviceModel %i: orig_state is None, retrying' % self.vm.getDomid())

                time.sleep(0.1)
                count += 1
                if count > 100:
                    break

            domains.domains_lock.acquire()
Exemplo n.º 7
0
    def parseDeviceModelArgs(self, vmConfig):
        if not enable_qemu_xen:
            ret = ["-domain-name", str(self.vm.info['name_label'])]
        else:
            ret = ["-name", str(self.vm.info['name_label'])]

        xen_extended_power_mgmt = int(vmConfig['platform'].get(
            'xen_extended_power_mgmt', 0))
        if xen_extended_power_mgmt != 0:
            xstransact.Store("/local/domain/0/device-model/%i"
                              % self.vm.getDomid(),
                              ('xen_extended_power_mgmt',
                               xen_extended_power_mgmt))

        # Find RFB console device, and if it exists, make QEMU enable
        # the VNC console.
        if int(vmConfig['platform'].get('nographic', 0)) != 0:
            # skip vnc init if nographic is set
            ret.append('-nographic')
            return ret

        vram = str(vmConfig['platform'].get('videoram',4))
        if not enable_qemu_xen:
            ret.append('-videoram')
            ret.append(vram)

        vnc_config = {}
        has_vnc = int(vmConfig['platform'].get('vnc', 0)) != 0
        has_sdl = int(vmConfig['platform'].get('sdl', 0)) != 0
        opengl = 1
        keymap = vmConfig['platform'].get("keymap")
        for dev_uuid in vmConfig['console_refs']:
            dev_type, dev_info = vmConfig['devices'][dev_uuid]
            if dev_type == 'vfb':
                if 'keymap' in dev_info:
                    keymap = dev_info.get('keymap',{})
                if 'monitor' in dev_info:
                    ret.append("-serial")
                    ret.append(dev_info.get('monitor',{}))
                    ret.append("-monitor")
                    ret.append("null")
                if 'serial' in dev_info:
                    ret.append("-serial")
                    ret.append(dev_info.get('serial',{}))
                if int(dev_info.get('vnc', 0)) != 0 :
                    has_vnc = True
                if int(dev_info.get('sdl', 0)) != 0 :
                    has_sdl = True
                if has_sdl:
                    self.display = dev_info.get('display', self.display)
                    self.xauthority = dev_info.get('xauthority', self.xauthority)
                    opengl = int(dev_info.get('opengl', opengl))
                if has_vnc:
                    vnc_config = dev_info.get('other_config', {})
                break

        if keymap:
            ret.append("-k")
            ret.append(keymap)

        if has_vnc:
            if not vnc_config:
                for key in ('vncunused', 'vnclisten', 'vncdisplay',
                            'vncpasswd'):
                    if key in vmConfig['platform']:
                        vnc_config[key] = vmConfig['platform'][key]
            if vnc_config.has_key("vncpasswd"):
                passwd = vnc_config["vncpasswd"]
            else:
                passwd = XendOptions.instance().get_vncpasswd_default()
            vncopts = ""
            if passwd:
                self.vm.storeVm("vncpasswd", passwd)
                self.vm.permissionsVm("vncpasswd", { 'dom': self.vm.getDomid(), 'read': True } )
                vncopts = vncopts + ",password"
                log.debug("Stored a VNC password for vfb access")
            else:
                log.debug("No VNC passwd configured for vfb access")

            if XendOptions.instance().get_vnc_tls():
                vncx509certdir = XendOptions.instance().get_vnc_x509_cert_dir()
                vncx509verify = XendOptions.instance().get_vnc_x509_verify()

                if not os.path.exists(vncx509certdir):
                    raise VmError("VNC x509 certificate dir %s does not exist" % vncx509certdir)

                if vncx509verify:
                    vncopts = vncopts + ",tls,x509verify=%s" % vncx509certdir
                else:
                    vncopts = vncopts + ",tls,x509=%s" % vncx509certdir


            vnclisten = vnc_config.get('vnclisten',
                                       XendOptions.instance().get_vnclisten_address())
            vncdisplay = int(vnc_config.get('vncdisplay', 0))
            ret.append('-vnc')
            if not enable_qemu_xen:
                ret.append("%s:%s%s" % (vnclisten, vncdisplay, vncopts))
            else:
                ret.append("%s:%s%s, to=99" % (vnclisten, vncdisplay, vncopts))
                ret.append('-sdl')
                
            if not enable_qemu_xen:
                if int(vnc_config.get('vncunused', 1)) != 0:
                    ret.append('-vncunused')

        if has_sdl:
            ret.append('-sdl')
            if int(vmConfig['platform'].get('opengl', opengl)) != 1 :
                ret.append('-disable-opengl')

        if not has_sdl and not has_vnc :
            ret.append('-nographic')

        if vmConfig['platform'].get('parallel'):
            ret = ret + ["-parallel", vmConfig['platform'].get('parallel')]

        if int(vmConfig['platform'].get('monitor', 0)) != 0:
            if vmConfig['platform'].get('monitor_path'):
                ret = ret + ['-monitor', vmConfig['platform'].get('monitor_path')]
            else:
                ret = ret + ['-monitor', 'vc']

        return ret
Exemplo n.º 8
0
    def parseDeviceModelArgs(self, vmConfig):
        ret = ["-domain-name", str(self.vm.info["name_label"])]

        xen_extended_power_mgmt = int(vmConfig["platform"].get("xen_extended_power_mgmt", 0))
        if xen_extended_power_mgmt != 0:
            xstransact.Store(
                "/local/domain/0/device-model/%i" % self.vm.getDomid(),
                ("xen_extended_power_mgmt", xen_extended_power_mgmt),
            )

        # Find RFB console device, and if it exists, make QEMU enable
        # the VNC console.
        if int(vmConfig["platform"].get("nographic", 0)) != 0:
            # skip vnc init if nographic is set
            ret.append("-nographic")
            return ret

        vram = str(vmConfig["platform"].get("videoram", 4))
        ret.append("-videoram")
        ret.append(vram)

        vnc_config = {}
        has_vnc = int(vmConfig["platform"].get("vnc", 0)) != 0
        has_sdl = int(vmConfig["platform"].get("sdl", 0)) != 0
        opengl = 1
        keymap = vmConfig["platform"].get("keymap")
        for dev_uuid in vmConfig["console_refs"]:
            dev_type, dev_info = vmConfig["devices"][dev_uuid]
            if dev_type == "vfb":
                if "keymap" in dev_info:
                    keymap = dev_info.get("keymap", {})
                if "monitor" in dev_info:
                    ret.append("-serial")
                    ret.append(dev_info.get("monitor", {}))
                    ret.append("-monitor")
                    ret.append("null")
                if "serial" in dev_info:
                    ret.append("-serial")
                    ret.append(dev_info.get("serial", {}))
                if int(dev_info.get("vnc", 0)) != 0:
                    has_vnc = True
                if int(dev_info.get("sdl", 0)) != 0:
                    has_sdl = True
                if has_sdl:
                    self.display = dev_info.get("display", self.display)
                    self.xauthority = dev_info.get("xauthority", self.xauthority)
                    opengl = int(dev_info.get("opengl", opengl))
                if has_vnc:
                    vnc_config = dev_info.get("other_config", {})
                break

        if keymap:
            ret.append("-k")
            ret.append(keymap)

        if has_vnc:
            if not vnc_config:
                for key in ("vncunused", "vnclisten", "vncdisplay", "vncpasswd"):
                    if key in vmConfig["platform"]:
                        vnc_config[key] = vmConfig["platform"][key]
            if vnc_config.has_key("vncpasswd"):
                passwd = vnc_config["vncpasswd"]
            else:
                passwd = XendOptions.instance().get_vncpasswd_default()
            vncopts = ""
            if passwd:
                self.vm.storeVm("vncpasswd", passwd)
                self.vm.permissionsVm("vncpasswd", {"dom": self.vm.getDomid(), "read": True})
                vncopts = vncopts + ",password"
                log.debug("Stored a VNC password for vfb access")
            else:
                log.debug("No VNC passwd configured for vfb access")

            if XendOptions.instance().get_vnc_tls():
                vncx509certdir = XendOptions.instance().get_vnc_x509_cert_dir()
                vncx509verify = XendOptions.instance().get_vnc_x509_verify()

                if not os.path.exists(vncx509certdir):
                    raise VmError("VNC x509 certificate dir %s does not exist" % vncx509certdir)

                if vncx509verify:
                    vncopts = vncopts + ",tls,x509verify=%s" % vncx509certdir
                else:
                    vncopts = vncopts + ",tls,x509=%s" % vncx509certdir

            vnclisten = vnc_config.get("vnclisten", XendOptions.instance().get_vnclisten_address())
            vncdisplay = int(vnc_config.get("vncdisplay", 0))
            ret.append("-vnc")
            ret.append("%s:%s%s" % (vnclisten, vncdisplay, vncopts))

            if int(vnc_config.get("vncunused", 1)) != 0:
                ret.append("-vncunused")

        if has_sdl:
            ret.append("-sdl")
            if int(vmConfig["platform"].get("opengl", opengl)) != 1:
                ret.append("-disable-opengl")

        if not has_sdl and not has_vnc:
            ret.append("-nographic")

        if vmConfig["platform"].get("parallel"):
            ret = ret + ["-parallel", vmConfig["platform"].get("parallel")]

        if int(vmConfig["platform"].get("monitor", 0)) != 0:
            if vmConfig["platform"].get("monitor_path"):
                ret = ret + ["-monitor", vmConfig["platform"].get("monitor_path")]
            else:
                ret = ret + ["-monitor", "vc"]

        return ret
Exemplo n.º 9
0
    def createDeviceModel(self, restore=False):
        if self.device_model is None:
            return
        if self.pid:
            return
        # Execute device model.
        #todo: Error handling
        args = self.getDeviceModelArgs(restore)
        env = dict(os.environ)
        if self.display:
            env['DISPLAY'] = self.display
        if self.xauthority:
            env['XAUTHORITY'] = self.xauthority
        unique_id = "%i-%i" % (self.vm.getDomid(), time.time())
        sentinel_path = sentinel_path_prefix + unique_id
        sentinel_path_fifo = sentinel_path + '.fifo'
        os.mkfifo(sentinel_path_fifo, 0600)
        sentinel_write = file(sentinel_path_fifo, 'r+')
        self._openSentinel(sentinel_path_fifo)
        self.vm.storeDom("image/device-model-fifo", sentinel_path_fifo)
        xstransact.Mkdir("/local/domain/0/device-model/%i" %
                         self.vm.getDomid())
        xstransact.SetPermissions(
            "/local/domain/0/device-model/%i" % self.vm.getDomid(), {
                'dom': self.vm.getDomid(),
                'read': True,
                'write': True
            })
        log.info("spawning device models: %s %s", self.device_model, args)
        # keep track of pid and spawned options to kill it later

        self.logfile = "/var/log/xen/qemu-dm-%s.log" % str(
            self.vm.info['name_label'])

        # rotate log
        logfile_mode = os.O_WRONLY | os.O_CREAT | os.O_APPEND
        logrotate_count = XendOptions.instance().get_qemu_dm_logrotate_count()
        if logrotate_count > 0:
            logfile_mode |= os.O_TRUNC
            if os.path.exists("%s.%d" % (self.logfile, logrotate_count)):
                os.unlink("%s.%d" % (self.logfile, logrotate_count))
            for n in range(logrotate_count - 1, 0, -1):
                if os.path.exists("%s.%d" % (self.logfile, n)):
                    os.rename("%s.%d" % (self.logfile, n),
                              "%s.%d" % (self.logfile, (n + 1)))
            if os.path.exists(self.logfile):
                os.rename(self.logfile, self.logfile + ".1")

        null = os.open("/dev/null", os.O_RDONLY)
        logfd = os.open(self.logfile, logfile_mode, 0666)

        sys.stderr.flush()
        contract = osdep.prefork("%s:%d" %
                                 (self.vm.getName(), self.vm.getDomid()))
        pid = os.fork()
        if pid == 0:  #child
            try:
                osdep.postfork(contract)
                os.dup2(null, 0)
                os.dup2(logfd, 1)
                os.dup2(logfd, 2)
                oshelp.close_fds((sentinel_write.fileno(), ))
                try:
                    os.execve(self.device_model, args, env)
                except Exception, e:
                    print >> sys.stderr, (
                        'failed to set up fds or execute dm %s: %s' %
                        (self.device_model, utils.exception_string(e)))
                    os._exit(126)
            except:
                os._exit(127)
        else:
            osdep.postfork(contract, abandon=True)
            self.pid = pid
            os.close(null)
            os.close(logfd)
        sentinel_write.close()
        self.vm.storeDom("image/device-model-pid", self.pid)
        log.info("device model pid: %d", self.pid)
        # we would very much prefer not to have a thread here and instead
        #  have a callback but sadly we don't have Twisted in xend
        self.sentinel_thread = thread.start_new_thread(self._sentinel_watch,
                                                       ())
        if self.device_model.find('stubdom-dm') > -1:
            from xen.xend import XendDomain
            domains = XendDomain.instance()
            domains.domains_lock.release()

            count = 0
            while True:
                orig_state = xstransact.Read(
                    "/local/domain/0/device-model/%i/state" %
                    self.vm.getDomid())
                # This can occur right after start-up
                if orig_state != None:
                    break

                log.debug(
                    'createDeviceModel %i: orig_state is None, retrying' %
                    self.vm.getDomid())

                time.sleep(0.1)
                count += 1
                if count > 100:
                    break

            domains.domains_lock.acquire()
Exemplo n.º 10
0
    def parseDeviceModelArgs(self, vmConfig):
        ret = ["-domain-name", str(self.vm.info['name_label'])]

        xen_extended_power_mgmt = int(vmConfig['platform'].get(
            'xen_extended_power_mgmt', 0))
        if xen_extended_power_mgmt != 0:
            xstransact.Store(
                "/local/domain/0/device-model/%i" % self.vm.getDomid(),
                ('xen_extended_power_mgmt', xen_extended_power_mgmt))

        # Find RFB console device, and if it exists, make QEMU enable
        # the VNC console.
        if int(vmConfig['platform'].get('nographic', 0)) != 0:
            # skip vnc init if nographic is set
            ret.append('-nographic')
            return ret

        vram = str(vmConfig['platform'].get('videoram', 4))
        ret.append('-videoram')
        ret.append(vram)

        vnc_config = {}
        has_vnc = int(vmConfig['platform'].get('vnc', 0)) != 0
        has_sdl = int(vmConfig['platform'].get('sdl', 0)) != 0
        opengl = 1
        keymap = vmConfig['platform'].get("keymap")
        for dev_uuid in vmConfig['console_refs']:
            dev_type, dev_info = vmConfig['devices'][dev_uuid]
            if dev_type == 'vfb':
                if 'keymap' in dev_info:
                    keymap = dev_info.get('keymap', {})
                if 'monitor' in dev_info:
                    ret.append("-serial")
                    ret.append(dev_info.get('monitor', {}))
                    ret.append("-monitor")
                    ret.append("null")
                if 'serial' in dev_info:
                    ret.append("-serial")
                    ret.append(dev_info.get('serial', {}))
                if int(dev_info.get('vnc', 0)) != 0:
                    has_vnc = True
                if int(dev_info.get('sdl', 0)) != 0:
                    has_sdl = True
                if has_sdl:
                    self.display = dev_info.get('display', self.display)
                    self.xauthority = dev_info.get('xauthority',
                                                   self.xauthority)
                    opengl = int(dev_info.get('opengl', opengl))
                if has_vnc:
                    vnc_config = dev_info.get('other_config', {})
                break

        if keymap:
            ret.append("-k")
            ret.append(keymap)

        if has_vnc:
            if not vnc_config:
                for key in ('vncunused', 'vnclisten', 'vncdisplay',
                            'vncpasswd'):
                    if key in vmConfig['platform']:
                        vnc_config[key] = vmConfig['platform'][key]
            if vnc_config.has_key("vncpasswd"):
                passwd = vnc_config["vncpasswd"]
            else:
                passwd = XendOptions.instance().get_vncpasswd_default()
            vncopts = ""
            if passwd:
                self.vm.storeVm("vncpasswd", passwd)
                self.vm.permissionsVm("vncpasswd", {
                    'dom': self.vm.getDomid(),
                    'read': True
                })
                vncopts = vncopts + ",password"
                log.debug("Stored a VNC password for vfb access")
            else:
                log.debug("No VNC passwd configured for vfb access")

            if XendOptions.instance().get_vnc_tls():
                vncx509certdir = XendOptions.instance().get_vnc_x509_cert_dir()
                vncx509verify = XendOptions.instance().get_vnc_x509_verify()

                if not os.path.exists(vncx509certdir):
                    raise VmError(
                        "VNC x509 certificate dir %s does not exist" %
                        vncx509certdir)

                if vncx509verify:
                    vncopts = vncopts + ",tls,x509verify=%s" % vncx509certdir
                else:
                    vncopts = vncopts + ",tls,x509=%s" % vncx509certdir

            vnclisten = vnc_config.get(
                'vnclisten',
                XendOptions.instance().get_vnclisten_address())
            vncdisplay = int(vnc_config.get('vncdisplay', 0))
            ret.append('-vnc')
            ret.append("%s:%s%s" % (vnclisten, vncdisplay, vncopts))

            if int(vnc_config.get('vncunused', 1)) != 0:
                ret.append('-vncunused')

        if has_sdl:
            ret.append('-sdl')
            if int(vmConfig['platform'].get('opengl', opengl)) != 1:
                ret.append('-disable-opengl')

        if not has_sdl and not has_vnc:
            ret.append('-nographic')

        if vmConfig['platform'].get('parallel'):
            ret = ret + ["-parallel", vmConfig['platform'].get('parallel')]

        if int(vmConfig['platform'].get('monitor', 0)) != 0:
            if vmConfig['platform'].get('monitor_path'):
                ret = ret + [
                    '-monitor', vmConfig['platform'].get('monitor_path')
                ]
            else:
                ret = ret + ['-monitor', 'vc']

        return ret
Exemplo n.º 11
0
    def parseDeviceModelArgs(self, vmConfig):
        ret = ["-domain-name", str(self.vm.info['name_label'])]

        xen_extended_power_mgmt = int(vmConfig['platform'].get(
            'xen_extended_power_mgmt', 0))
        if xen_extended_power_mgmt != 0:
             xstransact.Store("/local/domain/0/device-model/%i"
                              % self.vm.getDomid(),
                              ('xen_extended_power_mgmt',
                               xen_extended_power_mgmt))

        # Find RFB console device, and if it exists, make QEMU enable
        # the VNC console.
        if int(vmConfig['platform'].get('nographic', 0)) != 0:
            # skip vnc init if nographic is set
            ret.append('-nographic')
            return ret

        vram = str(vmConfig['platform'].get('videoram',4))
        ret.append('-videoram')
        ret.append(vram)

        vnc_config = {}
        has_vnc = int(vmConfig['platform'].get('vnc', 0)) != 0
        has_sdl = int(vmConfig['platform'].get('sdl', 0)) != 0
        opengl = 1
        keymap = vmConfig['platform'].get("keymap")
        for dev_uuid in vmConfig['console_refs']:
            dev_type, dev_info = vmConfig['devices'][dev_uuid]
            if dev_type == 'vfb':
                if 'keymap' in dev_info:
                    keymap = dev_info.get('keymap',{})
                if 'monitor' in dev_info:
                    ret.append("-serial")
                    ret.append(dev_info.get('monitor',{}))
                    ret.append("-monitor")
                    ret.append("null")
                if 'serial' in dev_info:
                    ret.append("-serial")
                    ret.append(dev_info.get('serial',{}))
                if int(dev_info.get('vnc', 0)) != 0 :
                    has_vnc = True
                if int(dev_info.get('sdl', 0)) != 0 :
                    has_sdl = True
                if has_sdl:
                    self.display = dev_info.get('display', self.display)
                    self.xauthority = dev_info.get('xauthority', self.xauthority)
                    opengl = int(dev_info.get('opengl', opengl))
                if has_vnc:
                    vnc_config = dev_info.get('other_config', {})
                break

        if keymap:
            ret.append("-k")
            ret.append(keymap)

        if has_vnc:
            if not vnc_config:
                for key in ('vncunused', 'vnclisten', 'vncdisplay',
                            'vncpasswd'):
                    if key in vmConfig['platform']:
                        vnc_config[key] = vmConfig['platform'][key]
            if vnc_config.has_key("vncpasswd"):
                passwd = vnc_config["vncpasswd"]
            else:
                passwd = XendOptions.instance().get_vncpasswd_default()
            vncopts = ""
            if passwd:
                self.vm.storeVm("vncpasswd", passwd)
                self.vm.permissionsVm("vncpasswd", { 'dom': self.vm.getDomid(), 'read': True } )
                vncopts = vncopts + ",password"
                log.debug("Stored a VNC password for vfb access")
            else:
                log.debug("No VNC passwd configured for vfb access")

            if XendOptions.instance().get_vnc_tls():
                vncx509certdir = XendOptions.instance().get_vnc_x509_cert_dir()
                vncx509verify = XendOptions.instance().get_vnc_x509_verify()

                if not os.path.exists(vncx509certdir):
                    raise VmError("VNC x509 certificate dir %s does not exist" % vncx509certdir)

                if vncx509verify:
                    vncopts = vncopts + ",tls,x509verify=%s" % vncx509certdir
                else:
                    vncopts = vncopts + ",tls,x509=%s" % vncx509certdir


            vnclisten = vnc_config.get('vnclisten',
                                       XendOptions.instance().get_vnclisten_address())
            vncdisplay = int(vnc_config.get('vncdisplay', 0))
            ret.append('-vnc')
            ret.append("%s:%s%s" % (vnclisten, vncdisplay, vncopts))

            if int(vnc_config.get('vncunused', 1)) != 0:
                ret.append('-vncunused')

        spice_config = {}
        qxl_config = {}
        has_spice = int(vmConfig['platform'].get('spice', 0)) != 0
        has_qxl = int(vmConfig['platform'].get('qxl', 0)) != 0

        if has_spice:
            if not spice_config:
                for skey in ('spicehost', 'spiceport', 'spicepasswd',
                   'spice_disable_ticketing', 'spiceic', 'spicesv', 'spicejpeg_wan_compression',
                   'spicezlib_glz_wan_compression', 'spiceplayback', 'spiceagent_mouse'):
                    if skey in vmConfig['platform']:
                        spice_config[skey] = vmConfig['platform'][skey]
            spicehost = spice_config.get('spicehost', '127.0.0.1')
            spiceport = int(spice_config.get('spiceport', 6000))
            spicepasswd = spice_config.get('spicepasswd', '')
            spice_disable_ticketing = int(spice_config.get('spice_disable_ticketing', 0))

            spiceic = spice_config.get('spiceic', 'auto_glz')
            spicesv = spice_config.get('spicesv', 'on')
            spicejpeg_wan_compression = spice_config.get('spicejpeg_wan_compression', 'auto')
            spicezlib_glz_wan_compression = spice_config.get('spicezlib_glz_wan_compression', 'auto')
            spiceplayback = int(spice_config.get('spiceplayback', 1))
            spiceagent_mouse = int(spice_config.get('spiceagent_mouse', 1))
            ret.append('-spice')
            ret.append("port=%s,host=%s,passwd=%s,disable_ticketing=%s,ic=%s,sv=%s,jpeg_wan_compression=%s,\
zlib_glz_wan_compression=%s,playback=%s,agent_mouse=%s" % (spiceport, spicehost, spicepasswd,
            spice_disable_ticketing, spiceic, spicesv, spicejpeg_wan_compression,
            spicezlib_glz_wan_compression, spiceplayback, spiceagent_mouse))

        if has_qxl:
            if not qxl_config:
                for skey in ('qxlnum', 'qxlram'):
                    if skey in vmConfig['platform']:
                        qxl_config[skey] = vmConfig['platform'][skey]
            qxlnum = int(qxl_config.get('qxlnum', 1))
            qxlram = int(qxl_config.get('qxlram', 64))
            ret.append('-qxl')
            ret.append('num=%s,ram=%s' % (qxlnum, qxlram))

        if has_sdl:
            ret.append('-sdl')
            if int(vmConfig['platform'].get('opengl', opengl)) != 1 :
                ret.append('-disable-opengl')

        if not has_sdl and not has_vnc :
            ret.append('-nographic')

        if vmConfig['platform'].get('parallel'):
            ret = ret + ["-parallel", vmConfig['platform'].get('parallel')]

        if int(vmConfig['platform'].get('monitor', 0)) != 0:
            if vmConfig['platform'].get('monitor_path'):
                ret = ret + ['-monitor', vmConfig['platform'].get('monitor_path')]
            else:
                ret = ret + ['-monitor', 'vc']

        return ret
Exemplo n.º 12
0
    def createDeviceModel(self, restore = False):
        if self.device_model is None:
            return
        if self.pid:
            return
        # Execute device model.
        #todo: Error handling
        args = self.getDeviceModelArgs(restore)
        env = dict(os.environ)
        if self.display:
            env['DISPLAY'] = self.display
        if self.xauthority:
            env['XAUTHORITY'] = self.xauthority
        if self.vncconsole:
            args = args + ([ "-vncviewer" ])
        unique_id = "%i-%i" % (self.vm.getDomid(), time.time())
        sentinel_path = sentinel_path_prefix + unique_id
        sentinel_path_fifo = sentinel_path + '.fifo'
        os.mkfifo(sentinel_path_fifo, 0600)
        sentinel_write = file(sentinel_path_fifo, 'r+')
        self._openSentinel(sentinel_path_fifo)
        self.vm.storeDom("image/device-model-fifo", sentinel_path_fifo)
        xstransact.Mkdir("/local/domain/0/device-model/%i" % self.vm.getDomid())
        xstransact.SetPermissions("/local/domain/0/device-model/%i" % self.vm.getDomid(),
                        { 'dom': self.vm.getDomid(), 'read': True, 'write': True })
        log.info("spawning device models: %s %s", self.device_model, args)
        # keep track of pid and spawned options to kill it later

        self.logfile = "/var/log/xen/qemu-dm-%s.log" %  str(self.vm.info['name_label'])

        # rotate log
        logfile_mode = os.O_WRONLY|os.O_CREAT|os.O_APPEND
        logrotate_count = XendOptions.instance().get_qemu_dm_logrotate_count()
        if logrotate_count > 0:
            logfile_mode |= os.O_TRUNC
            if os.path.exists("%s.%d" % (self.logfile, logrotate_count)):
                os.unlink("%s.%d" % (self.logfile, logrotate_count))
            for n in range(logrotate_count - 1, 0, -1):
                if os.path.exists("%s.%d" % (self.logfile, n)):
                    os.rename("%s.%d" % (self.logfile, n),
                              "%s.%d" % (self.logfile, (n + 1)))
            if os.path.exists(self.logfile):
                os.rename(self.logfile, self.logfile + ".1")

        null = os.open("/dev/null", os.O_RDONLY)
        logfd = os.open(self.logfile, logfile_mode)
        
        sys.stderr.flush()
        pid = os.fork()
        if pid == 0: #child
            try:
                os.dup2(null, 0)
                os.dup2(logfd, 1)
                os.dup2(logfd, 2)
                os.close(null)
                os.close(logfd)
                self.sentinel_fifo.close()
                try:
                    os.execve(self.device_model, args, env)
                except Exception, e:
                    print >>sys.stderr, (
                        'failed to set up fds or execute dm %s: %s' %
                        (self.device_model, utils.exception_string(e)))
                    os._exit(126)
            except:
                os._exit(127)
        else:
            self.pid = pid
            os.close(null)
            os.close(logfd)
        sentinel_write.close()
        self.vm.storeDom("image/device-model-pid", self.pid)
        log.info("device model pid: %d", self.pid)
        # we would very much prefer not to have a thread here and instead
        #  have a callback but sadly we don't have Twisted in xend
        self.sentinel_thread = thread.start_new_thread(self._sentinel_watch,())
Exemplo n.º 13
0
    def parseDeviceModelArgs(self, vmConfig):
        ret = ["-domain-name", str(self.vm.info['name_label'])]

        # Find RFB console device, and if it exists, make QEMU enable
        # the VNC console.
        if int(vmConfig['platform'].get('nographic', 0)) != 0:
            # skip vnc init if nographic is set
            ret.append('-nographic')
            return ret

        vnc_config = {}
        has_vnc = int(vmConfig['platform'].get('vnc', 0)) != 0
        has_sdl = int(vmConfig['platform'].get('sdl', 0)) != 0
        for dev_uuid in vmConfig['console_refs']:
            dev_type, dev_info = vmConfig['devices'][dev_uuid]
            if dev_type == 'vfb':
                vfb_type = dev_info.get('type', {})
                if vfb_type == 'sdl':
                    self.display = dev_info.get('display', {})
                    self.xauthority = dev_info.get('xauthority', {})
                    has_sdl = True
                else:
                    vnc_config = dev_info.get('other_config', {})
                    has_vnc = True
                break

        keymap = vmConfig['platform'].get("keymap")
        if keymap:
            ret.append("-k")
            ret.append(keymap)

        if has_vnc:
            if not vnc_config:
                for key in ('vncunused', 'vnclisten', 'vncdisplay',
                            'vncpasswd'):
                    if key in vmConfig['platform']:
                        vnc_config[key] = vmConfig['platform'][key]
            if vnc_config.has_key("vncpasswd"):
                passwd = vnc_config["vncpasswd"]
            else:
                passwd = XendOptions.instance().get_vncpasswd_default()
            vncopts = ""
            if passwd:
                self.vm.storeVm("vncpasswd", passwd)
                vncopts = vncopts + ",password"
                log.debug("Stored a VNC password for vfb access")
            else:
                log.debug("No VNC passwd configured for vfb access")

            if XendOptions.instance().get_vnc_tls():
                vncx509certdir = XendOptions.instance().get_vnc_x509_cert_dir()
                vncx509verify = XendOptions.instance().get_vnc_x509_verify()

                if not os.path.exists(vncx509certdir):
                    raise VmError(
                        "VNC x509 certificate dir %s does not exist" %
                        vncx509certdir)

                if vncx509verify:
                    vncopts = vncopts + ",tls,x509verify=%s" % vncx509certdir
                else:
                    vncopts = vncopts + ",tls,x509=%s" % vncx509certdir

            vnclisten = vnc_config.get(
                'vnclisten',
                XendOptions.instance().get_vnclisten_address())
            vncdisplay = vnc_config.get('vncdisplay', 0)
            ret.append('-vnc')
            ret.append("%s:%s%s" % (vnclisten, vncdisplay, vncopts))

            if vnc_config.get('vncunused', 0):
                ret.append('-vncunused')

        elif has_sdl:
            # SDL is default in QEMU.
            pass
        else:
            ret.append('-nographic')

        if int(vmConfig['platform'].get('monitor', 0)) != 0:
            ret = ret + ['-monitor', 'vc']
        return ret
Exemplo n.º 14
0
def listenUdevEvent():
    xoptions = XendOptions.instance()
    if xoptions.get_xend_udev_event_server():
        unix.UnixDgramListener(UDEV_EVENT_PATH, UdevEventProtocol)
Exemplo n.º 15
0
    def parseDeviceModelArgs(self, vmConfig):
        ret = ["-domain-name", str(self.vm.info['name_label'])]

        # Find RFB console device, and if it exists, make QEMU enable
        # the VNC console.
        if int(vmConfig['platform'].get('nographic', 0)) != 0:
            # skip vnc init if nographic is set
            ret.append('-nographic')
            return ret

        vnc_config = {}
        has_vnc = int(vmConfig['platform'].get('vnc', 0)) != 0
        has_sdl = int(vmConfig['platform'].get('sdl', 0)) != 0
        for dev_uuid in vmConfig['console_refs']:
            dev_type, dev_info = vmConfig['devices'][dev_uuid]
            if dev_type == 'vfb':
                vfb_type = dev_info.get('type', {})
                if vfb_type == 'sdl':
                    self.display = dev_info.get('display', {})
                    self.xauthority = dev_info.get('xauthority', {})
                    has_sdl = True
                else:
                    vnc_config = dev_info.get('other_config', {})
                    has_vnc = True
                break

        keymap = vmConfig['platform'].get("keymap")
        if keymap:
            ret.append("-k")
            ret.append(keymap)

        if has_vnc:
            if not vnc_config:
                for key in ('vncunused', 'vnclisten', 'vncdisplay',
                            'vncpasswd'):
                    if key in vmConfig['platform']:
                        vnc_config[key] = vmConfig['platform'][key]
            if vnc_config.has_key("vncpasswd"):
                passwd = vnc_config["vncpasswd"]
            else:
                passwd = XendOptions.instance().get_vncpasswd_default()
            vncopts = ""
            if passwd:
                self.vm.storeVm("vncpasswd", passwd)
                vncopts = vncopts + ",password"
                log.debug("Stored a VNC password for vfb access")
            else:
                log.debug("No VNC passwd configured for vfb access")

            if XendOptions.instance().get_vnc_tls():
                vncx509certdir = XendOptions.instance().get_vnc_x509_cert_dir()
                vncx509verify = XendOptions.instance().get_vnc_x509_verify()

                if not os.path.exists(vncx509certdir):
                    raise VmError("VNC x509 certificate dir %s does not exist" % vncx509certdir)

                if vncx509verify:
                    vncopts = vncopts + ",tls,x509verify=%s" % vncx509certdir
                else:
                    vncopts = vncopts + ",tls,x509=%s" % vncx509certdir


            vnclisten = vnc_config.get('vnclisten',
                                       XendOptions.instance().get_vnclisten_address())
            vncdisplay = vnc_config.get('vncdisplay', 0)
            ret.append('-vnc')
            ret.append("%s:%s%s" % (vnclisten, vncdisplay, vncopts))

            if vnc_config.get('vncunused', 0):
                ret.append('-vncunused')

        elif has_sdl:
            # SDL is default in QEMU.
            pass
        else:
            ret.append('-nographic')

        if int(vmConfig['platform'].get('monitor', 0)) != 0:
            ret = ret + ['-monitor', 'vc']
        return ret
Exemplo n.º 16
0
Missing      = 3
Timeout      = 4
Busy         = 5
Disconnected = 6

xenbusState = {
    'Unknown'      : 0,
    'Initialising' : 1,
    'InitWait'     : 2,
    'Initialised'  : 3,
    'Connected'    : 4,
    'Closing'      : 5,
    'Closed'       : 6,
    }

xoptions = XendOptions.instance()

xenbusState.update(dict(zip(xenbusState.values(), xenbusState.keys())))


class DevController:
    """Abstract base class for a device controller.  Device controllers create
    appropriate entries in the store to trigger the creation, reconfiguration,
    and destruction of devices in guest domains.  Each subclass of
    DevController is responsible for a particular device-class, and
    understands the details of configuration specific to that device-class.

    DevController itself provides the functionality common to all device
    creation tasks, as well as providing an interface to XendDomainInfo for
    triggering those events themselves.
    """
Exemplo n.º 17
0
def listenUdevEvent():
    xoptions = XendOptions.instance()
    if xoptions.get_xend_udev_event_server():
        unix.UnixDgramListener(UDEV_EVENT_PATH, UdevEventProtocol)