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
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
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)
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!")
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")
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
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)
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
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
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
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)
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
def connection(): s = XenAPI.Session("http://localhost") user = os.getenv('XS_USER', 'root') password = os.getenv('XS_PASSWORD', 'xenroot') s.login_with_password(user, password) yield s s.close()
def test_start_vm(self): # connect to xenserver session = XenAPI.Session(XEN_URL) session.xenapi.login_with_password(XEN_USER, XEN_PWD) vm2 = session.xenapi.VM.get_by_name_label(XEN_TEST_VM2)[0] state = session.xenapi.VM.get_record(vm2) self.assertEqual("Running", state["power_state"])
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('-o', '--output-path', dest='output_path') 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: enable_nbd_on_all_networks(session) vdi_ref = session.xenapi.VDI.get_by_uuid(args.vdi_uuid) session.xenapi.VDI.enable_cbt(vdi_ref) snapshot_ref = session.xenapi.VDI.snapshot(vdi_ref) export_vdi(args.host, session._session, session.xenapi.VDI.get_uuid(snapshot_ref), 'raw', args.output_path) # Once you are done copying the blocks, delete the snapshot data session.xenapi.VDI.data_destroy(snapshot_ref) print session.xenapi.VDI.get_uuid(snapshot_ref) finally: session.xenapi.session.logout()
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"]
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)
def __init__(self, Ip, userName, password, vm_uuid): TestSetUp.__init__(self, Ip, userName, password, False, False) self.session = XenAPI.Session("http://%s" % Ip) self.session.xenapi.login_with_password(userName, password) self.vm_uuid = vm_uuid self.vsms = self.conn.EnumerateInstanceNames( 'Xen_VirtualSystemManagementService') vssd_refs = self.conn.EnumerateInstanceNames("Xen_ComputerSystem") for ref in vssd_refs: if ref['Name'] == vm_uuid: self.test_vm = ref if not self.test_vm: raise Exception("Error: cannot find VM with UUID %s" % vm_uuid) vm_ref = self.session.xenapi.VM.get_by_uuid(vm_uuid) if not 'kvp_enabled' in self.session.xenapi.VM.get_other_config( vm_ref).keys(): # Initiate CIM call that setups up the specified VM for using # the KVP communication channel. # This is a requirement for any other KVP operations. print "Setup KVP Communication" SetupKVPCommunication(self.conn, self.test_vm) print "Init complete"
def main(): try: print "Aquiring session with the provided xenserver IP" session = XenAPI.Session('http://' + inputs['xenserver_master_ip']) print "Trying to connect to xenserver %s" % inputs[ 'xenserver_master_ip'] session.xenapi.login_with_password(inputs['xenserver_user'], inputs['xenserver_password']) print "Connected to xenserver !" vm_refs = session.xenapi.VM.get_by_name_label(inputs['vm_name']) for vm_ref in vm_refs: vm_uuid = session.xenapi.VM.get_uuid(vm_ref) vm = session.xenapi.VM.get_by_uuid(vm_uuid) force = str2bool(inputs['force']) if inputs['operation'] == 'start': start_vm(session, vm, force) elif inputs['operation'] == 'stop': stop_vm(session, vm, force) elif inputs['operation'] == 'suspend': suspend_vm(session, vm) elif inputs['operation'] == 'pause': pause_vm(session, vm) elif inputs['operation'] == 'resume': resume_vm(session, vm) elif inputs['operation'] == 'reset': reset_vm(session, vm, force) except Exception, e: print "Caught exception: %s" % str(e)
def main(): options = parse_arguments() setLogLevel(options.loglevel) log.debug("\nXen Server host: " + options.xenhost + "\n") url = "http://" + options.xenhost session = XenAPI.Session(url) try: session.xenapi.login_with_password(options.username, options.userpwd) except XenAPI.Failure as f: log.error("Failed to acquire a session: %s" % f.details) sys.exit(1) try: if options.create_vm_names: new_vms = create_vms(session, options) log.info(new_vms) elif options.delete_vm_names: delete_vms(session, options) elif options.list_vm_names: list_given_vm_set_details(session, options) else: list_vms(session, options) except Exception as e: log.error(str(e)) raise finally: session.logout()
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.'
def main(): try: print "Aquiring session with the provided xenserver IP..." session = XenAPI.Session('http://' + inputs['xenserver_master_ip']) print "Trying to connect to xenserver %s ..." % inputs[ 'xenserver_master_ip'] session.xenapi.login_with_password(inputs['xenserver_user'], inputs['xenserver_password']) print "Connected to xenserver !" for vm_ref in session.xenapi.VM.get_by_name_label(inputs['vm_name']): vm_uuid = session.xenapi.VM.get_uuid(vm_ref) vm = session.xenapi.VM.get_by_uuid(vm_uuid) for host_ref in session.xenapi.host.get_by_name_label( inputs['target_host']): host_uuid = session.xenapi.host.get_uuid(host_ref) target_host = session.xenapi.host.get_by_uuid(host_uuid) print "Migrating VM using XenMotion..." try: session.xenapi.VM.pool_migrate(vm, target_host, {"live": "true"}) msg = "Successfully migrated VM %s to %s" % (inputs['vm_name'], inputs['target_host']) print msg except Exception, e: print e msg = "Failed to Migrate VM %s to %s " % (inputs['vm_name'], inputs['target_host']) print msg except Exception, e: print "Caught exception: %s" % str(e)
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
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)
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)
def test_create_vm(self): # connect to xenserver session = XenAPI.Session(XEN_URL) session.xenapi.login_with_password(XEN_USER, XEN_PWD) vm1 = session.xenapi.VM.get_by_name_label(XEN_TEST_VM1) #vm = session.xenapi.VM.get_by_name_label("NotExistingVM") self.assertNotEqual([], vm1)
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"))
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