示例#1
0
    def OpenSession(self):
        session = None

        if not self.masterConnectionBroken:
            try:
                # Try the local Unix domain socket first
                session = XenAPI.xapi_local()
                session.login_with_password('root', '', '', 'XSConsole')
            except socket.timeout:
                session = None
                self.masterConnectionBroken = True
                self.error = 'The master connection has timed out.'
            except Exception, e:
                session = None
                self.error = e

            if session is None and self.testingHost is not None:
                # Local session couldn't connect, so try remote.
                session = XenAPI.Session("https://" + self.testingHost)
                try:
                    session.login_with_password('root', self.defaultPassword,
                                                '', 'XSConsole')

                except XenAPI.Failure, e:
                    if e.details[
                            0] != 'HOST_IS_SLAVE':  # Ignore slave errors when testing
                        session = None
                        self.error = e
                except socket.timeout:
                    session = None
                    self.masterConnectionBroken = True
                    self.error = 'The master connection has timed out.'
示例#2
0
    def connect(cls, module, disconnect_atexit=True):
        """Establishes XAPI connection and returns session reference.

        If no existing session is available, establishes a new one
        and returns it, else returns existing one.

        Args:
            module: Reference to Ansible module object.
            disconnect_atexit (bool): Controls if method should
                register atexit handler to disconnect from XenServer
                on module exit (default: True).

        Returns:
            XAPI session reference.
        """
        if cls._xapi_session is not None:
            return cls._xapi_session

        hostname = module.params['hostname']
        username = module.params['username']
        password = module.params['password']
        ignore_ssl = not module.params['validate_certs']

        if hostname == 'localhost':
            cls._xapi_session = XenAPI.xapi_local()
            username = ''
            password = ''
        else:
            # If scheme is not specified we default to http:// because https://
            # is problematic in most setups.
            if not hostname.startswith("http://") and not hostname.startswith(
                    "https://"):
                hostname = "http://%s" % hostname

            try:
                # ignore_ssl is supported in XenAPI.py 7.2 onward but there
                # is no way to tell which version we are using. TypeError will
                # be raised if ignore_ssl is not supported. Additionally,
                # ignore_ssl requires Python 2.7.9 or newer.
                cls._xapi_session = XenAPI.Session(hostname,
                                                   ignore_ssl=ignore_ssl)
            except TypeError:
                # Try without ignore_ssl.
                cls._xapi_session = XenAPI.Session(hostname)

            if not password:
                password = ''

        try:
            cls._xapi_session.login_with_password(username, password,
                                                  ANSIBLE_VERSION, 'Ansible')
        except XenAPI.Failure as f:
            module.fail_json(
                msg="Unable to log on to XenServer at %s as %s: %s" %
                (hostname, username, f.details))

        # Disabling atexit should be used in special cases only.
        if disconnect_atexit:
            atexit.register(cls._xapi_session.logout)
        return cls._xapi_session
示例#3
0
def get_api_session(conf):
    if not api:
        raise ImportError(_('XenAPI not installed'))

    url = conf.xenapi.connection_url
    username = conf.xenapi.connection_username
    password = conf.xenapi.connection_password
    if not url or password is None:
        raise XenapiException(
            _('Must specify connection_url, and '
              'connection_password to use'))

    try:
        session = (api.xapi_local()
                   if url == 'unix://local' else api.Session(url))
        session.login_with_password(username, password)
    except api.Failure as e:
        if e.details[0] == 'HOST_IS_SLAVE':
            master = e.details[1]
            url = swap_xapi_host(url, master)
            try:
                session = api.Session(url)
                session.login_with_password(username, password)
            except api.Failure as es:
                raise XenapiException(
                    _('Could not connect slave host: %s ') % es.details[0])
        else:
            msg = _("Could not connect to XenAPI: %s") % e.details[0]
            raise XenapiException(msg)
    return session
示例#4
0
class XenServerAPI:
    def __init__(self, cfg, host, user, passwd):
        unqdn = '.'.join(mothership.get_unqdn(cfg, host))
        #print 'Original: %s' % unqdn
        self.session = XenAPI.Session('https://%s:443' % unqdn)
        try:
            self.session.xenapi.login_with_password(user, passwd)
        except XenAPI.Failure, e:
            # If slave host from pool chosed, contact master
            exec 'err=%s' % str(e)
            #print 'Error: %s' % err[1]
            self.session = XenAPI.Session('https://%s:443' % err[1])
            self.session.xenapi.login_with_password(user, passwd)
        except socket.error, e:
            try:
                # Try specified host if unqdn fails
                #print 'Host: %s' % host
                self.session = XenAPI.Session('https://%s:443' % host)
                self.session.xenapi.login_with_password(user, passwd)
            except socket.error, e:
                # Try mgmt if connection refused
                #print 'Mgmt: %s' % unqdn.replace('prod','mgmt')
                self.session = XenAPI.Session('https://%s:443' % \
                    unqdn.replace('prod','mgmt'))
                self.session.xenapi.login_with_password(user, passwd)
示例#5
0
    def connect(cls, disconnect_atexit=True, hostname, username, password):
        if cls._xapi_session is not None:
            return cls._xapi_session

        ignore_ssl = True

        if hostname == 'localhost':
            cls._xapi_session = XenAPI.xapi_local()
            username = ''
            password = ''
        else:
            cls._xapi_session = XenAPI.Session("http://%s/" % hostname,
                                               ignore_ssl=ignore_ssl)

            if not password:
                password = ''

        try:
            cls._xapi_session.login_with_password(username, password, '1.0',
                                                  'xenserver_guest.py')
        except XenAPI.Failure as f:
            print("Unable to log on to XenServer at %s as %s: %s" %
                  (hostname, username, f.details))

        return cls._xapi_session
 def __init__(self, url, port, username, password):
     errorMsg = "An error has occured during Xen connection. Script aborting..."
     url = url_abs_path(url)
     logger.info("Establishing connexion to xen server " + username + "@" +
                 url + ":" + str(port) + "...")
     try:
         session = XenAPI.Session(url + ":" + str(port))
         session.xenapi.login_with_password(username, password)
     except Exception as e:
         if hasattr(e, "details") and e.details[0] == "HOST_IS_SLAVE":
             # Redirect to cluster master
             url = urlparse(url).scheme + "://" + e.details[1]
             try:
                 session = XenAPI.Session(url)
                 session.login_with_password(username, password)
             except Exception as e:
                 logger.error(e)
                 logger.error(errorMsg)
                 raise NameError(errorMsg)
         else:
             logger.error(e)
             logger.error(errorMsg)
             raise NameError(errorMsg)
     self.url = url
     self.port = port
     self.session = session
     self.username = username
     self.password = password
     logger.info("XEN connection OK!")
示例#7
0
    def Connect(self):
        ''' This is called at the startup of Collectd '''
        # Called at startup

        if self.host is None:
            self.hostinfo['session'] = XenAPI.xapi_local(
            )  #no __nonzero__, can not use if/not for bool test
            self.url = "http://localhost"
        else:
            self.url = "http://" + str(self.host)
            self.hostinfo['session'] = XenAPI.Session(self.url)
        self._LogVerbose("Conntct to url: %s" % (self.url))
        self.hostinfo['rrdupdates'] = GetRRDUdpates()
        self.hostinfo['session'].xenapi.login_with_password(
            self.user, self.passwd)
        # host name, uuid translation
        host_ref = self.hostinfo['session'].xenapi.host.get_all()[0]
        uuid = self.hostinfo['session'].xenapi.host.get_uuid(host_ref)
        server_name = self.hostinfo['session'].xenapi.host.get_hostname(
            host_ref)
        self.uuid_name_map[uuid] = server_name
        self.hostname = server_name
        # VM name, uuid translation
        vm_refs_list = self.hostinfo['session'].xenapi.VM.get_all()
        for vm_ref in vm_refs_list:
            vm_uuid = self.hostinfo['session'].xenapi.VM.get_uuid(vm_ref)
            vm_name = self.hostinfo['session'].xenapi.VM.get_name_label(vm_ref)
            if self.hostinfo['session'].xenapi.VM.get_is_control_domain(
                    vm_ref):
                self.uuid_name_map[vm_uuid] = server_name + "_control-domain"
            else:
                self.uuid_name_map[vm_uuid] = vm_name
示例#8
0
 def make_session(self):
     try:
         # Making XenServer API Session
         session = XenAPI.Session(self.xs_url)
         session.xenapi.login_with_password(self.xs_username, self.xs_password)
     except XenAPI.Failure, e:
         if e.details[0] == 'HOST_IS_SLAVE':
             session = XenAPI.Session('http://' + e.details[1])
             session.login_with_password(self.xs_username, self.xs_password)
             sys.stdout.write(self.xs_host+" is a slave host. Trying with: "+ e.details[1]+"\n")
示例#9
0
def get_session(server, username, password):

    # creating a session with server
    if (server[:6] == 'http://' or server[:7] == 'https://'):
        session = XenAPI.Session(server)
    else:
        session = XenAPI.Session('http://' + server)

    session.xenapi.login_with_password(username, password)

    return session
def getHostsVms(hostname, username, password, hosts, vms):
    url = 'https://%s' % hostname
    session = XenAPI.Session(url)
    try:
        session.login_with_password(username, password)
    except XenAPI.Failure, e:
        if (e.details[0] == 'HOST_IS_SLAVE'):
            session = XenAPI.Session("https://" + e.details[1])
            session.login_with_password(username, password)
        else:
            raise
示例#11
0
 def __init__(self, cfg, host, user, passwd):
     unqdn = '.'.join(mothership.get_unqdn(cfg, host))
     #print 'Original: %s' % unqdn
     self.session = XenAPI.Session('https://%s:443' % unqdn)
     try:
         self.session.xenapi.login_with_password(user, passwd)
     except XenAPI.Failure, e:
         # If slave host from pool chosed, contact master
         exec 'err=%s' % str(e)
         #print 'Error: %s' % err[1]
         self.session = XenAPI.Session('https://%s:443' % err[1])
         self.session.xenapi.login_with_password(user, passwd)
示例#12
0
def _get_session():
    '''
    Get a connection to the XenServer host
    '''
    api_version = '1.0'
    originator = 'salt_cloud_{}_driver'.format(__virtualname__)
    url = config.get_cloud_config_value(
        'url',
        get_configured_provider(),
        __opts__,
        search_global=False
    )
    user = config.get_cloud_config_value(
        'user',
        get_configured_provider(),
        __opts__,
        search_global=False
    )
    password = config.get_cloud_config_value(
        'password',
        get_configured_provider(),
        __opts__,
        search_global=False
    )
    ignore_ssl = config.get_cloud_config_value(
        'ignore_ssl',
        get_configured_provider(),
        __opts__,
        default=False,
        search_global=False
    )
    try:
        session = XenAPI.Session(url, ignore_ssl=ignore_ssl)
        log.debug(
            'url: %s user: %s password: %s, originator: %s',
            url, user, 'XXX-pw-redacted-XXX', originator
        )
        session.xenapi.login_with_password(
            user, password, api_version, originator)
    except XenAPI.Failure as ex:
        pool_master_addr = six.text_type(ex.__dict__['details'][1])
        slash_parts = url.split('/')
        new_url = '/'.join(slash_parts[:2]) + '/' + pool_master_addr
        session = XenAPI.Session(new_url)
        log.debug(
            'session is -> url: %s user: %s password: %s, originator:%s',
            new_url, user, 'XXX-pw-redacted-XXX', originator
        )
        session.xenapi.login_with_password(
            user, password, api_version, originator)
    return session
