Example #1
0
    def getDeviceDetails(self, config):
    
         
        """@see DevController.getDeviceDetails"""

#        dev = sxp.child_value(config, 'dev')
#        (typ, params) = string.split(sxp.child_value(config, 'uname'), ':', 1)


        uname = sxp.child_value(config, 'uname')
        (typ, params) = string.split(uname, ':')
        dev = sxp.child_value(config, 'dev')
        mode = sxp.child_value(config, 'mode')

        back = { 'dev'    : dev,
                 'type'   : typ,
                 'params' : params,
                 'mode'   : sxp.child_value(config, 'mode', 'r')
                 }

#        if 'ioemu:' in dev:
#            (dummy, dev1) = string.split(dev, ':', 1)
#            devid = blkif.blkdev_name_to_number(dev1)
#            front = {}
#        else:
#            devid = blkif.blkdev_name_to_number(dev)

        devid = 777
        front = { 'virtual-device' : "%i" % devid }

        return (devid, back, front)
Example #2
0
def diagnose(dom):
    global domain
    global domid
    global dompath

    try:
        domain = server.xend.domain(dom)
        state = sxp.child_value(domain, 'state')
        domid = int(sxp.child_value(domain, 'domid'))
        name = sxp.child_value(domain, 'name')

        print "Domain ID is %d." % domid
        print "Domain name is %s." % name

        if not state:
            raise XendError("Cannot find state")

        if state.find('c') != -1:
            print "Domain has crashed."
    except socket.error, exn:
        print "Cannot contact Xend."

        try:
            domid = int(dom)
            name = dom
        except ValueError:
            print \
"Without Xend, you will have to specify the domain ID, not the domain name."
            sys.exit(1)
Example #3
0
def xm_domname(args):
    arg_check(args, "domname", 1)

    name = args[0]

    dom = server.xend.domain(name)
    print sxp.child_value(dom, "name")
def diagnose(dom):
    global domain
    global domid
    global dompath
    
    try:
        domain = server.xend.domain(dom)
        state = sxp.child_value(domain, 'state')
        domid = int(sxp.child_value(domain, 'domid'))
        name = sxp.child_value(domain, 'name')

        print "Domain ID is %d." % domid
        print "Domain name is %s." % name

        if not state:
            raise XendError("Cannot find state")

        if state.find('c') != -1:
            print "Domain has crashed."
    except socket.error, exn:
        print "Cannot contact Xend."

        try:
            domid = int(dom)
            name = dom
        except ValueError:
            print \
"Without Xend, you will have to specify the domain ID, not the domain name."
            sys.exit(1)
Example #5
0
def xm_domname(args):
    arg_check(args, "domname", 1)

    name = args[0]

    dom = server.xend.domain(name)
    print sxp.child_value(dom, 'name')
Example #6
0
def diagnose(dom):
    global domain
    global domid
    global dompath
    
    try:
        domain = server.xend_domain(dom)
        state = sxp.child_value(domain, 'state')
        domid = int(sxp.child_value(domain, 'domid'))
        name = sxp.child_value(domain, 'name')
        dompath = '/local/domain/%d' % domid

        print "Domain ID is %d." % domid
        print "Domain name is %s." % name

        if not state:
            raise XendError("Cannot find state")

        if state.find('c') != -1:
            print "Domain has crashed."

        diagnose_console()

        diagnose_devices()
    except xen.xend.XendProtocol.XendError, exn:
        print exn
Example #7
0
def config_security_check(config, verbose):
    """Checks each resource listed in the config to see if the active
       policy will permit creation of a new domain using the config.
       Returns 1 if the config passes all tests, otherwise 0.
    """
    answer = 1

    # get the domain acm_label
    domain_label = None
    domain_policy = None
    for x in sxp.children(config):
        if sxp.name(x) == 'security':
            domain_label = sxp.child_value(sxp.name(sxp.child0(x)), 'label')
            domain_policy = sxp.child_value(sxp.name(sxp.child0(x)), 'policy')

    # if no domain label, use default
    if not domain_label and security.on():
        try:
            domain_label = security.ssidref2label(security.NULL_SSIDREF)
        except:
            import traceback
            traceback.print_exc(limit=1)
            return 0
        domain_policy = 'NULL'
    elif not domain_label:
        domain_label = ""
        domain_policy = 'NULL'

    if verbose:
        print "Checking resources:"

    # build a list of all resources in the config file
    resources = []
    for x in sxp.children(config):
        if sxp.name(x) == 'device':
            if sxp.name(sxp.child0(x)) == 'vbd':
                resources.append(sxp.child_value(sxp.child0(x), 'uname'))

    # perform a security check on each resource
    for resource in resources:
        try:
            security.res_security_check(resource, domain_label)
            if verbose:
                print "   %s: PERMITTED" % (resource)

        except security.XSMError:
            print "   %s: DENIED" % (resource)
            (poltype, res_label, res_policy) = security.get_res_label(resource)
            if not res_label:
                res_label = ""
            print "   --> res: %s (%s:%s)" % (str(res_label),
                                           str(poltype), str(res_policy))
            print "   --> dom: %s (%s:%s)" % (str(domain_label),
                                           str(poltype), str(domain_policy))

            answer = 0

    return answer
Example #8
0
def config_security_check(config, verbose):
    """Checks each resource listed in the config to see if the active
       policy will permit creation of a new domain using the config.
       Returns 1 if the config passes all tests, otherwise 0.
    """
    answer = 1

    # get the domain acm_label
    domain_label = None
    domain_policy = None
    for x in sxp.children(config):
        if sxp.name(x) == 'security':
            domain_label = sxp.child_value(sxp.name(sxp.child0(x)), 'label')
            domain_policy = sxp.child_value(sxp.name(sxp.child0(x)), 'policy')

    # if no domain label, use default
    if not domain_label and security.on():
        try:
            domain_label = security.ssidref2label(security.NULL_SSIDREF)
        except:
            import traceback
            traceback.print_exc(limit=1)
            return 0
        domain_policy = 'NULL'
    elif not domain_label:
        domain_label = ""
        domain_policy = 'NULL'

    if verbose:
        print "Checking resources:"

    # build a list of all resources in the config file
    resources = []
    for x in sxp.children(config):
        if sxp.name(x) == 'device':
            if sxp.name(sxp.child0(x)) == 'vbd':
                resources.append(sxp.child_value(sxp.child0(x), 'uname'))

    # perform a security check on each resource
    for resource in resources:
        try:
            security.res_security_check(resource, domain_label)
            if verbose:
                print "   %s: PERMITTED" % (resource)

        except security.XSMError:
            print "   %s: DENIED" % (resource)
            (poltype, res_label, res_policy) = security.get_res_label(resource)
            if not res_label:
                res_label = ""
            print "   --> res: %s (%s:%s)" % (str(res_label), str(poltype),
                                              str(res_policy))
            print "   --> dom: %s (%s:%s)" % (str(domain_label), str(poltype),
                                              str(domain_policy))

            answer = 0

    return answer
Example #9
0
    def getDeviceDetails(self, config):
        """@see DevController.getDeviceDetails"""

        devid = self.allocateDeviceID()
        inst = int(sxp.child_value(config, 'pref_instance', '-1'))
        if inst == -1:
            inst = int(sxp.child_value(config, 'instance' , '0'))

        log.info("The domain has a TPM with instance %d and devid %d.",
                 inst, devid)
        back  = { 'pref_instance' : "%i" % inst,
                  'resume'        : "%s" % (self.vm.getResume()) }
        front = { 'handle' : "%i" % devid }

        return (devid, back, front)
 def __init__(self, dbpath, config=None):
     if config:
         self.id = str(sxp.child_value(config, 'id'))
         self.dbid = self.id.replace(':', '-')
         self.dbpath = dbpath + '/' + self.dbid
         self.config = config
     else:
         self.dbpath = dbpath
         self.importFromDB()
         
     self.bridge = sxp.child_value(self.config, 'bridge')
     if not self.bridge:
         self.bridge = "vnet%s" % self.id
     self.vnetif = sxp.child_value(self.config, 'vnetif')
     if not self.vnetif:
         self.vnetif = "vnif%s" % self.id
Example #11
0
def xm_console(args):
    arg_check(args, "console", 1)

    dom = args[0]
    info = server.xend.domain(dom)
    domid = int(sxp.child_value(info, "domid", "-1"))
    console.execConsole(domid)
    def get_runtime_properties(self):
        xendom = XendDomain.instance()
        dominfo = xendom.get_vm_by_uuid(self.VM)

        try:
            device_dict = {}
            for device_sxp in dominfo.getDeviceSxprs('vscsi'):
                target_dev = None
                for dev in device_sxp[1][0][1]:
                    vdev = sxp.child_value(dev, 'v-dev')
                    if vdev == self.virtual_HCTL:
                        target_dev = dev
                        break
                if target_dev is None:
                    continue

                dev_dict = {}
                for info in target_dev[1:]:
                    dev_dict[info[0]] = info[1]
                device_dict['dev'] = dev_dict
                for info in device_sxp[1][1:]:
                    device_dict[info[0]] = info[1]

            return device_dict
        except Exception, exn:
            log.exception(exn)
            return {}
Example #13
0
def xm_console(args):
    arg_check(args, "console", 1)

    dom = args[0]
    info = server.xend.domain(dom)
    domid = int(sxp.child_value(info, 'domid', '-1'))
    console.execConsole(domid)
Example #14
0
    def get_runtime_properties(self):
        xendom = XendDomain.instance()
        dominfo = xendom.get_vm_by_uuid(self.VM)

        try:
            device_dict = {}
            for device_sxp in dominfo.getDeviceSxprs('vscsi'):
                target_dev = None
                for dev in device_sxp[1][0][1]:
                    vdev = sxp.child_value(dev, 'v-dev')
                    if vdev == self.virtual_HCTL:
                        target_dev = dev
                        break
                if target_dev is None:
                    continue

                dev_dict = {}
                for info in target_dev[1:]:
                    dev_dict[info[0]] = info[1]
                device_dict['dev'] = dev_dict
                for info in device_sxp[1][1:]:
                    device_dict[info[0]] = info[1]

            return device_dict
        except Exception, exn:
            log.exception(exn)
            return {}
Example #15
0
    def __init__(self, dbpath, config=None):
        if config:
            self.id = str(sxp.child_value(config, 'id'))
            self.dbid = self.id.replace(':', '-')
            self.dbpath = dbpath + '/' + self.dbid
            self.config = config
        else:
            self.dbpath = dbpath
            self.importFromDB()

        self.bridge = sxp.child_value(self.config, 'bridge')
        if not self.bridge:
            self.bridge = "vnet%s" % self.id
        self.vnetif = sxp.child_value(self.config, 'vnetif')
        if not self.vnetif:
            self.vnetif = "vnif%s" % self.id
Example #16
0
    def getDeviceDetails(self, config):
        """@see DevController.getDeviceDetails"""

        devid = self.allocateDeviceID()
        inst = int(sxp.child_value(config, 'pref_instance', '-1'))
        if inst == -1:
            inst = int(sxp.child_value(config, 'instance', '0'))

        log.info("The domain has a TPM with instance %d and devid %d.", inst,
                 devid)
        back = {
            'pref_instance': "%i" % inst,
            'resume': "%s" % (self.vm.getResume())
        }
        front = {'handle': "%i" % devid}

        return (devid, back, front)
Example #17
0
    def get_config_value(self, name, val=None):
        """Get the value of an atomic configuration element.

        @param name: element name
        @param val:  default value (optional, defaults to None)
        @return: value
        """
        return sxp.child_value(self.config, name, val=val)
Example #18
0
    def get_config_value(self, name, val=None):
        """Get the value of an atomic configuration element.

        @param name: element name
        @param val:  default value (optional, defaults to None)
        @return: value
        """
        return sxp.child_value(self.config, name, val=val)
Example #19
0
    def getDeviceDetails(self, config):
        """@see DevController.getDeviceDetails"""

        #log.debug('pci config='+sxp.to_string(config))

        def get_param(config, field, default=None):
            try:
                val = sxp.child_value(config, field)

                if not val:
                    if default == None:
                        raise VmError('pci: Missing %s config setting' % field)
                    else:
                        return default

                if isinstance(val, types.StringType):
                    return int(val, 16)
                else:
                    return val
            except:
                if default == None:
                    raise VmError('pci: Invalid config setting %s: %s' %
                                  (field, val))
                else:
                    return default

        back = {}

        val = sxp.child_value(config, 'dev')
        if isinstance(val, list):
            pcidevid = 0
            for dev_config in sxp.children(config, 'dev'):
                domain = get_param(dev_config, 'domain', 0)
                bus = get_param(dev_config, 'bus')
                slot = get_param(dev_config, 'slot')
                func = get_param(dev_config, 'func')

                self.setupDevice(domain, bus, slot, func)

                back['dev-%i'%(pcidevid)]="%04x:%02x:%02x.%02x"% \
                        (domain, bus, slot, func)
                pcidevid += 1

            back['num_devs'] = str(pcidevid)

        else:
            # Xen 2.0 configuration compatibility
            domain = get_param(dev_config, 'domain', 0)
            bus = get_param(config, 'bus')
            slot = get_param(config, 'dev')
            func = get_param(config, 'func')

            self.setupDevice(domain, bus, slot, func)

            back['dev-0'] = "%04x:%02x:%02x.%02x" % (domain, bus, slot, func)
            back['num_devs'] = str(1)

        return (0, back, {})
def main_dom(opts, args):
    if len(args) == 0: opts.err('No domain parameter given')
    if len(args) >  1: opts.err('No multiple domain parameters allowed')
    if serverType == SERVER_XEN_API:
        dom = get_single_vm(args[0])
    else:
        dom = sxp.child_value(server.xend.domain(args[0]), 'name')
    mode = shutdown_mode(opts)  
    shutdown(opts, [ dom ], mode, opts.vals.wait)
Example #21
0
    def getDeviceDetails(self, config):
        """@see DevController.getDeviceDetails"""
        #log.debug('pci config='+sxp.to_string(config))

        def get_param(config, field, default=None):
            try:
                val = sxp.child_value(config, field)

                if not val:
                    if default==None:
                        raise VmError('pci: Missing %s config setting' % field)
                    else:
                        return default

                if isinstance(val, types.StringType):
                    return int(val, 16)
                else:
                    return val
            except:
                if default==None:
                    raise VmError('pci: Invalid config setting %s: %s' %
                              (field, val))
                else:
                    return default
        
        back = {}

        val = sxp.child_value(config, 'dev')
        if isinstance(val, list):
            pcidevid = 0
            for dev_config in sxp.children(config, 'dev'):
                domain = get_param(dev_config, 'domain', 0)
                bus = get_param(dev_config,'bus')
                slot = get_param(dev_config,'slot')
                func = get_param(dev_config,'func')

                self.setupDevice(domain, bus, slot, func)

                back['dev-%i'%(pcidevid)]="%04x:%02x:%02x.%02x"% \
                        (domain, bus, slot, func)
                pcidevid+=1
            
            back['num_devs']=str(pcidevid)

        else:
            # Xen 2.0 configuration compatibility
            domain = get_param(dev_config, 'domain', 0)
            bus  = get_param(config, 'bus')
            slot = get_param(config, 'dev')
            func = get_param(config, 'func')

            self.setupDevice(domain, bus, slot, func)

            back['dev-0']="%04x:%02x:%02x.%02x"%(domain, bus, slot, func)
            back['num_devs']=str(1)

        return (0, back, {})
Example #22
0
    def configVNC(self, config):
        # Handle graphics library related options
        vnc = sxp.child_value(config, 'vnc')
        sdl = sxp.child_value(config, 'sdl')
        ret = []
        nographic = sxp.child_value(config, 'nographic')
        if nographic:
            ret.append('-nographic')
            return ret

        if vnc and sdl:
            ret = ret + ['-vnc-and-sdl', '-k', 'en-us']
        elif vnc:
            ret = ret + ['-vnc', '-k', 'en-us']
        if vnc:
            vncport = int(self.vm.getDomid()) + 5900
            ret = ret + ['-vncport', '%d' % vncport]
        return ret
Example #23
0
def main_dom(opts, args):
    if len(args) == 0: opts.err('No domain parameter given')
    if len(args) > 1: opts.err('No multiple domain parameters allowed')
    if serverType == SERVER_XEN_API:
        dom = get_single_vm(args[0])
    else:
        dom = sxp.child_value(server.xend.domain(args[0]), 'name')
    mode = shutdown_mode(opts)
    shutdown(opts, [dom], mode, opts.vals.wait)
def main_all(opts, args):
    if serverType == SERVER_XEN_API:
        doms = [dom for dom in server.xenapi.VM.get_all()
                if not server.xenapi.VM.get_is_control_domain(dom)]
    else:
        doms = server.xend.domains(0)
        dom0_name = sxp.child_value(server.xend.domain(0), 'name')
        doms.remove(dom0_name)
    mode = shutdown_mode(opts)  
    shutdown(opts, doms, mode, opts.vals.wait)
Example #25
0
        def get_param(field):
            try:
                val = sxp.child_value(config, field)

                if not val:
                    raise VmError('ioports: Missing %s config setting' % field)

                return parse_ioport(val)
            except:
                raise VmError('ioports: Invalid config setting %s: %s' %
                              (field, val))
Example #26
0
def main_all(opts, args):
    if serverType == SERVER_XEN_API:
        doms = [
            dom for dom in server.xenapi.VM.get_all()
            if not server.xenapi.VM.get_is_control_domain(dom)
        ]
    else:
        doms = server.xend.domains(0)
        dom0_name = sxp.child_value(server.xend.domain(0), 'name')
        doms.remove(dom0_name)
    mode = shutdown_mode(opts)
    shutdown(opts, doms, mode, opts.vals.wait)
Example #27
0
    def configure(self, imageConfig, deviceConfig):
        ImageHandler.configure(self, imageConfig, deviceConfig)

        info = xc.xeninfo()
        if not 'hvm' in info['xen_caps']:
            raise VmError("Not an HVM capable platform, we stop creating!")

        self.dmargs = self.parseDeviceModelArgs(imageConfig, deviceConfig)
        self.device_model = sxp.child_value(imageConfig, 'device_model')
        if not self.device_model:
            raise VmError("hvm: missing device model")
        self.display = sxp.child_value(imageConfig, 'display')
        self.xauthority = sxp.child_value(imageConfig, 'xauthority')

        self.vm.storeVm(("image/dmargs", " ".join(self.dmargs)),
                        ("image/device-model", self.device_model),
                        ("image/display", self.display))

        self.pid = 0

        self.dmargs += self.configVNC(imageConfig)

        self.pae  = int(sxp.child_value(imageConfig, 'pae', 0))

        self.acpi = int(sxp.child_value(imageConfig, 'acpi', 0))
        self.apic = int(sxp.child_value(imageConfig, 'apic', 0))
Example #28
0
def get_vbd_paths(domain):
    info = server.xend.domain(domain,1)
    devices = [x[1] for x in sxp.children(info,'device')]
    vbds = sxp.children(devices,'vbd')
    for vbd in vbds:
        path = sxp.child_value(vbd,'uname')
        if path.startswith("phy:"):
            path = path.replace("phy:", "/dev/")
        elif path.startswith("file:"):
            path = path.replace("file:", "")
        else :
            raise 'not handled'
        yield path
Example #29
0
 def getDeviceDetails(self, config):
     log.debug('vbfs config=' + sxp.to_string(config))
     luns = sxp.child_value(config, 'luns')
     if not luns:
         log.debug('vbfs: luns param not set')
         raise VmError('luns param not set')
     back = {'luns': luns}
     #        devid = self.allocateDeviceID()
     devid = 1
     front = {'virtual-device': "%i" % devid}
     log.info('bfsback :%s', back)
     log.info('bfsfront:%s', front)
     return (devid, back, front)
Example #30
0
    def getDeviceDetails(self, config):
        """@see DevControllergetDeviceDetails"""

        ssi = sxp.child_value(config, 'ssi')

        back = { 'ssi' : ssi}
        """ device id is determined by O.S. (see blkif.getDeviceDetails)
	"""
        devid = 9999
	ssa_value = 444
        front = { 'virtual-device' : "%i" % devid, 'ssa-register': "%i" % ssa_value}

        return (devid, back, front)
Example #31
0
 def getDeviceDetails(self, config):
     log.debug("vbfs config=" + sxp.to_string(config))
     luns = sxp.child_value(config, "luns")
     if not luns:
         log.debug("vbfs: luns param not set")
         raise VmError("luns param not set")
     back = {"luns": luns}
     #        devid = self.allocateDeviceID()
     devid = 1
     front = {"virtual-device": "%i" % devid}
     log.info("bfsback :%s", back)
     log.info("bfsfront:%s", front)
     return (devid, back, front)
Example #32
0
def get_vbd_paths(domain):
    info = server.xend.domain(domain)
    devices = [x[1] for x in sxp.children(info, 'device')]
    vbds = sxp.children(devices, 'vbd')
    for vbd in vbds:
        path = sxp.child_value(vbd, 'uname')
        if path.startswith("phy:"):
            path = path.replace("phy:", "/dev/")
        elif path.startswith("file:"):
            path = path.replace("file:", "")
        else:
            raise 'not handled'
        yield path
Example #33
0
    def addStoreEntries(self, config, devid, backDetails, frontDetails):
        """Add to backDetails and frontDetails the entries to be written in
        the store to trigger creation of a device.  The backend domain ID is
        taken from the given config, paths for frontend and backend are
        computed, and these are added to the backDetails and frontDetails
        dictionaries for writing to the store, including references from
        frontend to backend and vice versa.

        @return A pair of (backpath, frontpath).  backDetails and frontDetails
        will have been updated appropriately, also.

        @param config The configuration of the device, as given to
        {@link #createDevice}.
        @param devid        As returned by {@link #getDeviceDetails}.
        @param backDetails  As returned by {@link #getDeviceDetails}.
        @param frontDetails As returned by {@link #getDeviceDetails}.
        """

        import xen.xend.XendDomain
        xd = xen.xend.XendDomain.instance()

        backdom_name = sxp.child_value(config, 'backend')
        if backdom_name:
            backdom = xd.domain_lookup_by_name_or_id_nr(backdom_name)
        else:
            backdom = xd.privilegedDomain()

        if not backdom:
            raise VmError("Cannot configure device for unknown backend %s" %
                          backdom_name)

        frontpath = self.frontendPath(devid)
        backpath  = self.backendPath(backdom, devid)
        
        frontDetails.update({
            'backend' : backpath,
            'backend-id' : "%i" % backdom.getDomid(),
            'state' : str(xenbusState['Initialising'])
            })


        backDetails.update({
            'domain' : self.vm.getName(),
            'frontend' : frontpath,
            'frontend-id' : "%i" % self.vm.getDomid(),
            'state' : str(xenbusState['Initialising'])
            })

        return (backpath, frontpath)
Example #34
0
        def get_param(field):
            try:
                val = sxp.child_value(config, field)

                if not val:
                    raise VmError('irq: Missing %s config setting' % field)

                if isinstance(val, types.StringType):
                    return int(val,10)
                    radix = 10
                else:
                    return val
            except:
                raise VmError('irq: Invalid config setting %s: %s' %
                              (field, val))
Example #35
0
        def get_param(field):
            try:
                val = sxp.child_value(config, field)

                if not val:
                    raise VmError('irq: Missing %s config setting' % field)

                if isinstance(val, types.StringType):
                    return int(val, 10)
                    radix = 10
                else:
                    return val
            except:
                raise VmError('irq: Invalid config setting %s: %s' %
                              (field, val))
Example #36
0
    def getDeviceDetails(self, config):
        """@see DevControllergetDeviceDetails"""

        ssi = sxp.child_value(config, 'ssi')

        back = {'ssi': ssi}
        """ device id is determined by O.S. (see blkif.getDeviceDetails)
	"""
        devid = 9999
        ssa_value = 444
        front = {
            'virtual-device': "%i" % devid,
            'ssa-register': "%i" % ssa_value
        }

        return (devid, back, front)
Example #37
0
 def convertToDeviceNumber(self, devid):
     try:
         return int(devid)
     except ValueError:
         if type(devid) is not str:
             raise VmError("devid %s is wrong type" % str(devid))
         try:
             dev = devid.split('/')[-1]
             return (int(dev))
         except ValueError:
             devs = [d for d in self.vm.info.all_devices_sxpr()
                 if d[0] == 'vif']
             for nr in range(len(devs)):
                 dev_type, dev_info = devs[nr]
                 if (sxp.child_value(dev_info, 'mac').lower() ==
                     devid.lower()):
                     return nr
             raise VmError("unknown devid %s" % str(devid))
Example #38
0
 def convertToDeviceNumber(self, devid):
     try:
         return int(devid)
     except ValueError:
         if type(devid) is not str:
             raise VmError("devid %s is wrong type" % str(devid))
         try:
             dev = devid.split('/')[-1]
             return (int(dev))
         except ValueError:
             devs = [
                 d for d in self.vm.info.all_devices_sxpr() if d[0] == 'vif'
             ]
             for nr in range(len(devs)):
                 dev_type, dev_info = devs[nr]
                 if (sxp.child_value(dev_info,
                                     'mac').lower() == devid.lower()):
                     return nr
             raise VmError("unknown devid %s" % str(devid))
Example #39
0
        def get_param(config, field, default=None):
            try:
                val = sxp.child_value(config, field)

                if not val:
                    if default == None:
                        raise VmError('pci: Missing %s config setting' % field)
                    else:
                        return default

                if isinstance(val, types.StringType):
                    return int(val, 16)
                else:
                    return val
            except:
                if default == None:
                    raise VmError('pci: Invalid config setting %s: %s' %
                                  (field, val))
                else:
                    return default
