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:
def should_domain_be_somewhere_else(localhost_uuid, domain): (domid, uuid) = domain try: x = XenAPI.xapi_local() x.xenapi.login_with_password( "root", "", "1.0", "xen-api-scripts-monitor-unwanted-domains.py") try: try: vm = x.xenapi.VM.get_by_uuid(uuid) resident_on = x.xenapi.VM.get_resident_on(vm) current_operations = x.xenapi.VM.get_current_operations(vm) result = current_operations == {} and resident_on != localhost_uuid if result: log("domid %s uuid %s: is not being operated on and is not resident here" % (domid, uuid)) return result except XenAPI.Failure as e: if e.details[0] == "UUID_INVALID": # VM is totally bogus log("domid %s uuid %s: is not in the xapi database" % (domid, uuid)) return True # fail safe for now return False finally: x.xenapi.logout() except: return False
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()
def from_cli(cls): import XenAPI session = XenAPI.xapi_local() session.xenapi.login_with_password('root', '', '', 'SM') return cls.from_session(session)
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
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
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()
def canonicaliseOtherConfig(vm_uuid): session = XenAPI.xapi_local() session.login_with_password("", "", "", PROGRAM_NAME) 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-args': collect(other_config, 'install-args', None), '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 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()
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 __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')
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:
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
def update_rounds(vm, current_round, rounds_required): session = XenAPI.xapi_local() session.xenapi.login_with_password("", "", "", PROGRAM_NAME) 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()
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 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
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.'
def get_xenapi_session(): try: session = XenAPI.xapi_local() session.xenapi.login_with_password('', '') return session except XenAPI.Failure: sys.exit(1)
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')
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)
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 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
def init_session(uname, pwd, local=True): # TODO: enable the init of a possibly remote session if local: session = XenAPI.xapi_local() session.xenapi.login_with_password(uname, pwd) else: print return session
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
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)
def init_session(uname, pwd, local=True): # TODO: enable the init of a possibly remote session if local: session = XenAPI.xapi_local() session.xenapi.login_with_password(uname, pwd) else: log('currently not support remote connection') return session
def main(argv): session = XenAPI.xapi_local() session.xenapi.login_with_password("", "", "1.0", "xen-api-scripts-restore-sr-metadata") try: opts, args = getopt.getopt(argv, "hf:u:", []) except getopt.GetoptError, err: print str(err) usage()
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 library from XenServer 7.2 # SDK 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 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()
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()
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']
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
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()
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()
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()
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()
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)
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
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)
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
def switchBootloader(vm_uuid, target_bootloader = "pygrub"): if never_latch: return session = XenAPI.xapi_local() session.login_with_password("", "", "", PROGRAM_NAME) 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()
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()
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 __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()
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()
def tweak_bootable_disk(vm): if never_latch: return session = XenAPI.xapi_local() session.xenapi.login_with_password("", "", "", PROGRAM_NAME) 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
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
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)
def get_mgmt_config(): ret = None session = XenAPI.xapi_local() session.xenapi.login_with_password('', '') this_host = session.xenapi.session.get_this_host(session._session) host_record = session.xenapi.host.get_record(this_host) for pif in host_record['PIFs']: pif_record = session.xenapi.PIF.get_record(pif) if pif_record['management']: ret = pif_record break session.xenapi.session.logout() return ret