⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 xenddomain.py

📁 xen虚拟机源代码安装包
💻 PY
📖 第 1 页 / 共 5 页
字号:
#============================================================================# This library is free software; you can redistribute it and/or# modify it under the terms of version 2.1 of the GNU Lesser General Public# License as published by the Free Software Foundation.## This library is distributed in the hope that it will be useful,# but WITHOUT ANY WARRANTY; without even the implied warranty of# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU# Lesser General Public License for more details.## You should have received a copy of the GNU Lesser General Public# License along with this library; if not, write to the Free Software# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA#============================================================================# Copyright (C) 2004, 2005 Mike Wray <mike.wray@hp.com># Copyright (C) 2005 Christian Limpach <Christian.Limpach@cl.cam.ac.uk># Copyright (C) 2005 XenSource Ltd#============================================================================"""Handler for domain operations. Nothing here is persistent (across reboots). Needs to be persistent for one uptime."""import osimport statimport shutilimport socketimport tempfileimport threadingimport xen.lowlevel.xcfrom xen.xend import XendOptions, XendCheckpoint, XendDomainInfofrom xen.xend.PrettyPrint import prettyprintfrom xen.xend import XendConfig, imagefrom xen.xend.XendError import XendError, XendInvalidDomain, VmErrorfrom xen.xend.XendError import VMBadStatefrom xen.xend.XendLogging import logfrom xen.xend.XendAPIConstants import XEN_API_VM_POWER_STATEfrom xen.xend.XendConstants import XS_VMROOTfrom xen.xend.XendConstants import DOM_STATE_HALTED, DOM_STATE_PAUSEDfrom xen.xend.XendConstants import DOM_STATE_RUNNING, DOM_STATE_SUSPENDEDfrom xen.xend.XendConstants import DOM_STATE_SHUTDOWN, DOM_STATE_UNKNOWNfrom xen.xend.XendConstants import DOM_STATE_CRASHED, HVM_PARAM_ACPI_S_STATEfrom xen.xend.XendConstants import TRIGGER_TYPE, TRIGGER_S3RESUMEfrom xen.xend.XendDevices import XendDevicesfrom xen.xend.XendAPIConstants import *from xen.xend.xenstore.xstransact import xstransactfrom xen.xend.xenstore.xswatch import xswatchfrom xen.util import mkdirfrom xen.xend import uuidxc = xen.lowlevel.xc.xc()xoptions = XendOptions.instance() __all__ = [ "XendDomain" ]CACHED_CONFIG_FILE = 'config.sxp'CHECK_POINT_FILE = 'checkpoint.chk'DOM0_UUID = "00000000-0000-0000-0000-000000000000"DOM0_NAME = "Domain-0"DOM0_ID   = 0POWER_STATE_NAMES = dict([(x, XEN_API_VM_POWER_STATE[x])                          for x in [DOM_STATE_HALTED,                                    DOM_STATE_PAUSED,                                    DOM_STATE_RUNNING,                                    DOM_STATE_SUSPENDED,                                    DOM_STATE_SHUTDOWN,                                    DOM_STATE_CRASHED,                                    DOM_STATE_UNKNOWN]])POWER_STATE_ALL = 'all'class XendDomain:    """Index of all domains. Singleton.    @ivar domains: map of domains indexed by domid    @type domains: dict of XendDomainInfo    @ivar managed_domains: domains that are not running and managed by Xend    @type managed_domains: dict of XendDomainInfo indexed by uuid    @ivar domains_lock: lock that must be held when manipulating self.domains    @type domains_lock: threaading.RLock    @ivar _allow_new_domains: Flag to set that allows creating of new domains.    @type _allow_new_domains: boolean    """    def __init__(self):        self.domains = {}        self.managed_domains = {}        self.domains_lock = threading.RLock()        # xen api instance vars        # TODO: nothing uses this at the moment        self._allow_new_domains = True    # This must be called only the once, by instance() below.  It is separate    # from the constructor because XendDomainInfo calls back into this class    # in order to check the uniqueness of domain names.  This means that    # instance() must be able to return a valid instance of this class even    # during this initialisation.    def init(self):        """Singleton initialisation function."""        dom_path = self._managed_path()        mkdir.parents(dom_path, stat.S_IRWXU)        xstransact.Mkdir(XS_VMROOT)        xstransact.SetPermissions(XS_VMROOT, {'dom': DOM0_ID})        self.domains_lock.acquire()        try:            try:                dom0info = [d for d in self._running_domains() \                            if d.get('domid') == DOM0_ID][0]                                dom0info['name'] = DOM0_NAME                dom0 = XendDomainInfo.recreate(dom0info, True)            except IndexError:                raise XendError('Unable to find Domain 0')                        self._setDom0CPUCount()            # This watch registration needs to be before the refresh call, so            # that we're sure that we haven't missed any releases, but inside            # the domains_lock, as we don't want the watch to fire until after            # the refresh call has completed.            xswatch("@introduceDomain", self._on_domains_changed)            xswatch("@releaseDomain",   self._on_domains_changed)            self._init_domains()        finally:            self.domains_lock.release()        def _on_domains_changed(self, _):        """ Callback method when xenstore changes.        Calls refresh which will keep the local cache of domains        in sync.        @rtype: int        @return: 1        """        self.domains_lock.acquire()        try:            self._refresh()        finally:            self.domains_lock.release()        return 1    def _init_domains(self):        """Does the initial scan of managed and active domains to        populate self.domains.        Note: L{XendDomainInfo._checkName} will call back into XendDomain        to make sure domain name is not a duplicate.        """        self.domains_lock.acquire()        try:            running = self._running_domains()            managed = self._managed_domains()            # add all active domains            for dom in running:                if dom['dying'] == 1:                    log.warn('Ignoring dying domain %d from now on' %                             dom['domid'])                    continue                if dom['domid'] != DOM0_ID:                    try:                        new_dom = XendDomainInfo.recreate(dom, False)                    except Exception:                        log.exception("Failed to create reference to running "                                      "domain id: %d" % dom['domid'])            image.cleanup_stale_sentinel_fifos()            # add all managed domains as dormant domains.            for dom in managed:                dom_uuid = dom.get('uuid')                if not dom_uuid:                    continue                                dom_name = dom.get('name_label', 'Domain-%s' % dom_uuid)                try:                    running_dom = self.domain_lookup_nr(dom_name)                    if not running_dom:                        # instantiate domain if not started.                        new_dom = XendDomainInfo.createDormant(dom)                        self._managed_domain_register(new_dom)                    else:                        self._managed_domain_register(running_dom)                        for key in XendConfig.XENAPI_CFG_TYPES.keys():                            if key not in XendConfig.LEGACY_XENSTORE_VM_PARAMS and \                                   key in dom:                                running_dom.info[key] = dom[key]                except Exception:                    log.exception("Failed to create reference to managed "                                  "domain: %s" % dom_name)        finally:            self.domains_lock.release()    # -----------------------------------------------------------------    # Getting managed domains storage path names    def _managed_path(self, domuuid = None):        """Returns the path of the directory where managed domain        information is stored.        @keyword domuuid: If not None, will return the path to the domain                          otherwise, will return the path containing                          the directories which represent each domain.        @type: None or String.        @rtype: String        @return: Path.        """        dom_path = xoptions.get_xend_domains_path()        if domuuid:            dom_path = os.path.join(dom_path, domuuid)        return dom_path    def _managed_config_path(self, domuuid):        """Returns the path to the configuration file of a managed domain.        @param domname: Domain uuid        @type domname: String        @rtype: String        @return: path to config file.        """        return os.path.join(self._managed_path(domuuid), CACHED_CONFIG_FILE)    def _managed_check_point_path(self, domuuid):        """Returns absolute path to check point file for managed domain.                @param domuuid: Name of managed domain        @type domname: String        @rtype: String        @return: Path        """        return os.path.join(self._managed_path(domuuid), CHECK_POINT_FILE)    def _managed_config_remove(self, domuuid):        """Removes a domain configuration from managed list        @param domuuid: Name of managed domain        @type domname: String        @raise XendError: fails to remove the domain.        """        config_path = self._managed_path(domuuid)        try:            if os.path.exists(config_path) and os.path.isdir(config_path):                shutil.rmtree(config_path)        except IOError:            log.exception('managed_config_remove failed removing conf')            raise XendError("Unable to remove managed configuration"                            " for domain: %s" % domuuid)                def managed_config_save(self, dominfo):        """Save a domain's configuration to disk                @param domninfo: Managed domain to save.        @type dominfo: XendDomainInfo        @raise XendError: fails to save configuration.        @rtype: None        """        if not self.is_domain_managed(dominfo):            return # refuse to save configuration this domain isn't managed                if dominfo:            domains_dir = self._managed_path()            dom_uuid = dominfo.get_uuid()                        domain_config_dir = self._managed_path(dom_uuid)            def make_or_raise(path):                try:                    mkdir.parents(path, stat.S_IRWXU)                except:                    log.exception("%s could not be created." % path)                    raise XendError("%s could not be created." % path)            make_or_raise(domains_dir)            make_or_raise(domain_config_dir)            try:                fd, fn = tempfile.mkstemp()                f = os.fdopen(fd, 'w+b')                try:                    prettyprint(dominfo.sxpr(legacy_only = False), f,                                width = 78)                finally:                    f.close()                                    try:                    shutil.move(fn, self._managed_config_path(dom_uuid))                except:                    log.exception("Renaming %s to %s", fn,                                  self._managed_config_path(dom_uuid))                    os.remove(fn)            except:                log.exception("Error occurred saving configuration file " +                              "to %s" % domain_config_dir)                raise XendError("Failed to save configuration file to: %s" %                                domain_config_dir)        else:            log.warn("Trying to save configuration for invalid domain")    def _managed_domains(self):        """ Returns list of domains that are managed.                Expects to be protected by domains_lock.        @rtype: list of XendConfig        @return: List of domain configurations that are managed.        """        dom_path = self._managed_path()        dom_uuids = os.listdir(dom_path)        doms = []        for dom_uuid in dom_uuids:            try:                cfg_file = self._managed_config_path(dom_uuid)                cfg = XendConfig.XendConfig(filename = cfg_file)                if cfg.get('uuid') != dom_uuid:                    # something is wrong with the SXP                    log.error("UUID mismatch in stored configuration: %s" %                              cfg_file)                    continue                doms.append(cfg)            except Exception:                log.exception('Unable to open or parse config.sxp: %s' % \                              cfg_file)        return doms    def _managed_domain_unregister(self, dom):        try:

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -