def run(self): with Client(unix_socket_path="/var/run/xenstored/socket_ro") as c: # watch the xenstore entries and perform different functions accodingly m = c.monitor() for key in self.keys: tmp_key_path = (self.base_path+'/'+self.domuid+'/'+key).encode() token = (key).encode() m.watch(tmp_key_path,token) msg="" while msg!='done': path,token=next(m.wait()) msg=c.read(path).decode() self.threadLock.acquire() if "heart_rate" in path.decode(): heart_rate=-1 try : self.st=time.time() heart_rate = float(msg) self.res_allocat(heart_rate) print(time.time()-st) except: heart_rate=-1 self.threadLock.release() return
def run(self): with Client(unix_socket_path="/var/run/xenstored/socket_ro") as c: # watch the xenstore entries and perform different functions accodingly m = c.monitor() for key in self.keys: tmp_key_path = (self.base_path + '/' + self.domuid + '/' + key).encode() token = (key).encode() m.watch(tmp_key_path, token) msg = "" while msg != 'done': path, token = next(m.wait()) msg = c.read(path).decode() self.threadLock.acquire() if "frame_size" in path.decode(): if msg.isdigit(): with open("data.txt", "a") as myfile: myfile.write(self.domuid + " " + (msg) + " frame size" + " " + str(time.time()) + "\n") if "heart_rate" in path.decode(): heart_rate = -1 try: heart_rate = float(msg) self.res_allocat(heart_rate) except: heart_rate = -1 self.threadLock.release() return
def write(self,key='test',val='0'): with Client(xen_bus_path="/dev/xen/xenbus") as c: msg=str(val).encode() success = False while not success: c.transaction() c.write(self.key_path_hash[key],msg) success = c.commit()
def __init__(self,keys=['test'],base_path='/local/domain'): self.domu_id="" self.keys=keys self.base_path=base_path self.key_path_hash = {} with Client(xen_bus_path="/dev/xen/xenbus") as c: self.domu_id = c.read("domid".encode()) for key in self.keys: self.key_path_hash[key]=(self.base_path+'/'+self.domu_id.decode()+'/'+key).encode()
def list_vm(self, vm_name, display_port): """ lists specified virtual machine (output of xl list vm_name) :param vm_name name of virtual machine :param (OPTIONAL) Display Driver used (VNC/Spice) :return VirtualMachine with id, name, memory, vcpus, state, uptime """ logger.debug('Listing VM {}'.format(vm_name)) cmd = 'xl list ' + vm_name p = Popen(cmd.split(), stdout=PIPE, stderr=PIPE) out, err = p.communicate() if p.returncode != 0: raise Exception('ERROR : cannot list the vm. \n Reason : %s' % err.rstrip()) output = out.split("\n") line = output[1] line = " ".join(line.split()) val = line.strip().split(" ") # creating VirtualMachine instance to return vm = VirtualMachine(val[0]) vm.id = val[1] vm.memory = val[2] vm.vcpus = val[3] vm.state = val[4] vm.uptime = val[5] vm.vnc_port = None if not display_port is None: # The display server being used is SPICE vm.vnc_port = display_port else: # even though value of vnc port is set in the config file, if the port is already in use # by the vnc server, it allocates a new vnc port without throwing an error. # this additional step makes sure that we get the updated vnc-port #cmd = 'xenstore-read /local/domain/' + vm.id + '/console/vnc-port' #p = Popen(cmd.split(), stdout=PIPE, stderr=PIPE) #out, err = p.communicate() #if not p.returncode == 0: # raise Exception('ERROR : cannot start the vm - error while getting vnc-port. ' # '\n Reason : %s' % err.rstrip()) #vm.vnc_port = out.rstrip() with Client() as c: vm.vnc_port = c[b'/local/domain/{}/console/vnc-port'.format( vm.id)] if vm.vnc_port is None: raise Exception( 'ERROR : cannot start the vm - error while getting vnc-port.') logger.debug('Display Port for VM Id {} is {}'.format( vm.id, vm.vnc_port)) return vm
def run(**kwargs): with Client(**kwargs) as c: # a) write-read. c.write("/foo/bar", "baz") print(c.read("/foo/bar")) # ==> "baz" # b) exceptions! let's try to read a non-existant path. try: c.read("/path/to/something/useless") except PyXSError as e: print(e) # c) okay, time to delete that /foo/bar path. c.rm("/foo/bar") try: c.read("/foo/bar") except PyXSError as e: print("`/foo/bar` is no moar!") # d) directory listing and permissions. c.mkdir("/foo/bar") c.mkdir("/foo/baz") c.mkdir("/foo/boo") print("Here's what `/foo` has: ", c.ls("/foo")) print(c.get_permissions("/foo")) # e) let's watch some paths! c.write("/foo/bar", "baz") with c.monitor() as m: m.watch("/foo/bar", "baz") print("Watching ... do `$ xenstore-write /foo/bar <anything>`.") print(m.wait()) m.unwatch("/foo/bar", "baz") # f) domain managment commands. print(c.get_domain_path(0)) print(c.is_domain_introduced(0)) # g) transactions. with c.transaction() as t: print("Creating a `/bar/foo` within a transaction.") t.write("/bar/foo", "baz") print("Transaction is over -- let's check it: " "/bar/foo =", c.read("/bar/foo"))
def __init__(self, keys=['heart_rate'], domu_ids=[], base_path='/local/domain'): self.domu_ids = domu_ids self.keys = keys self.base_path = base_path with Client(xen_bus_path="/dev/xen/xenbus") as c: if domu_ids == []: for x in c.list(base_path.encode()): self.domu_ids.append(x.decode()) self.domu_ids.pop(0) for domuid in self.domu_ids: permissions = [] permissions.append(('b' + '0').encode()) permissions.append(('b' + domuid).encode()) for key in keys: tmp_key_path = (base_path + '/' + domuid + '/' + key).encode() tmp_val = ('xenstore entry init').encode() c.write(tmp_key_path, tmp_val) c.set_perms(tmp_key_path, permissions) print('created', key, 'for dom', domuid)
def listenToVMShutdown(self, dom_id): try: with Client() as c: # the sys.arg is the domid which is to be passed to the function call # dom_id = int(sys.argv[1]) dom_name = c['/local/domain/{}/name'.format(dom_id)] user_id = dom_name.split('_')[0] vm_id = dom_name.split('_')[2] course_id = dom_name.split('_')[1] logger.debug('VM {}, {}'.format(user_id, vm_id)) path = c.get_domain_path(dom_id) path = path + '/control/shutdown' with c.monitor() as m: # watch for any random string m.watch(path, b'baz') logger.debug('Watching path {}'.format(path)) next(m.wait()) if next(m.wait()) is not None: logger.debug('Event on path {}'.format(path)) # Send update via ZMQ Socket task_kwargs = { 'user_id': user_id, 'course_id': course_id, 'vm_id': vm_id, } task_socket.send_json({ 'task': 'release_vm', 'task_kwargs': task_kwargs, }) # requests.get('https://' + config.get("VITAL", "SERVER_NAME") + '/vital/users/' + user_id + '/vms/' + vm_id + '/release-vm/', params=params) except Exception as e: logger.error(str(e))
def vmonitor(self): # one monitor observe one domU at a time with Client(unix_socket_path="/var/run/xenstored/socket_ro") as c: m = c.monitor() for key in self.keys: tmp_key_path = (self.base_path + '/' + self.domuid + '/' + key).encode() token = (key).encode() m.watch(tmp_key_path, token) msg = "" while msg != 'done': path, token = next(m.wait()) msg = c.read(path).decode() self.threadLock.acquire() if self.keys[1] in path.decode(): if msg.isdigit(): self.algo = int(msg) with open("info.txt", "a") as myfile: myfile.write(self.domuid + " " + (msg) + " " + str(time.time()) + "\n") if self.keys[2] in path.decode(): self.pid.reset() if msg.isdigit(): with open("info.txt", "a") as myfile: myfile.write(self.domuid + " " + (msg) + " frame freq" + " " + str(time.time()) + "\n") if self.keys[3] in path.decode(): self.pid.reset() if msg.isdigit(): tmp_new_timeslice_us = int(msg) * 1000 if self.rtxen_or_credit == 1: cur_bw = 0 myinfo = self.shared_data[self.domuid] for vcpu in myinfo: if vcpu['pcpu'] != -1: cur_bw = int(vcpu['b']) xen_interface.sched_rtds( self.domuid, tmp_new_timeslice_us, cur_bw / self.timeslice_us * tmp_new_timeslice_us, []) xen_interface.sched_rtds( str(int(self.domuid) + 2), tmp_new_timeslice_us, (self.timeslice_us - cur_bw) / self.timeslice_us * tmp_new_timeslice_us, []) for vcpu in myinfo: if vcpu['pcpu'] != -1: vcpu[ 'b'] = cur_bw / self.timeslice_us * tmp_new_timeslice_us vcpu['p'] = tmp_new_timeslice_us else: cur_bw = 0 myinfo = self.shared_data[self.domuid] for vcpu in myinfo: if vcpu['pcpu'] != -1: cur_bw = int(vcpu['w']) xen_interface.sched_credit( self.domuid, cur_bw / self.timeslice_us * tmp_new_timeslice_us) xen_interface.sched_credit( str(int(self.domuid) + 2), (self.timeslice_us - cur_bw) / self.timeslice_us * tmp_new_timeslice_us) for vcpu in myinfo: if vcpu['pcpu'] != -1: vcpu[ 'w'] = cur_bw / self.timeslice_us * tmp_new_timeslice_us xen_interface.sched_credit_timeslice(int(msg)) self.timeslice_us = tmp_new_timeslice_us with open("info.txt", "a") as myfile: myfile.write(self.domuid + " " + (msg) + " time slice len 6" + " " + str(time.time()) + "\n") if self.keys[0] in path.decode(): heart_rate = -1 try: heart_rate = float(msg) except: heart_rate = -1 if heart_rate > -1: self.res_allocat(heart_rate) #self.res_allo(self.algo,self.rtxen_or_credit,float(msg),self.shared_data,self.domuid ,self.min_heart_rate,self.max_heart_rate) # try : # if self.keys[0] in path.decode(): # self.res_allocat(float(msg)) # #self.res_allo(self.algo,self.rtxen_or_credit,float(msg),self.shared_data,self.domuid ,self.min_heart_rate,self.max_heart_rate) # except: # #print("meow",int(self.domuid),token.decode(),msg) self.threadLock.release()
import argparse ap = argparse.ArgumentParser() ap.add_argument("-f", "--fps", type=float, default=10, help="target fps") ap.add_argument("-a", "--algo", type=int, default=0, help="algorithm for VM1") ap.add_argument("-s", "--static-alloc", type=int, default=20, help="static utilization percentage(%)") args = vars(ap.parse_args()) monitoring_items = ["heart_rate"] monitoring_domU = ["VM1_id_placeholder"] # find correct domUs id with Client(xen_bus_path="/dev/xen/xenbus") as c: domu_ids = [] all_domuid_ids = [] for uid in c.list('/local/domain'.encode()): all_domuid_ids.append(uid.decode()) all_domuid_ids.pop(0) for uid in all_domuid_ids: name_path = ("/local/domain/" + uid + "/name").encode() print(name_path) if c[name_path].decode() == "VM1": monitoring_domU[0] = uid # create xenstore entry for DomU to write data domUs = dom0_comm.Dom0(monitoring_items, monitoring_domU) timeslice_us = 10000 #args["timeslice"]
""" helloworld ~~~~~~~~~~ A minimal working example, showing :mod:`pyxs` API usage. :copyright: (c) 2016 by pyxs authors and contributors, see AUTHORS for more details. """ from __future__ import print_function from pyxs import Client, PyXSError if __name__ == "__main__": with Client() as c: # a) write-read. c[b"/foo/bar"] = b"baz" print(c[b"/foo/bar"]) # ==> "baz" # b) exceptions! let's try to read a non-existant path. try: c[b"/path/to/something/useless"] except PyXSError as e: print(e) # c) okay, time to delete that /foo/bar path. del c[b"/foo/bar"] try: c[b"/foo/bar"]