Example #40
0
        def get_param(config, field, default=None):
            try:
                val = sxp.child_value(config, field)

                if not val:
                    if default==None:
                        raise VmError('pci: Missing %s config setting' % field)
                    else:
                        return default

                if isinstance(val, types.StringType):
                    return int(val, 16)
                else:
                    return val
            except:
                if default==None:
                    raise VmError('pci: Invalid config setting %s: %s' %
                              (field, val))
                else:
                    return default
Example #41
0
def check_domain_label(config, verbose):
    """All that we need to check here is that the domain label exists and
       is not null when security is on.  Other error conditions are
       handled when the config file is parsed.
    """
    answer = 0
    default_label = None
    secon = 0
    if security.on():
        default_label = security.ssidref2label(security.NULL_SSIDREF)
        secon = 1

    # get the domain acm_label
    dom_label = None
    dom_name = None
    for x in sxp.children(config):
        if sxp.name(x) == 'security':
            dom_label = sxp.child_value(sxp.name(sxp.child0(x)), 'label')
        if sxp.name(x) == 'name':
            dom_name = sxp.child0(x)

    # sanity check on domain label
    if verbose:
        print "Checking domain:"
    if (not secon) and (not dom_label):
        answer = 1
        if verbose:
            print "   %s: PERMITTED" % (dom_name)
    elif (secon) and (dom_label) and (dom_label != default_label):
        answer = 1
        if verbose:
            print "   %s: PERMITTED" % (dom_name)
    else:
        print "   %s: DENIED" % (dom_name)
        if not secon:
            print "   --> Security off, but domain labeled"
        else:
            print "   --> Domain not labeled"
        answer = 0

    return answer
Example #42
0
def check_domain_label(config, verbose):
    """All that we need to check here is that the domain label exists and
       is not null when security is on.  Other error conditions are
       handled when the config file is parsed.
    """
    answer = 0
    default_label = None
    secon = 0
    if security.on():
        default_label = security.ssidref2label(security.NULL_SSIDREF)
        secon = 1

    # get the domain acm_label
    dom_label = None
    dom_name = None
    for x in sxp.children(config):
        if sxp.name(x) == 'security':
            dom_label = sxp.child_value(sxp.name(sxp.child0(x)), 'label')
        if sxp.name(x) == 'name':
            dom_name = sxp.child0(x)

    # sanity check on domain label
    if verbose:
        print "Checking domain:"
    if (not secon) and (not dom_label):
        answer = 1
        if verbose:
            print "   %s: PERMITTED" % (dom_name)
    elif (secon) and (dom_label) and (dom_label != default_label):
        answer = 1
        if verbose:
            print "   %s: PERMITTED" % (dom_name)
    else:
        print "   %s: DENIED" % (dom_name)
        if not secon:
            print "   --> Security off, but domain labeled"
        else:
            print "   --> Domain not labeled"
        answer = 0

    return answer
Example #43
0
def shutdown(opts, doms, mode, wait):
    if doms == None: doms = server.xend.domains(0)
    dom0_name = sxp.child_value(server.xend.domain(0), 'name')
    for x in [dom0_name, DOM0_ID]:
        if x in doms:
            if opts.vals.all:
                doms.remove(x)
            else:
                opts.err("Can't specify Domain-0")
    for d in doms:
        server.xend.domain.shutdown(d, mode)
    if wait:
        while doms:
            alive = server.xend.domains(0)
            dead = []
            for d in doms:
                if d in alive: continue
                dead.append(d)
            for d in dead:
                opts.info("Domain %s terminated" % d)
                doms.remove(d)
            time.sleep(1)
        opts.info("All domains terminated")
Example #44
0
def shutdown(opts, doms, mode, wait):
    if doms == None: doms = server.xend.domains(0)
    dom0_name = sxp.child_value(server.xend.domain(0), 'name')
    for x in [dom0_name, DOM0_ID]:
        if x in doms:
            if opts.vals.all:
                doms.remove(x)
            else:
                opts.err("Can't specify Domain-0")
    for d in doms:
        server.xend.domain.shutdown(d, mode)
    if wait:
        while doms:
            alive = server.xend.domains(0)
            dead = []
            for d in doms:
                if d in alive: continue
                dead.append(d)
            for d in dead:
                opts.info("Domain %s terminated" % d)
                doms.remove(d)
            time.sleep(1)
        opts.info("All domains terminated")
Example #45
0
def do_console(domain_name):
    cpid = os.fork() 
    if cpid != 0:
        for i in range(10):
            # Catch failure of the create process 
            time.sleep(1)
            (p, rv) = os.waitpid(cpid, os.WNOHANG)
            if os.WIFEXITED(rv):
                if os.WEXITSTATUS(rv) != 0:
                    sys.exit(os.WEXITSTATUS(rv))
            try:
                # Acquire the console of the created dom
                if serverType == SERVER_XEN_API:
                    domid = server.xenapi.VM.get_domid(
                               get_single_vm(domain_name))
                else:
                    dom = server.xend.domain(domain_name)
                    domid = int(sxp.child_value(dom, 'domid', '-1'))
                console.execConsole(domid)
            except:
                pass
        print("Could not start console\n");
        sys.exit(0)