示例#13
0
文件: xen.py 项目: zxstar/salt
def _get_session():
    """
    Get a connection to the XenServer host
    """
    api_version = "1.0"
    originator = "salt_cloud_{}_driver".format(__virtualname__)
    url = config.get_cloud_config_value("url",
                                        get_configured_provider(),
                                        __opts__,
                                        search_global=False)
    user = config.get_cloud_config_value("user",
                                         get_configured_provider(),
                                         __opts__,
                                         search_global=False)
    password = config.get_cloud_config_value("password",
                                             get_configured_provider(),
                                             __opts__,
                                             search_global=False)
    ignore_ssl = config.get_cloud_config_value(
        "ignore_ssl",
        get_configured_provider(),
        __opts__,
        default=False,
        search_global=False,
    )
    try:
        session = XenAPI.Session(url, ignore_ssl=ignore_ssl)
        log.debug(
            "url: %s user: %s password: %s, originator: %s",
            url,
            user,
            "XXX-pw-redacted-XXX",
            originator,
        )
        session.xenapi.login_with_password(user, password, api_version,
                                           originator)
    except XenAPI.Failure as ex:
        pool_master_addr = six.text_type(ex.__dict__["details"][1])
        slash_parts = url.split("/")
        new_url = "/".join(slash_parts[:2]) + "/" + pool_master_addr
        session = XenAPI.Session(new_url)
        log.debug(
            "session is -> url: %s user: %s password: %s, originator:%s",
            new_url,
            user,
            "XXX-pw-redacted-XXX",
            originator,
        )
        session.xenapi.login_with_password(user, password, api_version,
                                           originator)
    return session
示例#14
0
def con_poolmaster(xs, user, password):
    try:
        s = XenAPI.Session("http://%s" % xs)
        s.xenapi.login_with_password(user, password)
        return s
    except XenAPI.Failure, msg:
        if msg.details[0] == "HOST_IS_SLAVE":
            host = msg.details[1]
            s = XenAPI.Session("http://%s" % host)
            s.xenapi.login_with_password(user, password)
            return s
        else:
            print "Error: pool con:", xs, sys.exc_info()[0]
            pass
def getHostsVms(xenmaster, username, password, xenhosts, xenvms, xensrs):
    """
    function getHostsVms get all available virtual machines in a xencluster
    """

    url = 'https://%s/' % xenmaster
    session = XenAPI.Session(url, ignore_ssl=True)
    try:
        session.login_with_password(username, password, "1.0", "citrix.py")
    except XenAPI.Failure, e:
        if (e.details[0] == 'HOST_IS_SLAVE'):
            session = XenAPI.Session("https://" + e.details[1])
            session.login_with_password(username, password)
        else:
            raise
示例#16
0
def main():
   
	try:
                myopts, args = getopt.getopt(sys.argv[1:], "huncw:",["help", "follow", "names", "uuid"])
	except getopt.GetoptError:
                print "Unknown options"
                systax()
                sys.exit(1)

        minspace = 4
        mode = "name"
        follow = False

        for opt, arg in myopts:
                if opt in ("-h", "--help"):
                        syntax()
                        sys.exit(1)
                elif opt in ("-f", "--follow"):
                        follow = True
                elif opt in ("-n", "--name"):
                        mode = "name"
                elif opt in ("-u", "--uuid"):
                        mode = "uuid"


        session = XenAPI.xapi_local()

        session.xenapi.login_with_password("", "")


	hosts = gethosts(session)
	hostscpus = getcpus(session, hosts)
	gethostcpus(session, hostscpus)
示例#17
0
文件: SR.py 项目: euanh/sm
    def __init__(self, srcmd, sr_uuid):
        """Base class initializer. All subclasses should call SR.__init__ 
           in their own
        initializers.

        Arguments:
          srcmd: SRCommand instance, contains parsed arguments
        """
        try:
            self.srcmd = srcmd
            self.dconf = srcmd.dconf
            if srcmd.params.has_key('session_ref'):
                self.session_ref = srcmd.params['session_ref']
                self.session = XenAPI.xapi_local()
                self.session._session = self.session_ref
                if 'subtask_of' in self.srcmd.params:
                    self.session.transport.add_extra_header('Subtask-of', self.srcmd.params['subtask_of'])
            else:
                self.session = None

            if 'host_ref' not in self.srcmd.params:
                self.host_ref = ""
            else:
                self.host_ref = self.srcmd.params['host_ref']

            if 'sr_ref' in self.srcmd.params:
                self.sr_ref = self.srcmd.params['sr_ref']

        except Exception, e:
            raise e
            raise xs_errors.XenError('SRBadXML')
示例#18
0
文件: SR.py 项目: ESDS/sm
    def __init__(self, srcmd, sr_uuid):
        """Base class initializer. All subclasses should call SR.__init__ 
           in their own
        initializers.

        Arguments:
          srcmd: SRCommand instance, contains parsed arguments
        """
        try:
            self.srcmd = srcmd
            self.dconf = srcmd.dconf
            if srcmd.params.has_key('session_ref'):
                self.session_ref = srcmd.params['session_ref']
                self.session = XenAPI.xapi_local()
                self.session._session = self.session_ref
                if 'subtask_of' in self.srcmd.params:
                    self.session.transport.add_extra_header('Subtask-of', self.srcmd.params['subtask_of'])
            else:
                self.session = None

            if 'host_ref' not in self.srcmd.params:
                self.host_ref = ""
            else:
                self.host_ref = self.srcmd.params['host_ref']

            self.sr_ref = self.srcmd.params.get('sr_ref')

	    if 'device_config' in self.srcmd.params:
                if self.dconf.get("SRmaster") == "true":
                    os.environ['LVM_SYSTEM_DIR'] = MASTER_LVM_CONF

        except Exception, e:
            raise e
            raise xs_errors.XenError('SRBadXML')
示例#19
0
def main():
	try:
		myopts, args = getopt.getopt(sys.argv[1:], "huncw:",["help", "uuid", "name", "csv", "wspace"])
	except getopt.GetoptError:
		print "Unknown options"
		syntax()
		sys.exit(1) 
	minspace = 4
	CSV = False
	mode = "name"
	for opt, arg in myopts:
		if opt in ("-h", "--help"):
			syntax()
			sys.exit(1)
		elif opt in ("-u", "--uuid"):
			mode = "uuid"			
		elif opt in ("-n", "--name"):
			mode = "name"
		elif opt in ("-c", "--csv"):
			CSV = True 
		elif opt in ("-w", "--wspace"):
			minspace = int(arg)
			
	session = XenAPI.xapi_local()
	
	session.xenapi.login_with_password("", "")
	
	hosts = gethostdata(session)
	
	headings = defineheadings(mode)
	
	print formatdarray(hosts, headings, CSV, minspace)
	
	session.xenapi.session.logout()
示例#20
0
def get_xenapi_session():
    try:
        session = XenAPI.xapi_local()
        session.xenapi.login_with_password('', '')
        return session
    except XenAPI.Failure:
        sys.exit(1)
def call_plugin_on_host(dbg, host_name, plugin_name, plugin_function, args):
    log.debug("%s: calling plugin '%s' function '%s' with args %s on %s" % (dbg, plugin_name, plugin_function, args, host_name))
    session = XenAPI.xapi_local()
    try:
        session.xenapi.login_with_password('root', '')
    except:
        # ToDo: We ought to raise something else
        raise
    try:
        for host_ref in get_online_host_refs(dbg, session):
            log.debug("%s: host_ref %s - host_name %s)" % (dbg, session.xenapi.host.get_name_label(host_ref), host_name))
            if session.xenapi.host.get_name_label(host_ref) == host_name:
                log.debug("%s: calling plugin '%s' function '%s' with args %s on host %s - %s)" % (dbg, plugin_name, plugin_function, args, host_ref, host_name))
                resulttext = session.xenapi.host.call_plugin(
                    host_ref,
                    plugin_name,
                    plugin_function,
                    args)
                log.debug("%s: resulttext = %s" % (dbg, resulttext))
                if resulttext != "True":
                    # ToDo: We ought to raise something else
                    raise xapi.storage.api.volume.Unimplemented(
                        "Failed to get hostref %s to run %s(%s)" %
                        (host_ref, plugin_name, plugin_function, args))
    except:
        # ToDo: We ought to raise something else
        raise
    finally:
        session.xenapi.session.logout()
示例#22
0
文件: lcache.py 项目: MarkSymsCtx/sm
    def from_cli(cls):
        import XenAPI

        session = XenAPI.xapi_local()
        session.xenapi.login_with_password('root', '', '', 'SM')

        return cls.from_session(session)
示例#23
0
    def login(self, switchToMaster=False):
        try:
            self._url = self._protocol + self._host + ':' + self._port
            # On python 2.7.9, HTTPS is verified by default,
            if self._useSSL and self._verifySSL is False:
                context = ssl.SSLContext(
                    ssl.PROTOCOL_SSLv23)  # @UndefinedVariable
                context.verify_mode = ssl.CERT_NONE
                transport = xmlrpclib.SafeTransport(context=context)
            else:
                transport = None

            self._session = XenAPI.Session(self._url, transport=transport)
            self._session.xenapi.login_with_password(self._username,
                                                     self._password)
            self._loggedIn = True
            self._apiVersion = self._session.API_version
            self._poolName = unicode(self.getPoolName())
        except XenAPI.Failure as e:  # XenAPI.Failure: ['HOST_IS_SLAVE', '172.27.0.29'] indicates that this host is an slave of 172.27.0.29, connect to it...
            if switchToMaster and e.details[0] == 'HOST_IS_SLAVE':
                logger.info(
                    '{0} is an Slave, connecting to master at {1} cause switchToMaster is True'
                    .format(self._host, e.details[1]))
                self._host = e.details[1]
                self.login()
            else:
                raise XenFailure(e.details)
示例#24
0
def get_api_session(conf):
    if not api:
        raise ImportError(_('XenAPI not installed'))

    url = conf.xenapi.connection_url
    username = conf.xenapi.connection_username
    password = conf.xenapi.connection_password
    if not url or password is None:
        raise XenapiException(_('Must specify connection_url, and '
                                'connection_password to use'))

    try:
        session = (api.xapi_local() if url == 'unix://local'
                   else api.Session(url))
        session.login_with_password(username, password)
    except api.Failure as e:
        if e.details[0] == 'HOST_IS_SLAVE':
            master = e.details[1]
            url = swap_xapi_host(url, master)
            try:
                session = api.Session(url)
                session.login_with_password(username, password)
            except api.Failure as es:
                raise XenapiException(_('Could not connect slave host: %s ') %
                                      es.details[0])
        else:
            msg = _("Could not connect to XenAPI: %s") % e.details[0]
            raise XenapiException(msg)
    return session
示例#25
0
def main(url, username, password):
    while True:
        session = XenAPI.Session(url)
        session.login_with_password(username, password)
        print_metrics(session.xenapi)
        session.logout()
        time.sleep(5)
示例#26
0
    def OpenSession(self):
        session = None

        if not self.masterConnectionBroken:
            try:
                # Try the local Unix domain socket first
                session = XenAPI.xapi_local()
                session.login_with_password('root','')
            except socket.timeout:
                session = None
                self.masterConnectionBroken = True
                self.error = 'The master connection has timed out.'
            except Exception,  e:
                session = None
                self.error = e
                
            if session is None and self.testingHost is not None:
                # Local session couldn't connect, so try remote.
                session = XenAPI.Session("https://"+self.testingHost)
                try:
                    session.login_with_password('root', self.defaultPassword)
                    
                except XenAPI.Failure, e:
                    if e.details[0] != 'HOST_IS_SLAVE': # Ignore slave errors when testing
                        session = None
                        self.error = e
                except socket.timeout:
                    session = None
                    self.masterConnectionBroken = True
                    self.error = 'The master connection has timed out.'
示例#27
0
 def get_connection(self):
     '''get the session from the master of the pool'''
     try:
         self.session = XenAPI.Session(self._url)
         self.session.xenapi.login_with_password(self._user, self._pwd)
     except XenAPI.Failure, e:
         raise ManagerError, e
示例#28
0
def mount(dbg, dev_path):
    # Ensure corosync+dlm are configured and running
    inventory = xcp.environ.readInventory()
    session = XenAPI.xapi_local()
    session.xenapi.login_with_password("root", "")
    this_host = session.xenapi.host.get_by_uuid(
        inventory.get("INSTALLATION_UUID"))
    log.debug("%s: setting up corosync and dlm on this host" % (dbg))
    session.xenapi.host.call_plugin(
        this_host, "gfs2setup", "gfs2Setup", {})

    mnt_path = os.path.abspath(mountpoint_root + dev_path)
    try:
        os.makedirs(mnt_path)
    except OSError as exc:
        if exc.errno == errno.EEXIST and os.path.isdir(mnt_path):
            pass
        else:
            raise
    if not os.path.ismount(mnt_path):
        cmd = ["/usr/sbin/modprobe", "gfs2"]
        call(dbg, cmd)

        cmd = ["/usr/bin/mount", "-t", "gfs2", "-o",
               "noatime,nodiratime", dev_path, mnt_path]
        call(dbg, cmd)
    return mnt_path
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-ip', '--host-ip', dest='host')
    parser.add_argument('-u', '--username', dest='username')
    parser.add_argument('-p', '--password', dest='password')
    parser.add_argument('-v', '--vdi-uuid', dest='vdi_uuid')
    parser.add_argument('-f', '--filename', dest='path')
    parser.add_argument('--as-new-vdi',
                        dest='new_vdi',
                        action='store_const',
                        const=True,
                        default=False,
                        help='Create a new VDI for the import')
    args = parser.parse_args()

    session = XenAPI.Session("https://" + args.host, ignore_ssl=True)
    session.login_with_password(args.username, args.password, "0.1",
                                "CBT example")

    try:
        vdi_uuid = args.vdi_uuid
        if args.new_vdi:
            vdi_ref = session.xenapi.VDI.get_by_uuid(args.vdi_uuid)
            size = session.xenapi.VDI.get_virtual_size(vdi_ref)
            sr_ref = session.xenapi.VDI.get_SR(vdi_ref)
            vdi_uuid = create_new_vdi(session, sr_ref, size)

        import_vdi(args.host, session._session, vdi_uuid, 'raw', args.path)
        print vdi_uuid
    finally:
        session.xenapi.session.logout(session)
示例#30
0
def dispatch(fn_table):
    if len(sys.argv) <> 2:
        exception_str = "Incorrect number of commandline arguments: %s" % len(
            sys.argv)
        raise Exception(exception_str)

    params, methodname = xmlrpclib.loads(sys.argv[1])
    print "params: %s, methodname: %s" % (params, methodname)
    session_id = params[0]
    args = params[1]
    if methodname in fn_table:
        x = XenAPI.xapi_local()
        x._session = session_id
        try:
            result = fn_table[methodname](x, args)
            print success_message(result)
        except SystemExit:
            # SystemExit should not be caught, as it is handled elsewhere in the plugin system.
            raise
        except Failure, e:
            print failure_message(e.params)
        except Exception, e:
            print failure_message([
                'XENAPI_PLUGIN_FAILURE', methodname, e.__class__.__name__,
                str(e)
            ])
示例#31
0
文件: lcache.py 项目: xcp-ng/sm
    def from_cli(cls):
        import XenAPI

        session = XenAPI.xapi_local()
        session.xenapi.login_with_password('root', '', '', 'SM')

        return cls.from_session(session)
示例#32
0
def update_rounds(vm, current_round, rounds_required):
    session = XenAPI.xapi_local()
    session.xenapi.login_with_password("", "")
    try:
        vm_ref = session.xenapi.VM.get_by_uuid(vm)

        # remove the install-round field: ignore errors as the key might
        # not be there and this is OK (default value is 1).
        session.xenapi.VM.remove_from_other_config(vm_ref, "install-round")

        # write a new value in for install-round if appropriate:
        if current_round != rounds_required:
            session.xenapi.VM.add_to_other_config(vm_ref, "install-round",
                                                  str(current_round + 1))
        else:
            # All rounds complete. Remove install-distro key from other_config param.
            # If we don't do this and we later perform a "convert to template" on this VM,
            # the GUI will infer from the presence of this key that it must query the user
            # for the install media location.  This is unecessary since the template already
            # contains a fully installed disk image, that only needs to be copied.
            session.xenapi.VM.remove_from_other_config(vm_ref,
                                                       "install-distro")

    finally:
        session.logout()
示例#33
0
def host_join(self, arg_dict):
    """Join a remote host into a pool.

    The pool's master is the host where the plugin is called from. The
    following constraints apply:

    - The host must have no VMs running, except nova-compute, which
      will be shut down (and restarted upon pool-join) automatically,
    - The host must have no shared storage currently set up,
    - The host must have the same license of the master,
    - The host must have the same supplemental packs as the master.
    """
    session = XenAPI.Session(arg_dict.get("url"))
    session.login_with_password(arg_dict.get("user"),
                                arg_dict.get("password"))
    compute_ref = session.xenapi.VM.get_by_uuid(arg_dict.get('compute_uuid'))
    session.xenapi.VM.clean_shutdown(compute_ref)
    try:
        if arg_dict.get("force"):
            session.xenapi.pool.join(arg_dict.get("master_addr"),
                                     arg_dict.get("master_user"),
                                     arg_dict.get("master_pass"))
        else:
            session.xenapi.pool.join_force(arg_dict.get("master_addr"),
                                           arg_dict.get("master_user"),
                                           arg_dict.get("master_pass"))
    finally:
        _resume_compute(session, compute_ref, arg_dict.get("compute_uuid"))
示例#34
0
def main():
    """Main loop."""
    options, args = parse_options()
    verbose = options.verbose
    command = args[0]

    if FLAGS.zombie_instance_updated_at_window < FLAGS.resize_confirm_window:
        raise Exception("`zombie_instance_updated_at_window` has to be longer"
                        " than `resize_confirm_window`.")

    session = XenAPI.Session(FLAGS.xenapi_connection_url)
    session.xenapi.login_with_password(FLAGS.xenapi_connection_username,
                                       FLAGS.xenapi_connection_password)

    if command == "list-vdis":
        if verbose:
            print "Connected VDIs:\n"
        orphaned_vdi_uuids = find_orphaned_vdi_uuids(session, verbose=verbose)
        if verbose:
            print "\nOrphaned VDIs:\n"
        list_orphaned_vdis(orphaned_vdi_uuids, verbose=verbose)
    elif command == "clean-vdis":
        orphaned_vdi_uuids = find_orphaned_vdi_uuids(session, verbose=verbose)
        clean_orphaned_vdis(session, orphaned_vdi_uuids, verbose=verbose)
    elif command == "list-instances":
        orphaned_instances = find_orphaned_instances(session, verbose=verbose)
        list_orphaned_instances(orphaned_instances, verbose=verbose)
    elif command == "clean-instances":
        orphaned_instances = find_orphaned_instances(session, verbose=verbose)
        clean_orphaned_instances(session, orphaned_instances, verbose=verbose)
    elif command == "test":
        doctest.testmod()
    else:
        print "Unknown command '%s'" % command
        sys.exit(1)
示例#35
0
def canonicaliseOtherConfig(vm_uuid):
    session = XenAPI.xapi_local()
    session.login_with_password("", "")
    try:
        vm = session.xenapi.VM.get_by_uuid(vm_uuid)
        other_config = session.xenapi.VM.get_other_config(vm)
    finally:
        session.logout()

    def collect(d, k, default = None):
        if d.has_key(k):
            return d[k]
        else:
            return default
    rc = { 'install-repository': collect(other_config, 'install-repository'),
           'install-vnc':        collect(other_config, 'install-vnc', "false") in ["1", "true"],
           'install-vncpasswd':  collect(other_config, 'install-vncpasswd'),
           'install-distro':     collect(other_config, 'install-distro', 'rhlike'), 
           'install-round':      collect(other_config, 'install-round', '1'),
           'install-arch':       collect(other_config, 'install-arch', 'i386'),
           'install-kernel':     collect(other_config, 'install-kernel', None),
           'install-ramdisk':    collect(other_config, 'install-ramdisk', None),
           'install-proxy':      collect(other_config, 'install-proxy', None),
           'debian-release':     collect(other_config, 'debian-release') }
    return rc
    def __init__(self, session_ref=None, cache_file=None):
        if session_ref and cache_file:
            raise Error("can't specify session reference and cache file")
        if cache_file == None:
            import XenAPI
            session = XenAPI.xapi_local()

            if not session_ref:
                log("No session ref given on command line, logging in.")
                session.xenapi.login_with_password("root", "")
            else:
                session._session = session_ref

            try:

                inventory = self.__read_xensource_inventory()
                assert(inventory.has_key('INSTALLATION_UUID'))
                log("host uuid is %s" % inventory['INSTALLATION_UUID'])

                host = session.xenapi.host.get_by_uuid(inventory['INSTALLATION_UUID'])

                self.__get_pif_records_from_xapi(session, host)

                try:
                    self.__get_tunnel_records_from_xapi(session)
                except XenAPI.Failure, e:
                    error,details = e.details
                    if error == "MESSAGE_METHOD_UNKNOWN" and details == "tunnel.get_all":
                        pass

                self.__get_vlan_records_from_xapi(session)
                self.__get_bond_records_from_xapi(session)
                self.__get_network_records_from_xapi(session)
            finally:
示例#37
0
 def vm_info(self):
     session = XenAPI.Session(XEN_URL)
     session.xenapi.login_with_password(XEN_USER, XEN_PWD)
     vm = session.xenapi.VM.get_by_name_label(str(self.vm_name))[0]
     state = session.xenapi.VM.get_record(vm)
     session.xenapi.session.logout()
     return state["power_state"]
示例#38
0
    def _session(self):
        LOG.debug("Created new Xapi session")

        session = XenAPI.Session(CONF.AGENT.xapi_connection_url)
        session.login_with_password(CONF.AGENT.xapi_connection_username,
                                    CONF.AGENT.xapi_connection_password)
        return session
示例#39
0
 def __enter__(self):
     self._session = XenAPI.xapi_local()
     self._session.xenapi.login_with_password("root", "")
     other_config = self.get_other_config()
     vdi_ref = self.get_existing_backup_vdi()
     new_vdi = False
     if not vdi_ref:
         new_vdi = True
         vdi_ref = self.create_backup_vdi()
     self.create_and_plug_backup_vbd(vdi_ref)
     device = os.path.join(
         "/dev/", self._session.xenapi.VBD.get_device(self.vbd_ref))
     if new_vdi:
         runcmd(['mkfs.ext4', device])
     try:
         os.mkdir('/srv/restic-repo')
     except OSError as exc:
         if exc.errno != errno.EEXIST:
             raise
     if not os.path.ismount("/srv/restic-repo"):
         # Check the filesystem, just in case. -f required
         # for later offline resize2fs.
         runcmd(['e2fsck', '-f', '-p', device], error=False)
         # Try to resize, just in case.
         runcmd(['resize2fs', device])
         runcmd(['mount', device, "/srv/restic-repo"])
     if new_vdi:
         init_backup_repo()
示例#40
0
文件: SR.py 项目: euanh/sm
    def __init__(self, srcmd, sr_uuid):
        """Base class initializer. All subclasses should call SR.__init__ 
           in their own
        initializers.

        Arguments:
          srcmd: SRCommand instance, contains parsed arguments
        """
        try:
            self.srcmd = srcmd
            self.dconf = srcmd.dconf
            if srcmd.params.has_key('session_ref'):
                self.session_ref = srcmd.params['session_ref']
                self.session = XenAPI.xapi_local()
                self.session._session = self.session_ref
                if 'subtask_of' in self.srcmd.params:
                    self.session.transport.add_extra_header(
                        'Subtask-of', self.srcmd.params['subtask_of'])
            else:
                self.session = None

            if 'host_ref' not in self.srcmd.params:
                self.host_ref = ""
            else:
                self.host_ref = self.srcmd.params['host_ref']

            if 'sr_ref' in self.srcmd.params:
                self.sr_ref = self.srcmd.params['sr_ref']

        except Exception, e:
            raise e
            raise xs_errors.XenError('SRBadXML')
示例#41
0
    def attach(self, dbg, uri):
        log.debug("%s: SR.attach: uri=%s" % (dbg, uri))

        # Notify other pool members we have arrived
        inventory = xcp.environ.readInventory()
        session = XenAPI.xapi_local()
        session.xenapi.login_with_password("root", "")
        this_host = session.xenapi.host.get_by_uuid(
            inventory.get("INSTALLATION_UUID"))
        # FIXME: Do not notify offline hosts
        # FIXME: See ffs.call_plugin_in_pool()
        for host in session.xenapi.host.get_all():
            if host != this_host:
                log.debug("%s: notifying host %s we have arrived" % (dbg, session.xenapi.host.get_name_label(host)))
                session.xenapi.host.call_plugin(
                    host, "gfs2setup", "gfs2Reload", {})

        # Zone in the LUN on this host
        dev_path = plug_device(dbg, uri)

        # Mount the gfs2 filesystem
        mnt_path = mount(dbg, dev_path)

        log.debug("%s: mounted on %s" % (dbg, mnt_path))
        uri = "file://" + mnt_path
        return uri
示例#42
0
    def __init__(self, url='', password='', username='******'):
        self.username = username
        self.password = password

        if url == '' or password == '':
            self.s = XenAPI.xapi_local()
        else:
            self.s = XenAPI.Session(url)
示例#43
0
def get_localAPI_session():
    # First acquire a valid session
    session = XenAPI.xapi_local()
    try:
        session.xenapi.login_with_password('root','')
    except:
        raise xs_errors.XenError('APISession')
    return session
示例#44
0
def main(argv):
    session = XenAPI.xapi_local()
    session.xenapi.login_with_password("", "", "1.0", "xen-api-scripts-linkvmsbysr.py")

    try:
        opts, args = getopt.getopt(sys.argv[1:], "hd:", [])
    except getopt.GetoptError, err:
        print str(err)
        usage()
示例#45
0
def switchBootloader(vm_uuid, target_bootloader = "pygrub"):
    if never_latch: return
    session = XenAPI.xapi_local()
    session.login_with_password("", "")
    try:
        vm = session.xenapi.VM.get_by_uuid(vm_uuid)
        session.xenapi.VM.set_PV_bootloader(vm, target_bootloader)
    finally:
        session.logout()
示例#46
0
def main():
    args = build_parser().parse_args()
    session = XenAPI.xapi_local()
    session.xenapi.login_with_password('root', '', '', 'send_message.py')

    try:
        session.xenapi.message.create(args.name, args.priority, args.cls, args.uuid, args.body)
    finally:
        session.xenapi.logout()
示例#47
0
def get_vm_group_perfmon(args={ }):
    login = XenAPI.xapi_local()
    login.login_with_password("", "")
    result = ""

    total_vm = int(args['total_vm'])
    total_counter = int(args['total_counter'])
    now = int(time.time()) / 60

    # Get pool's info of this host
    # pool = login.xenapi.pool.get_all()[0]
    # Get master node's address of pool
    # master = login.xenapi.pool.get_master(pool)
    # master_address = login.xenapi.host.get_address(master)
    session = login._session

    max_duration = 0
    for counter_count in xrange(1, total_counter + 1):
        duration = int(args['duration' + str(counter_count)])
        if duration > max_duration:
            max_duration = duration

    rrd_updates = RRDUpdates()
    rrd_updates.refresh(login.xenapi, now * 60 - max_duration, session, { })

    # for uuid in rrd_updates.get_vm_list():
    for vm_count in xrange(1, total_vm + 1):
        vm_name = args['vmname' + str(vm_count)]
        vm_uuid = getuuid(vm_name)
        # print "Got values for VM: " + str(vm_count) + " " + vm_uuid
        for counter_count in xrange(1, total_counter + 1):
            # refresh average
            average_cpu = 0
            average_memory = 0
            counter = args['counter' + str(counter_count)]
            total_row = rrd_updates.get_nrows()
            duration = int(args['duration' + str(counter_count)]) / 60
            duration_diff = total_row - duration
            if counter == "cpu":
                total_cpu = rrd_updates.get_total_cpu_core(vm_uuid)
                for row in xrange(duration_diff, total_row):
                    for cpu in xrange(0, total_cpu):
                        average_cpu += rrd_updates.get_vm_data(vm_uuid, "cpu" + str(cpu), row)
                average_cpu /= (duration * total_cpu)
                if result == "":
                    result += str(vm_count) + '.' + str(counter_count) + ':' + str(average_cpu)
                else:
                    result += ',' + str(vm_count) + '.' + str(counter_count) + ':' + str(average_cpu)
            elif counter == "memory":
                for row in xrange(duration_diff, total_row):
                    average_memory += rrd_updates.get_vm_data(vm_uuid, "memory_target", row) / 1048576 - rrd_updates.get_vm_data(vm_uuid, "memory_internal_free", row) / 1024
                average_memory /= duration
                if result == "":
                    result += str(vm_count) + '.' + str(counter_count) + ':' + str(average_memory)
                else:
                    result += ',' + str(vm_count) + '.' + str(counter_count) + ':' + str(average_memory)
    return result
示例#48
0
def main(argv):
    session = XenAPI.xapi_local()
    session.xenapi.login_with_password("", "", "1.0", "xen-api-scripts-backup-sr-metadata")

    try:
        opts, args = getopt.getopt(argv, "hf:", [])
    except getopt.GetoptError, err:
        print str(err)
        usage()
示例#49
0
def getDesiredInitiatorName(dbg):
    # FIXME: for now, get this from xapi. In future, xapi will 
    # write this to a file we can read from.
    inventory = xcp.environ.readInventory()
    session = XenAPI.xapi_local()
    session.xenapi.login_with_password("root", "")
    this_host = session.xenapi.host.get_by_uuid(
                inventory.get("INSTALLATION_UUID"))
    return session.xenapi.host.get_other_config(this_host)['iscsi_iqn']
示例#50
0
def main(argv):
    session = XenAPI.xapi_local()
    session.xenapi.login_with_password("", "")

    try:
        opts, args = getopt.getopt(argv, "hf:u:", [])
    except getopt.GetoptError, err:
        print str(err)
        usage()
示例#51
0
文件: kvpd.py 项目: HackLinux/xs-cim
    def __init__(self, event_classes, actions):
        self.session = XenAPI.xapi_local()
        self.session.login_with_password("","")

        self.classes = event_classes
        self.actions = actions

        # Register the session object to listen for
        # updates to tasks.
        self.session.xenapi.event.register(self.classes)
示例#52
0
 def OpenSession(self):
     session = None
     
     try:
         # Try the local Unix domain socket first
         session = XenAPI.xapi_local()
         session.login_with_password('root','')
     except Exception,  e:
         session = None
         self.error = e
示例#53
0
def switchBootloader(vm_uuid, target_bootloader = "pygrub"):
    if never_latch: return
    session = XenAPI.xapi_local()
    session.login_with_password("", "")
    try:
        xcp.logger.debug("Switching to " + target_bootloader)
        vm = session.xenapi.VM.get_by_uuid(vm_uuid)
        session.xenapi.VM.set_PV_bootloader(vm, target_bootloader)
        propagatePostinstallLimits(session, vm)
    finally:
        session.logout()
示例#54
0
文件: kvpd.py 项目: HackLinux/xs-cim
 def __init__(self, network='xenapi', vm_filt=lambda vm_rec:'kvp_enabled' \
                  in vm_rec['other_config'].keys() \
                  and not vm_rec['is_a_snapshot'] \
                  and vm_rec['power_state'] == "Running"):
     self.session = XenAPI.xapi_local()
     self.session.login_with_password("","")
     self.network = network
     self.vm_filt = vm_filt
     self.network_ref = self.get_internal_management_network()
     self.bridge = self.session.xenapi.network.get_bridge(self.network_ref)
     log.debug("Bridge = %s" % self.bridge)
     self.dom0_mac = self.get_dom0_mac()
示例#55
0
def tweak_bootable_disk(vm):
    session = XenAPI.xapi_local()
    session.xenapi.login_with_password("", "")
    try:
        # get all VBDs, set bootable = (device == 0):
        vm_ref = session.xenapi.VM.get_by_uuid(vm)
        vbds = session.xenapi.VM.get_VBDs(vm_ref)
        
        for vbd in vbds:
            session.xenapi.VBD.set_bootable(vbd, session.xenapi.VBD.get_userdevice(vbd) == "0")
    finally:
        session.logout()
def main():

    # First acquire a valid session by logging in:
    session = XenAPI.xapi_local()
    session.xenapi.login_with_password("root", "")

    hostname = socket.gethostname()
    host = (session.xenapi.host.get_by_name_label(hostname))[0]

    # warning when host not found...
    if not host:
        print "failed to detect XAPI host for '%s'" % hostname
        sys.exit(1)

    bonds, slaves = get_bonds(session, host)
    bond_status = get_bond_status(session, host)

    clist = []
    olist = []

    # iterate over the bonds
    for b in bonds:
        net = bonds[b]['name_label']
        ref = bonds[b]['bond_master_of'][0]
        status = bond_status[ref]

        # On XenServer 6.0 we manually build links_up by checking carrier
        if 'links_up' not in status:

            status['links_up'] = 0

            for slave in status['slaves']:
                if slaves[slave]['carrier']:
                    status['links_up'] += 1

        if len(status['slaves']) != int(status['links_up']):
            clist.append("%s has only %s links up (%s slaves)"
                         % (net, status['links_up'], len(status['slaves'])))
        else:
            olist.append("%s %s links up" % (net, status['links_up']))

    if len(clist):
        print "CRITICAL:", ", ".join(clist)
        return 2
    elif len(olist):
        print "OK:", ", ".join(olist)
        return 0
    else:
        print "OK: no bonds found"
        return 0
def main():
    xapi = XenAPI.xapi_local();
    xapi.login_with_password("","")
    session=xapi._session
    rrd_updates = RRDUpdates()
    rrd_updates.refresh(session,{})
    for uuid in rrd_updates.get_vm_list():
        print "Got values for VM: "+uuid
        for param in rrd_updates.get_vm_param_list(uuid):
            print "param: "+param
            data=""
            for row in range(rrd_updates.get_nrows()):
                data=data+"(%d,%f) " % (rrd_updates.get_row_time(row),
                                        rrd_updates.get_vm_data(uuid,param,row))
            print data
示例#58
0
    def ls(self, dbg, sr):
        pv_name = getPVName(dbg,sr)
        vg_name = getVGName(dbg,sr)
        lv_name = "/dev/" + vg_name +"/gfs2"

        try:
            # refresh iscsi connection to reflect LUN's new size
            call(dbg, ["/usr/sbin/iscsiadm", "-m", "node", "-R"])

            # Does not matter if LUN is resized or not, go ahead and resize pv,
            # incase if LUN is resized pv size will get updated
            call(dbg, ["/usr/sbin/pvresize" , pv_name, "--config", "global{metadata_read_only=0}"])

            # if pv was expanded, this will reflect as freespace
            # in the associated volume group, only then we need to expand gfs2 lv

            stats = vg_stats(dbg,vg_name)
            if stats['freespace'] > VG_FREE_SPACE_THRESHOLD:
                log.debug("Free space (%s) detected in VG, expanding gfs2 LV." %str(stats['freespace']))
                opq = urlparse.urlparse(sr).path
                try:
                    gl = os.path.join(opq, "gl")
                    f = util.lock_file(dbg, gl, "w+")
                    # extend lv
                    call(dbg, ["lvextend", "-l+100%FREE", lv_name, "--config", "global{metadata_read_only=0}"])

                    #inform other node about LUN resize
                    inventory = xcp.environ.readInventory()
                    session = XenAPI.xapi_local()
                    session.xenapi.login_with_password("root", "")
                    this_host = session.xenapi.host.get_by_uuid(
                        inventory.get("INSTALLATION_UUID"))

                    for host in session.xenapi.host.get_all():
                        if host != this_host:
                            log.debug("%s: setup host %s" % (dbg, session.xenapi.host.get_name_label(host)))
                            session.xenapi.host.call_plugin(
                                host, "gfs2setup", "refreshDM", {'lv_name': lv_name, 'pv_dev': pv_name.split('/')[2]})

                    # grow gfs2
                    call(dbg, ["gfs2_grow", mountpoint_root + "dev/" + vg_name +"/gfs2"])

                except Exception, e:
                    raise e

                finally:
                    if f:
                        util.unlock_file(dbg,f)