Example #46
0
    def getDeviceDetails(self, config):
        """@see DevController.getDeviceDetails"""

        def _get_config_ipaddr(config):
            val = []
            for ipaddr in sxp.children(config, elt='ip'):
                val.append(sxp.child0(ipaddr))
            return val

        script = os.path.join(xroot.network_script_dir,
                              sxp.child_value(config, 'script',
                                              xroot.get_vif_script()))
        typ = sxp.child_value(config, 'type')
        bridge  = sxp.child_value(config, 'bridge')
        mac     = sxp.child_value(config, 'mac')
        vifname = sxp.child_value(config, 'vifname')
        rate    = sxp.child_value(config, 'rate')
        ipaddr  = _get_config_ipaddr(config)

        devid = self.allocateDeviceID()

        if not mac:
            mac = randomMAC()

        back = { 'script' : script,
                 'mac'    : mac,
                 'handle' : "%i" % devid }

        if typ == 'ioemu':
            front = {}
            back['type'] = 'ioemu'
        else:
            front = { 'handle' : "%i" % devid,
                      'mac'    : mac }
        if ipaddr:
            back['ip'] = ' '.join(ipaddr)
        if bridge:
            back['bridge'] = bridge
        if vifname:
            back['vifname'] = vifname
        if rate:
            back['rate'] = parseRate(rate)

        return (devid, back, front)
Example #47
0
    def extract_scsis(self, scsis_sxp, document):

        scsis = []

        for scsi_sxp in scsis_sxp:
            feature_host = sxp.child_value(scsi_sxp, "feature-host")
            for dev_sxp in sxp.children(scsi_sxp, "dev"):
                scsi = document.createElement("vscsi")

                scsi.attributes["feature-host"] \
                    = feature_host and "True" or "False"
                if feature_host:
                    scsi.attributes["devid"] \
                        = str(get_child_by_name(dev_sxp, "devid"))
                    scsis.append(scsi)
                    break
                else:
                    scsi.attributes["p-dev"] \
                        = get_child_by_name(dev_sxp, "p-dev")
                    scsi.attributes["v-dev"] \
                        = get_child_by_name(dev_sxp, "v-dev")
                    scsis.append(scsi)

        return scsis
Example #48
0
    def extract_scsis(self, scsis_sxp, document):

        scsis = []

        for scsi_sxp in scsis_sxp:
            feature_host = sxp.child_value(scsi_sxp, "feature-host")
            for dev_sxp in sxp.children(scsi_sxp, "dev"):
                scsi = document.createElement("vscsi")

                scsi.attributes["feature-host"] \
                    = feature_host and "True" or "False"
                if feature_host:
                    scsi.attributes["devid"] \
                        = str(get_child_by_name(dev_sxp, "devid"))
                    scsis.append(scsi)
                    break
                else:
                    scsi.attributes["p-dev"] \
                        = get_child_by_name(dev_sxp, "p-dev")
                    scsi.attributes["v-dev"] \
                        = get_child_by_name(dev_sxp, "v-dev")
                    scsis.append(scsi)

        return scsis
Example #49
0
    def getDeviceDetails(self, config):
        """@see DevController.getDeviceDetails"""
        def _get_config_ipaddr(config):
            val = []
            for ipaddr in sxp.children(config, elt='ip'):
                val.append(sxp.child0(ipaddr))
            return val

        script = os.path.join(
            xroot.network_script_dir,
            sxp.child_value(config, 'script', xroot.get_vif_script()))
        typ = sxp.child_value(config, 'type')
        bridge = sxp.child_value(config, 'bridge')
        mac = sxp.child_value(config, 'mac')
        vifname = sxp.child_value(config, 'vifname')
        rate = sxp.child_value(config, 'rate')
        ipaddr = _get_config_ipaddr(config)

        devid = self.allocateDeviceID()

        if not mac:
            mac = randomMAC()

        back = {'script': script, 'mac': mac, 'handle': "%i" % devid}

        if typ == 'ioemu':
            front = {}
            back['type'] = 'ioemu'
        else:
            front = {'handle': "%i" % devid, 'mac': mac}
        if ipaddr:
            back['ip'] = ' '.join(ipaddr)
        if bridge:
            back['bridge'] = bridge
        if vifname:
            back['vifname'] = vifname
        if rate:
            back['rate'] = parseRate(rate)

        return (devid, back, front)
Example #50
0
    @param opts:   options
    @param config: configuration
    @return: domain id
    @rtype:  int
    """

    try:
        dominfo = server.xend.domain.create(config)
    except xmlrpclib.Fault, ex:
        if ex.faultCode == xen.xend.XendClient.ERROR_INVALID_DOMAIN:
            err("the domain '%s' does not exist." % ex.faultString)
        else:
            err("%s" % ex.faultString)

    dom = sxp.child_value(dominfo, 'name')

    try:
        server.xend.domain.waitForDevices(dom)
    except xmlrpclib.Fault, ex:
        server.xend.domain.destroy(dom)
        err("%s" % ex.faultString)
    except:
        server.xend.domain.destroy(dom)
        err("Device creation failed for domain %s" % dom)

    if not opts.vals.paused:
        try:
            server.xend.domain.unpause(dom)
        except:
            server.xend.domain.destroy(dom)
Example #51
0
    def parseDeviceModelArgs(self, imageConfig, deviceConfig):
        dmargs = [ 'cdrom', 'boot', 'fda', 'fdb', 'ne2000', 'audio',
                   'localtime', 'serial', 'stdvga', 'isa', 'vcpus']
        ret = []
        for a in dmargs:
            v = sxp.child_value(imageConfig, a)

            # python doesn't allow '-' in variable names
            if a == 'stdvga': a = 'std-vga'
            if a == 'ne2000': a = 'nic-ne2000'
            if a == 'audio': a = 'enable-audio'

            # Handle booleans gracefully
            if a in ['localtime', 'std-vga', 'isa', 'nic-ne2000', 'enable-audio']:
                if v != None: v = int(v)
                if v: ret.append("-%s" % a)
            else:
                if v:
                    ret.append("-%s" % a)
                    ret.append("%s" % v)
            log.debug("args: %s, val: %s" % (a,v))

        # Handle disk/network related options
        mac = None
        ret = ret + ["-domain-name", "%s" % self.vm.info['name']]
        nics = 0
        for (name, info) in deviceConfig:
            if name == 'vbd':
                uname = sxp.child_value(info, 'uname')
                typedev = sxp.child_value(info, 'dev')
                (_, vbdparam) = string.split(uname, ':', 1)

                if 'file:' in uname and not os.path.isfile(vbdparam):
                   raise VmError('Disk image does not exist: %s' % vbdparam)

                if 'ioemu:' in typedev:
                    (emtype, vbddev) = string.split(typedev, ':', 1)
                else:
                    emtype = 'vbd'
                    vbddev = typedev
                if emtype == 'vbd':
                    continue;
                vbddev_list = ['hda', 'hdb', 'hdc', 'hdd']
                if vbddev not in vbddev_list:
                    raise VmError("hvm: for qemu vbd type=file&dev=hda~hdd")
                ret.append("-%s" % vbddev)
                ret.append("%s" % vbdparam)
            if name == 'vif':
                type = sxp.child_value(info, 'type')
                if type != 'ioemu':
                    continue
                nics += 1
                if mac != None:
                    continue
                mac = sxp.child_value(info, 'mac')
                bridge = sxp.child_value(info, 'bridge')
                if mac == None:
                    mac = randomMAC()
                if bridge == None:
                    bridge = 'xenbr0'
                ret.append("-macaddr")
                ret.append("%s" % mac)
                ret.append("-bridge")
                ret.append("%s" % bridge)
            if name == 'vtpm':
                instance = sxp.child_value(info, 'pref_instance')
                ret.append("-instance")
                ret.append("%s" % instance)
        ret.append("-nics")
        ret.append("%d" % nics)
        return ret
Example #52
0
 def get_cfg(name, default = None):
     return sxp.child_value(imageConfig, name, default)
Example #53
0
            
    def get_domain_name_by_sxp(self, path):
        try:
            sxp_obj = sxp.parse(open(path, 'r'))
            sxp_obj = sxp_obj[0]
        except IOError, e:
            raise XendConfigError("Unable to read file: %s" % path)
        return sxp.child_value(sxp_obj, 'name_label', 'UNKNOWN')
    
    def get_domain_uuid_by_sxp(self, path):
        try:
            sxp_obj = sxp.parse(open(path, 'r'))
            sxp_obj = sxp_obj[0]
        except IOError, e:
            raise XendConfigError("Unable to read file: %s" % path)
        return sxp.child_value(sxp_obj, 'uuid', 'UNKNOWN')
            
    def save_state(self, transient=False):
        vdi_records = dict([(k, v.get_record(transient))
                            for k, v in self.images.items()])
        self.state.save_state('vdi', vdi_records)

    def append_state(self, new_image, transient):
        vdi_records = dict([(new_image.uuid, new_image.get_record(transient))])
        self.state.append_state('vdi', vdi_records)
    
    def destroy_vdi(self, vdi_uuid, del_file=False, transient = False):
#        if vdi_name:
#            for vdi_ref, image in self.images.items():
#                if image.name_label == vdi_name:
#                    vdi_uuid = vdi_ref
Example #54
0
        if ex.faultCode == xen.xend.XendClient.ERROR_INVALID_DOMAIN:
            err("the domain '%s' does not exist." % ex.faultString)
        else:
            err("%s" % ex.faultString)
    except Exception, ex:
        # main.py has good error messages that let the user know what failed.
        # unless the error is a create.py specific thing, it should be handled
        # at main. The purpose of this general-case 'Exception' handler is to
        # clean up create.py specific processes/data but since create.py does
        # not know what to do with the error, it should pass it up.
        import signal
        if vncpid:
            os.kill(vncpid, signal.SIGKILL)
        raise

    dom = sxp.child_value(dominfo, 'name')

    try:
        server.xend.domain.waitForDevices(dom)
    except xmlrpclib.Fault, ex:
        server.xend.domain.destroy(dom)
        err("%s" % ex.faultString)
    except:
        server.xend.domain.destroy(dom)
        err("Device creation failed for domain %s" % dom)

    if not opts.vals.paused:
        try:
            server.xend.domain.unpause(dom)
        except:
            server.xend.domain.destroy(dom)