コード例 #1
0
ファイル: relocate.py プロジェクト: andreiw/xen3-arm-tegra
 def op_receive(self, name, _):
     if self.transport:
         self.send_reply(["ready", name])
         XendDomain.instance().domain_restore_fd(
             self.transport.sock.fileno())
     else:
         log.error(name + ": no transport")
         raise XendError(name + ": no transport")
コード例 #2
0
 def getVBDs(self):
     from xen.xend import XendDomain
     vbd_refs = [d.get_vbds() for d in XendDomain.instance().list('all')]
     vbd_refs = reduce(lambda x, y: x + y, vbd_refs)
     vbds = []
     for vbd_ref in vbd_refs:
         vdi = XendDomain.instance().get_dev_property_by_uuid('vbd', vbd_ref, 'VDI')
         if vdi == self.uuid:
             vbds.append(vbd_ref)
     return vbds
コード例 #3
0
ファイル: image.py プロジェクト: Hearen/OnceServer
 def destroyDeviceModel(self):
     if self.device_model is None:
         return
     self.sentinel_lock.acquire()
     try:
         stubdomid = self.vm.getStubdomDomid()
         if stubdomid is not None :
             from xen.xend import XendDomain
             XendDomain.instance().domain_destroy(stubdomid)
         elif self.pid:
             try:
                 os.kill(self.pid, signal.SIGHUP)
             except OSError, exn:
                 log.exception(exn)
             # Try to reap the child every 100ms for 10s. Then SIGKILL it.
             for i in xrange(100):
                 try:
                     (p, rv) = os.waitpid(self.pid, os.WNOHANG)
                     if p == self.pid:
                         break
                 except OSError:
                     # This is expected if Xend has been restarted within
                     # the life of this domain.  In this case, we can kill
                     # the process, but we can't wait for it because it's
                     # not our child. We continue this loop, and after it is
                     # terminated make really sure the process is going away
                     # (SIGKILL).
                     pass
                 time.sleep(0.1)
             else:
                 log.warning("DeviceModel %d took more than 10s "
                             "to terminate: sending SIGKILL" % self.pid)
                 try:
                     os.kill(self.pid, signal.SIGKILL)
                     os.waitpid(self.pid, 0)
                 except OSError:
                     # This happens if the process doesn't exist.
                     pass
     finally:
         self.pid = None
         self.sentinel_lock.release()
         
     state = xstransact.Remove("/local/domain/0/device-model/%i"
                               % self.vm.getDomid())
     try:
         os.unlink('/var/run/tap/qemu-read-%d' % self.vm.getDomid())
         os.unlink('/var/run/tap/qemu-write-%d' % self.vm.getDomid())
     except:
         pass
     try:
         del sentinel_fifos_inuse[self.sentinel_path_fifo]
         os.unlink(self.sentinel_path_fifo)
     except:
         pass
コード例 #4
0
    def destroyDeviceModel(self):
        if self.device_model is None:
            return
        self.sentinel_lock.acquire()
        try:
            stubdomid = self.vm.getStubdomDomid()
            if stubdomid is not None:
                from xen.xend import XendDomain
                XendDomain.instance().domain_destroy(stubdomid)
            elif self.pid:
                try:
                    os.kill(self.pid, signal.SIGHUP)
                except OSError, exn:
                    log.exception(exn)
                # Try to reap the child every 100ms for 10s. Then SIGKILL it.
                for i in xrange(100):
                    try:
                        (p, rv) = os.waitpid(self.pid, os.WNOHANG)
                        if p == self.pid:
                            break
                    except OSError:
                        # This is expected if Xend has been restarted within
                        # the life of this domain.  In this case, we can kill
                        # the process, but we can't wait for it because it's
                        # not our child. We continue this loop, and after it is
                        # terminated make really sure the process is going away
                        # (SIGKILL).
                        pass
                    time.sleep(0.1)
                else:
                    log.warning("DeviceModel %d took more than 10s "
                                "to terminate: sending SIGKILL" % self.pid)
                    try:
                        os.kill(self.pid, signal.SIGKILL)
                        os.waitpid(self.pid, 0)
                    except OSError:
                        # This happens if the process doesn't exist.
                        pass
        finally:
            self.pid = None
            self.sentinel_lock.release()

        state = xstransact.Remove("/local/domain/0/device-model/%i" %
                                  self.vm.getDomid())
        try:
            os.unlink('/var/run/tap/qemu-read-%d' % self.vm.getDomid())
            os.unlink('/var/run/tap/qemu-write-%d' % self.vm.getDomid())
        except:
            pass
        try:
            del sentinel_fifos_inuse[self.sentinel_path_fifo]
            os.unlink(self.sentinel_path_fifo)
        except:
            pass
コード例 #5
0
 def op_receive(self, name, _):
     if self.transport:
         self.send_reply(["ready", name])
         try:
             XendDomain.instance().domain_restore_fd(
                 self.transport.sock.fileno(), relocating=True)
         except:
             self.send_error()
             self.close()
     else:
         log.error(name + ": no transport")
         raise XendError(name + ": no transport")
コード例 #6
0
 def op_receive(self, name, _):
     if self.transport:
         self.send_reply(["ready", name])
         try:
             XendDomain.instance().domain_restore_fd(
                 self.transport.sock.fileno(), relocating=True)
         except:
             self.send_error()
             self.close()
     else:
         log.error(name + ": no transport")
         raise XendError(name + ": no transport")
コード例 #7
0
def domains_with_state(detail, state, full):
    if detail:
        domains = XendDomain.instance().list_sorted(state)
        ret = []
        for dom in domains:
            try:
                ret.append(fixup_sxpr(dom.sxpr(not full)))
            except:
                log.warn("Failed to query SXPR for domain %s" % str(dom))
                pass
        return ret
    else:
        return XendDomain.instance().list_names(state)
コード例 #8
0
ファイル: XMLRPCServer.py プロジェクト: changliwei/suse_xen
def domains_with_state(detail, state, full):
    if detail:
        domains = XendDomain.instance().list_sorted(state)
        ret = []
        for dom in domains:
            try:
                ret.append(fixup_sxpr(dom.sxpr(not full)))
            except:
                log.warn("Failed to query SXPR for domain %s" % str(dom))
                pass
        return ret
    else:
        return XendDomain.instance().list_names(state)
コード例 #9
0
ファイル: XendCheckpoint.py プロジェクト: changliwei/suse_xen
    def wait_devs(dominfo):
        from xen.xend import XendDomain

        lock = True;
        try:
            XendDomain.instance().domains_lock.release()
        except:
            lock = False;

        try:
            dominfo.waitForDevices() # Wait for backends to set up
        except Exception, exn:
            log.exception(exn)
            if lock:
                XendDomain.instance().domains_lock.acquire()
            raise
コード例 #10
0
ファイル: PingNFS.py プロジェクト: cxxly/once-xend-core
 def check_status(self):
     try:
         global status_list
         global status_last
         global dest_ip
         status_changed=False
         status_list_copy=status_list
         while True:
             if status_list_copy[:5].count(1)==5:
                 status_now=True
             elif status_list_copy[:5].count(0)==5 or status_list_copy.count(0)==10:
                 status_now=False
             if status_now!=status_last:
                 status_changed=True
             else:
                 status_changed=False
             status_last=status_now
             if status_changed==True:
                 if status_now==False:
                     xendom = XendDomain.instance()
                     doms = xendom.list('all')
                     for dom in doms:
                         vm_uuid = dom.get_uuid()
                         if cmp(vm_uuid, DOM0_UUID) == 0:
                             continue
                         self.hard_shutdown_and_delete(vm_uuid)
     #                print dest_ip,"status to Down"
     #            elif status_now==True:
     #                print dest_ip,"status to Up"
             #print 'now status is: ', status_now
             time.sleep(0.3)
     except BaseException,e:
         log.debug(e)     
コード例 #11
0
ファイル: relocate.py プロジェクト: jeffchao/xen-3.3-tcg
 def op_sslreceive(self, name, _):
     if self.transport:
         self.send_reply(["ready", name])
         p2cread, p2cwrite = os.pipe()
         threading.Thread(target=connection.SSLSocketServerConnection.recv2fd,
                          args=(self.transport.sock, p2cwrite)).start()
         try:
             XendDomain.instance().domain_restore_fd(p2cread,
                                                     relocating=True)
         except:
             os.close(p2cread)
             os.close(p2cwrite)
             self.send_error()
             self.close()
     else:
         log.error(name + ": no transport")
         raise XendError(name + ": no transport")
コード例 #12
0
 def activate_xspolicy(self, xspol, flags):
     from xen.xend import XendDomain
     domains = XendDomain.instance()
     try:
         domains.domains_lock.acquire()
         return self.__activate_xspolicy(xspol, flags)
     finally:
         domains.domains_lock.release()
コード例 #13
0
 def activate_xspolicy(self, xspol, flags):
     from xen.xend import XendDomain
     domains = XendDomain.instance()
     try:
         domains.domains_lock.acquire()
         return self.__activate_xspolicy(xspol, flags)
     finally:
         domains.domains_lock.release()
コード例 #14
0
 def op_sslreceive(self, name, _):
     if self.transport:
         self.send_reply(["ready", name])
         p2cread, p2cwrite = os.pipe()
         threading.Thread(
             target=connection.SSLSocketServerConnection.recv2fd,
             args=(self.transport.sock, p2cwrite)).start()
         try:
             XendDomain.instance().domain_restore_fd(p2cread,
                                                     relocating=True)
         except:
             os.close(p2cread)
             os.close(p2cwrite)
             self.send_error()
             self.close()
     else:
         log.error(name + ": no transport")
         raise XendError(name + ": no transport")
コード例 #15
0
    def getDeviceDetails(self, config):
        (devid, back, front) = BlkifController.getDeviceDetails(self, config)

        phantomDevid = 0
        wrapped = False

        try:
            imagetype = self.vm.info['image']['type']
        except:
            imagetype = ""

        if imagetype == 'hvm':
            tdevname = back['dev']
            index = ['c', 'd', 'e', 'f', 'g', 'h', 'i', \
                     'j', 'l', 'm', 'n', 'o', 'p']
            while True:
                global phantomDev
                global phantomId
                import os, stat

                phantomId = phantomId + 1
                if phantomId == 16:
                    if index[phantomDev] == index[-1]:
                        if wrapped:
                            raise VmError(" No loopback block \
                                       devices are available. ")
                        wrapped = True
                        phantomDev = 0
                    else:
                        phantomDev = phantomDev + 1
                    phantomId = 1
                devname = 'xvd%s%d' % (index[phantomDev], phantomId)
                try:
                    info = os.stat('/dev/%s' % devname)
                except:
                    break

            vbd = { 'mode': 'w', 'device': devname }
            fn = 'tap:%s' % back['params']

            # recurse ... by creating the vbd, then fallthrough
            # and finish creating the original device

            from xen.xend import XendDomain
            dom0 = XendDomain.instance().privilegedDomain()
            phantomDevid = dom0.create_phantom_vbd_with_vdi(vbd, fn)
            # we need to wait for this device at a higher level
            # the vbd that gets created will have a link to us
            # and will let them do it there

        # add a hook to point to the phantom device,
        # root path is always the same (dom0 tap)
        if phantomDevid != 0:
            front['phantom_vbd'] = '/local/domain/0/backend/tap/0/%s' \
                                   % str(phantomDevid)

        return (devid, back, front)
コード例 #16
0
ファイル: BlktapController.py プロジェクト: CPFL/gxen
    def getDeviceDetails(self, config):
        (devid, back, front) = BlkifController.getDeviceDetails(self, config)

        phantomDevid = 0
        wrapped = False

        try:
            imagetype = self.vm.info['image']['type']
        except:
            imagetype = ""

        if imagetype == 'hvm':
            tdevname = back['dev']
            index = ['c', 'd', 'e', 'f', 'g', 'h', 'i', \
                     'j', 'l', 'm', 'n', 'o', 'p']
            while True:
                global phantomDev
                global phantomId
                import os, stat

                phantomId = phantomId + 1
                if phantomId == 16:
                    if index[phantomDev] == index[-1]:
                        if wrapped:
                            raise VmError(" No loopback block \
                                       devices are available. ")
                        wrapped = True
                        phantomDev = 0
                    else:
                        phantomDev = phantomDev + 1
                    phantomId = 1
                devname = 'xvd%s%d' % (index[phantomDev], phantomId)
                try:
                    info = os.stat('/dev/%s' % devname)
                except:
                    break

            vbd = { 'mode': 'w', 'device': devname }
            fn = 'tap:%s' % back['params']

            # recurse ... by creating the vbd, then fallthrough
            # and finish creating the original device

            from xen.xend import XendDomain
            dom0 = XendDomain.instance().privilegedDomain()
            phantomDevid = dom0.create_phantom_vbd_with_vdi(vbd, fn)
            # we need to wait for this device at a higher level
            # the vbd that gets created will have a link to us
            # and will let them do it there

        # add a hook to point to the phantom device,
        # root path is always the same (dom0 tap)
        if phantomDevid != 0:
            front['phantom_vbd'] = '/local/domain/0/backend/tap/0/%s' \
                                   % str(phantomDevid)

        return (devid, back, front)
コード例 #17
0
 def get_VM_ssidref(self, vm_ref):
     dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
     if not dom:
         raise InvalidHandleError("VM", vm_ref)
     if dom._stateGet() not in [ XEN_API_VM_POWER_STATE_RUNNING, \
                                 XEN_API_VM_POWER_STATE_PAUSED ]:
         raise VMBadState("Domain is not running or paused.")
     ssid = security.get_ssid(dom.getDomid())
     if not ssid:
         raise SecurityError(-xsconstants.XSERR_GENERAL_FAILURE)
     return ssid[3]
コード例 #18
0
ファイル: P_DataCollect.py プロジェクト: Hearen/OnceServer
    def get_memory_free(self):
        xendom = XendDomain.instance()
        doms = xendom.list()
        doms_mem_total = 0
        for dom in doms:
            if cmp(dom.get_uuid(), DOM0_UUID) == 0:
                continue
            dominfo = xendom.get_vm_by_uuid(dom.get_uuid())
            doms_mem_total += dominfo.get_memory_dynamic_max()
        

        return (self.host_instance.xc.physinfo()['total_memory'] * 1024 - doms_mem_total)/1024
コード例 #19
0
 def reset_acmpolicy(self):
     """
        Attempt to reset the system's policy by udating it with
        the DEFAULT policy.
     """
     from xen.xend import XendDomain
     domains = XendDomain.instance()
     try:
         domains.domains_lock.acquire()
         xml = ACMPolicy.get_reset_policy_xml()
         flags = xsconstants.XS_INST_BOOT | xsconstants.XS_INST_LOAD
         return self.__add_acmpolicy_to_system(xml, flags, True)
     finally:
         domains.domains_lock.release()
コード例 #20
0
 def reset_acmpolicy(self):
     """
        Attempt to reset the system's policy by udating it with
        the DEFAULT policy.
     """
     from xen.xend import XendDomain
     domains = XendDomain.instance()
     try:
         domains.domains_lock.acquire()
         xml = ACMPolicy.get_reset_policy_xml()
         flags = xsconstants.XS_INST_BOOT | xsconstants.XS_INST_LOAD
         return self.__add_acmpolicy_to_system(xml, flags, True)
     finally:
         domains.domains_lock.release()
コード例 #21
0
    def run(self):
        if self.use_tcp:
            # bind to something fixed for now as we may eliminate
            # tcp support completely.
            self.server = TCPXMLRPCServer(("localhost", 8005),
                                          logRequests=False)
        else:
            self.server = UnixXMLRPCServer(XML_RPC_SOCKET, False)

        # Functions in XendDomainInfo
        for name in methods:
            fn = eval("lambda domid, *args: dispatch(domid, '%s', args)" %
                      name)
            self.server.register_function(fn, "xend.domain.%s" % name)

        # Functions in XendDomain
        inst = XendDomain.instance()
        for name in dir(inst):
            fn = getattr(inst, name)
            if name.startswith("domain_") and callable(fn):
                if name not in exclude:
                    self.server.register_function(fn,
                                                  "xend.domain.%s" % name[7:])

        # Functions in XendNode and XendDmesg
        for type, lst, n in [(XendNode, ['info', 'cpu_bvt_slice_set'], 'node'),
                             (XendDmesg, ['info', 'clear'], 'node.dmesg')]:
            inst = type.instance()
            for name in lst:
                self.server.register_function(getattr(inst, name),
                                              "xend.%s.%s" % (n, name))

        # A few special cases
        self.server.register_function(domain, 'xend.domain')
        self.server.register_function(domains, 'xend.domains')
        self.server.register_function(get_log, 'xend.node.log')
        self.server.register_function(domain_create, 'xend.domain.create')
        self.server.register_function(domain_restore, 'xend.domain.restore')

        self.server.register_introspection_functions()
        self.ready = True
        self.server.serve_forever()
コード例 #22
0
ファイル: PingNFS.py プロジェクト: cxxly/once-xend-core
 def hard_shutdown_and_delete(self, vm_ref):
     xendom = XendDomain.instance()
     dominfo = xendom.get_vm_by_uuid(vm_ref)
     if not dominfo:
         return
     domid = dominfo.getDomid()
     if domid and cmp (int(domid), -1) > 0:
         xendom.domain_destroy(vm_ref)
     i = 0    
     time_out = 30
     while True:
         i += 1
 #                ps_new = self.VM_get_power_state(session, vm_ref)['Value']
         domid = dominfo.getDomid()
 #                log.debug(ps_new)
         if not domid or cmp (int(domid), -1) == 0:
             break
         elif cmp(i, time_out) > 0:
             break
         else:
             time.sleep(0.5)
             continue 
コード例 #23
0
    def run(self):
        if self.use_tcp:
            # bind to something fixed for now as we may eliminate
            # tcp support completely.
            self.server = TCPXMLRPCServer(("localhost", 8005), logRequests=False)
        else:
            self.server = UnixXMLRPCServer(XML_RPC_SOCKET, False)

        # Functions in XendDomainInfo
        for name in methods:
            fn = eval("lambda domid, *args: dispatch(domid, '%s', args)"%name)
            self.server.register_function(fn, "xend.domain.%s" % name)

        # Functions in XendDomain
        inst = XendDomain.instance()
        for name in dir(inst):
            fn = getattr(inst, name)
            if name.startswith("domain_") and callable(fn):
                if name not in exclude:
                    self.server.register_function(fn, "xend.domain.%s" % name[7:])

        # Functions in XendNode and XendDmesg
        for type, lst, n in [(XendNode, ['info', 'cpu_bvt_slice_set'], 'node'),
                             (XendDmesg, ['info', 'clear'], 'node.dmesg')]:
            inst = type.instance()
            for name in lst:
                self.server.register_function(getattr(inst, name),
                                              "xend.%s.%s" % (n, name))

        # A few special cases
        self.server.register_function(domain, 'xend.domain')
        self.server.register_function(domains, 'xend.domains')
        self.server.register_function(get_log, 'xend.node.log')
        self.server.register_function(domain_create, 'xend.domain.create')
        self.server.register_function(domain_restore, 'xend.domain.restore')

        self.server.register_introspection_functions()
        self.ready = True
        self.server.serve_forever()
コード例 #24
0
    def getVMRecords(self):
#         self.login()
#         vmRecords = self.proxy.VM.get_record_lite(self.session, '').get('Value', [])
#         return vmRecords
#         #host = self.proxy.VM.get_all().val ---
        vms = self._VM_get_all()
        retv = []
        if vms:
            for vm_ref in vms:
                xendom = XendDomain.instance()
                xeninfo = xendom.get_vm_by_uuid(vm_ref)
        #        xennode = XendNode.instance()
                if not xeninfo:
                    return retv
         
        #        domid = xeninfo.getDomid()
                dom_uuid = xeninfo.get_uuid()
                record_lite = {'uuid' : dom_uuid,
                               'power_state' : xeninfo.get_power_state(),
                               }  
    #            log.debug(record_lite)
                retv.append(record_lite)
        return retv
コード例 #25
0
 def add_acmpolicy_to_system(self, xmltext, flags, overwrite):
     """ Add an ACM policy's xml representation to the system. The
         policy will automatically be compiled
      flags:
       XS_INST_BOOT : make policy the one to boot the system with
                      by default; if there's a policy already installed,
                      refuse to install this policy unless its one with
                      the same name
       XS_INST_LOAD : load the policy immediately; if this does not work
                      refuse to install this policy
      overwrite:
       If any policy is installed and this is False, refuse to install
       this policy
       If flags is True, then any existing policy will be removed from
       the system and the new one will be installed
     """
     from xen.xend import XendDomain
     domains = XendDomain.instance()
     try:
         domains.domains_lock.acquire()
         return self.__add_acmpolicy_to_system(xmltext, flags, overwrite)
     finally:
         domains.domains_lock.release()
コード例 #26
0
 def add_acmpolicy_to_system(self, xmltext, flags, overwrite):
     """ Add an ACM policy's xml representation to the system. The
         policy will automatically be compiled
      flags:
       XS_INST_BOOT : make policy the one to boot the system with
                      by default; if there's a policy already installed,
                      refuse to install this policy unless its one with
                      the same name
       XS_INST_LOAD : load the policy immediately; if this does not work
                      refuse to install this policy
      overwrite:
       If any policy is installed and this is False, refuse to install
       this policy
       If flags is True, then any existing policy will be removed from
       the system and the new one will be installed
     """
     from xen.xend import XendDomain
     domains = XendDomain.instance()
     try:
         domains.domains_lock.acquire()
         return self.__add_acmpolicy_to_system(xmltext, flags, overwrite)
     finally:
         domains.domains_lock.release()
コード例 #27
0
ファイル: XMLRPCServer.py プロジェクト: changliwei/suse_xen
def domain_restore(src, paused=False):
    info = XendDomain.instance().domain_restore(src, paused)
    return fixup_sxpr(info.sxpr())
コード例 #28
0
ファイル: XMLRPCServer.py プロジェクト: changliwei/suse_xen
def domain_create(config):
    info = XendDomain.instance().domain_create(config)
    return fixup_sxpr(info.sxpr())
コード例 #29
0
def restore(xd, fd, dominfo=None, paused=False, relocating=False):
    signature = read_exact(fd, len(SIGNATURE),
                           "not a valid guest state file: signature read")
    if signature != SIGNATURE:
        raise XendError("not a valid guest state file: found '%s'" % signature)

    l = read_exact(fd, sizeof_int,
                   "not a valid guest state file: config size read")
    vmconfig_size = unpack("!i", l)[0]
    vmconfig_buf = read_exact(fd, vmconfig_size,
                              "not a valid guest state file: config read")

    p = sxp.Parser()
    p.input(vmconfig_buf)
    if not p.ready:
        raise XendError("not a valid guest state file: config parse")

    vmconfig = p.get_val()

    if not relocating:
        domconfig = XendConfig(sxp_obj=vmconfig)
        othervm = xd.domain_lookup_nr(domconfig["name_label"])
        if othervm is None or othervm.domid is None:
            othervm = xd.domain_lookup_nr(domconfig["uuid"])
        if othervm is not None and othervm.domid is not None:
            raise VmError("Domain '%s' already exists with ID '%d'" %
                          (domconfig["name_label"], othervm.domid))

    if dominfo:
        dominfo.resume()
    else:
        dominfo = xd.restore_(vmconfig)

    # repin domain vcpus if a target node number was specified
    # this is done prior to memory allocation to aide in memory
    # distribution for NUMA systems.
    nodenr = -1
    for i, l in enumerate(vmconfig):
        if type(l) == type([]):
            if l[0] == 'node':
                nodenr = int(l[1])

    if nodenr >= 0:
        node_to_cpu = XendNode.instance().xc.physinfo()['node_to_cpu']
        if nodenr < len(node_to_cpu):
            for v in range(0, dominfo.info['VCPUs_max']):
                xc.vcpu_setaffinity(dominfo.domid, v, node_to_cpu[nodenr])

    store_port = dominfo.getStorePort()
    console_port = dominfo.getConsolePort()

    assert store_port
    assert console_port

    # if hvm, pass mem size to calculate the store_mfn
    image_cfg = dominfo.info.get('image', {})
    is_hvm = dominfo.info.is_hvm()
    if is_hvm:
        apic = int(dominfo.info['platform'].get('apic', 0))
        pae = int(dominfo.info['platform'].get('pae', 0))
        log.info("restore hvm domain %d, apic=%d, pae=%d", dominfo.domid, apic,
                 pae)
    else:
        apic = 0
        pae = 0

    try:
        restore_image = image.create(dominfo, dominfo.info)
        memory = restore_image.getRequiredAvailableMemory(
            dominfo.info['memory_dynamic_max'] / 1024)
        maxmem = restore_image.getRequiredAvailableMemory(
            dominfo.info['memory_static_max'] / 1024)
        shadow = restore_image.getRequiredShadowMemory(
            dominfo.info['shadow_memory'] * 1024,
            dominfo.info['memory_static_max'] / 1024)

        log.debug("restore:shadow=0x%x, _static_max=0x%x, _static_min=0x%x, ",
                  dominfo.info['shadow_memory'],
                  dominfo.info['memory_static_max'],
                  dominfo.info['memory_static_min'])

        # Round shadow up to a multiple of a MiB, as shadow_mem_control
        # takes MiB and we must not round down and end up under-providing.
        shadow = ((shadow + 1023) / 1024) * 1024

        # set memory limit
        xc.domain_setmaxmem(dominfo.getDomid(), maxmem)

        balloon.free(memory + shadow)

        shadow_cur = xc.shadow_mem_control(dominfo.getDomid(), shadow / 1024)
        dominfo.info['shadow_memory'] = shadow_cur

        cmd = map(str, [
            xen.util.auxbin.pathTo(XC_RESTORE), fd,
            dominfo.getDomid(), store_port, console_port,
            int(is_hvm), pae, apic
        ])
        log.debug("[xc_restore]: %s", string.join(cmd))

        handler = RestoreInputHandler()

        forkHelper(cmd, fd, handler.handler, True)

        # We don't want to pass this fd to any other children -- we
        # might need to recover the disk space that backs it.
        try:
            flags = fcntl.fcntl(fd, fcntl.F_GETFD)
            flags |= fcntl.FD_CLOEXEC
            fcntl.fcntl(fd, fcntl.F_SETFD, flags)
        except:
            pass

        if handler.store_mfn is None:
            raise XendError('Could not read store MFN')

        if not is_hvm and handler.console_mfn is None:
            raise XendError('Could not read console MFN')

        # get qemu state and create a tmp file for dm restore
        # Even PV guests may have QEMU stat, but its not currently
        # used so only bother with HVM currently.
        if is_hvm:
            qemu_signature = read_exact(fd, len(QEMU_SIGNATURE),
                                        "invalid device model signature read")
            if qemu_signature != QEMU_SIGNATURE:
                raise XendError("not a valid device model state: found '%s'" %
                                qemu_signature)
            qemu_fd = os.open("/var/lib/xen/qemu-save.%d" % dominfo.getDomid(),
                              os.O_WRONLY | os.O_CREAT | os.O_TRUNC)
            while True:
                buf = os.read(fd, dm_batch)
                if len(buf):
                    write_exact(qemu_fd, buf,
                                "could not write dm state to tmp file")
                else:
                    break
            os.close(qemu_fd)

        restore_image.setCpuid()

        os.read(fd, 1)  # Wait for source to close connection

        dominfo.completeRestore(handler.store_mfn, handler.console_mfn)

        #
        # We shouldn't hold the domains_lock over a waitForDevices
        # As this function sometime gets called holding this lock,
        # we must release it and re-acquire it appropriately
        #
        from xen.xend import XendDomain

        lock = True
        try:
            XendDomain.instance().domains_lock.release()
        except:
            lock = False

        try:
            dominfo.waitForDevices()  # Wait for backends to set up
        except Exception, exn:
            log.exception(exn)

        if lock:
            XendDomain.instance().domains_lock.acquire()

        if not paused:
            dominfo.unpause()

        return dominfo
コード例 #30
0
ファイル: XMLRPCServer.py プロジェクト: changliwei/suse_xen
def lookup(domid):
    info = XendDomain.instance().domain_lookup(domid)
    return info
コード例 #31
0
def domains_with_state(detail, state, full):
    if detail:
        domains = XendDomain.instance().list_sorted(state)
        return map(lambda dom: fixup_sxpr(dom.sxpr(not full)), domains)
    else:
        return XendDomain.instance().list_names(state)
コード例 #32
0
 def __init__(self, dom):
     SrvDir.__init__(self)
     self.dom = dom
     self.xd = XendDomain.instance()
コード例 #33
0
            restore_image.setCpuid()

        os.read(fd, 1)  # Wait for source to close connection

        dominfo.completeRestore(handler.store_mfn, handler.console_mfn)

        #
        # We shouldn't hold the domains_lock over a waitForDevices
        # As this function sometime gets called holding this lock,
        # we must release it and re-acquire it appropriately
        #
        from xen.xend import XendDomain

        lock = True
        try:
            XendDomain.instance().domains_lock.release()
        except:
            lock = False

        try:
            dominfo.waitForDevices()  # Wait for backends to set up
        except Exception, exn:
            log.exception(exn)

        if lock:
            XendDomain.instance().domains_lock.acquire()

        if not paused:
            dominfo.unpause()

        return dominfo
コード例 #34
0
ファイル: P_DataCollect.py プロジェクト: Hearen/OnceServer
 def __init__(self):
     self.domain_instance = XendDomain.instance()
コード例 #35
0
 def _VM_get_all(self):
     refs = [d.get_uuid() for d in XendDomain.instance().list('all') 
             if d.get_uuid() != DOM0_UUID]
     return refs
コード例 #36
0
ファイル: XendCheckpoint.py プロジェクト: a2k2/xen-unstable

        os.read(fd, 1)           # Wait for source to close connection
        
        dominfo.completeRestore(handler.store_mfn, handler.console_mfn)

        #
        # We shouldn't hold the domains_lock over a waitForDevices
        # As this function sometime gets called holding this lock,
        # we must release it and re-acquire it appropriately
        #
        from xen.xend import XendDomain

        lock = True;
        try:
            XendDomain.instance().domains_lock.release()
        except:
            lock = False;

        try:
            dominfo.waitForDevices() # Wait for backends to set up
        except Exception, exn:
            log.exception(exn)

        if lock:
            XendDomain.instance().domains_lock.acquire()

        if not paused:
            dominfo.unpause()

        return dominfo
コード例 #37
0
 def __init__(self):
     SrvDir.__init__(self)
     self.xd = XendDomain.instance()
コード例 #38
0
def lookup(domid):
    info = XendDomain.instance().domain_lookup(domid)
    return info
コード例 #39
0
            if meth_name[0] != '_':
                meth = getattr(self.xenapi, meth_name)
                if callable(meth) and hasattr(meth, 'api'):
                    self.server.register_function(meth, getattr(meth, 'api'))

        self.server.register_instance(XendAPI.XendAPIAsyncProxy(self.xenapi))
                
        # Legacy deprecated xm xmlrpc api
        # --------------------------------------------------------------------

        # Functions in XendDomainInfo
        for name in methods:
            fn = eval("lambda domid, *args: dispatch(domid, '%s', args)"%name)
            self.server.register_function(fn, "xend.domain.%s" % name)

        inst = XendDomain.instance()

        for name in dir(inst):
            fn = getattr(inst, name)
            if name.startswith("domain_") and callable(fn):
                if name not in exclude:
                    self.server.register_function(fn, "xend.domain.%s" % name[7:])

        # Functions in XendPool
        for name in POOL_FUNCS:
            fn = getattr(XendCPUPool, name)
            self.server.register_function(fn, "xend.cpu_pool.%s" % name[5:])

        # Functions in XendNode and XendDmesg
        for type, lst, n in [(XendNode,
                              ['info', 'pciinfo', 'send_debug_keys',
コード例 #40
0
    except Exception, exn:
        log.exception("Can't create directory '/var/lib/xen'")
        raise XendError("Can't create directory '/var/lib/xen'")

    write_exact(fd, SIGNATURE, "could not write guest state file: signature")

    sxprep = dominfo.sxpr()

    if node > -1:
        insert_after(sxprep,'vcpus',['node', str(node)])

    for device_sxp in sxp.children(sxprep, 'device'):
        backend = sxp.child(device_sxp[1], 'backend')
        if backend == None:
            continue
        bkdominfo = XendDomain.instance().domain_lookup_nr(backend[1])
        if bkdominfo == None:
            raise XendError("Could not find backend: %s" % backend[1])
        if bkdominfo.getDomid() == XendDomain.DOM0_ID:
            # Skip for compatibility of checkpoint data format
            continue
        backend[1] = bkdominfo.getName()
        
    config = sxp.to_string(sxprep)

    domain_name = dominfo.getName()
    # Rename the domain temporarily, so that we don't get a name clash if this
    # domain is migrating (live or non-live) to the local host.  Doing such a
    # thing is useful for debugging.
    dominfo.setName('migrating-' + domain_name)
コード例 #41
0
ファイル: image.py プロジェクト: Hearen/OnceServer
    def createDeviceModel(self, restore = False):
        if self.device_model is None:
            return
        if self.pid:
            return
        # Execute device model.
        #todo: Error handling
        args = self.getDeviceModelArgs(restore)
        env = dict(os.environ)
        if self.display:
            env['DISPLAY'] = self.display
        if self.xauthority:
            env['XAUTHORITY'] = self.xauthority
        unique_id = "%i-%i" % (self.vm.getDomid(), time.time())
        sentinel_path = sentinel_path_prefix + unique_id
        sentinel_path_fifo = sentinel_path + '.fifo'
        os.mkfifo(sentinel_path_fifo, 0600)
        sentinel_write = file(sentinel_path_fifo, 'r+')
        self._openSentinel(sentinel_path_fifo)
        self.vm.storeDom("image/device-model-fifo", sentinel_path_fifo)
        xstransact.Mkdir("/local/domain/0/device-model/%i" % self.vm.getDomid())
        xstransact.SetPermissions("/local/domain/0/device-model/%i" % self.vm.getDomid(),
                        { 'dom': self.vm.getDomid(), 'read': True, 'write': True })
        log.info("spawning device models: %s %s", self.device_model, args)
        # keep track of pid and spawned options to kill it later

        self.logfile = "/var/log/xen/qemu-dm-%s.log" %  str(self.vm.info['name_label'])

        # rotate log
        logfile_mode = os.O_WRONLY|os.O_CREAT|os.O_APPEND
        logrotate_count = XendOptions.instance().get_qemu_dm_logrotate_count()
        if logrotate_count > 0:
            logfile_mode |= os.O_TRUNC
            if os.path.exists("%s.%d" % (self.logfile, logrotate_count)):
                os.unlink("%s.%d" % (self.logfile, logrotate_count))
            for n in range(logrotate_count - 1, 0, -1):
                if os.path.exists("%s.%d" % (self.logfile, n)):
                    os.rename("%s.%d" % (self.logfile, n),
                              "%s.%d" % (self.logfile, (n + 1)))
            if os.path.exists(self.logfile):
                os.rename(self.logfile, self.logfile + ".1")

        null = os.open("/dev/null", os.O_RDONLY)
        logfd = os.open(self.logfile, logfile_mode, 0666)
        
        sys.stderr.flush()
        contract = osdep.prefork("%s:%d" %
                                 (self.vm.getName(), self.vm.getDomid()))
        pid = os.fork()
        if pid == 0: #child
            try:
                osdep.postfork(contract)
                os.dup2(null, 0)
                os.dup2(logfd, 1)
                os.dup2(logfd, 2)
                oshelp.close_fds((sentinel_write.fileno(),))
                try:
                    os.execve(self.device_model, args, env)
                except Exception, e:
                    print >>sys.stderr, (
                        'failed to set up fds or execute dm %s: %s' %
                        (self.device_model, utils.exception_string(e)))
                    os._exit(126)
            except:
                os._exit(127)
        else:
            osdep.postfork(contract, abandon=True)
            self.pid = pid
            os.close(null)
            os.close(logfd)
        sentinel_write.close()
        self.vm.storeDom("image/device-model-pid", self.pid)
        log.info("device model pid: %d", self.pid)
        # we would very much prefer not to have a thread here and instead
        #  have a callback but sadly we don't have Twisted in xend
        self.sentinel_thread = thread.start_new_thread(self._sentinel_watch,())
        if self.device_model.find('stubdom-dm') > -1 :
            from xen.xend import XendDomain
            domains = XendDomain.instance()
            domains.domains_lock.release()

            count = 0
            while True:
                orig_state = xstransact.Read("/local/domain/0/device-model/%i/state"
                                    % self.vm.getDomid())
                # This can occur right after start-up
                if orig_state != None:
                    break

                log.debug('createDeviceModel %i: orig_state is None, retrying' % self.vm.getDomid())

                time.sleep(0.1)
                count += 1
                if count > 100:
                    break

            domains.domains_lock.acquire()
コード例 #42
0
def domains(detail=1):
    if detail < 1:
        return XendDomain.instance().list_names()
    else:
        domains = XendDomain.instance().list_sorted()
        return map(lambda dom: fixup_sxpr(dom.sxpr()), domains)
コード例 #43
0
    def createDeviceModel(self, restore=False):
        if self.device_model is None:
            return
        if self.pid:
            return
        # Execute device model.
        #todo: Error handling
        args = self.getDeviceModelArgs(restore)
        env = dict(os.environ)
        if self.display:
            env['DISPLAY'] = self.display
        if self.xauthority:
            env['XAUTHORITY'] = self.xauthority
        unique_id = "%i-%i" % (self.vm.getDomid(), time.time())
        sentinel_path = sentinel_path_prefix + unique_id
        sentinel_path_fifo = sentinel_path + '.fifo'
        os.mkfifo(sentinel_path_fifo, 0600)
        sentinel_write = file(sentinel_path_fifo, 'r+')
        self._openSentinel(sentinel_path_fifo)
        self.vm.storeDom("image/device-model-fifo", sentinel_path_fifo)
        xstransact.Mkdir("/local/domain/0/device-model/%i" %
                         self.vm.getDomid())
        xstransact.SetPermissions(
            "/local/domain/0/device-model/%i" % self.vm.getDomid(), {
                'dom': self.vm.getDomid(),
                'read': True,
                'write': True
            })
        log.info("spawning device models: %s %s", self.device_model, args)
        # keep track of pid and spawned options to kill it later

        self.logfile = "/var/log/xen/qemu-dm-%s.log" % str(
            self.vm.info['name_label'])

        # rotate log
        logfile_mode = os.O_WRONLY | os.O_CREAT | os.O_APPEND
        logrotate_count = XendOptions.instance().get_qemu_dm_logrotate_count()
        if logrotate_count > 0:
            logfile_mode |= os.O_TRUNC
            if os.path.exists("%s.%d" % (self.logfile, logrotate_count)):
                os.unlink("%s.%d" % (self.logfile, logrotate_count))
            for n in range(logrotate_count - 1, 0, -1):
                if os.path.exists("%s.%d" % (self.logfile, n)):
                    os.rename("%s.%d" % (self.logfile, n),
                              "%s.%d" % (self.logfile, (n + 1)))
            if os.path.exists(self.logfile):
                os.rename(self.logfile, self.logfile + ".1")

        null = os.open("/dev/null", os.O_RDONLY)
        logfd = os.open(self.logfile, logfile_mode, 0666)

        sys.stderr.flush()
        contract = osdep.prefork("%s:%d" %
                                 (self.vm.getName(), self.vm.getDomid()))
        pid = os.fork()
        if pid == 0:  #child
            try:
                osdep.postfork(contract)
                os.dup2(null, 0)
                os.dup2(logfd, 1)
                os.dup2(logfd, 2)
                oshelp.close_fds((sentinel_write.fileno(), ))
                try:
                    os.execve(self.device_model, args, env)
                except Exception, e:
                    print >> sys.stderr, (
                        'failed to set up fds or execute dm %s: %s' %
                        (self.device_model, utils.exception_string(e)))
                    os._exit(126)
            except:
                os._exit(127)
        else:
            osdep.postfork(contract, abandon=True)
            self.pid = pid
            os.close(null)
            os.close(logfd)
        sentinel_write.close()
        self.vm.storeDom("image/device-model-pid", self.pid)
        log.info("device model pid: %d", self.pid)
        # we would very much prefer not to have a thread here and instead
        #  have a callback but sadly we don't have Twisted in xend
        self.sentinel_thread = thread.start_new_thread(self._sentinel_watch,
                                                       ())
        if self.device_model.find('stubdom-dm') > -1:
            from xen.xend import XendDomain
            domains = XendDomain.instance()
            domains.domains_lock.release()

            count = 0
            while True:
                orig_state = xstransact.Read(
                    "/local/domain/0/device-model/%i/state" %
                    self.vm.getDomid())
                # This can occur right after start-up
                if orig_state != None:
                    break

                log.debug(
                    'createDeviceModel %i: orig_state is None, retrying' %
                    self.vm.getDomid())

                time.sleep(0.1)
                count += 1
                if count > 100:
                    break

            domains.domains_lock.acquire()
コード例 #44
0
def domain_restore(src):
    info = XendDomain.instance().domain_restore(src)
    return fixup_sxpr(info.sxpr())
コード例 #45
0
def lookup(domid):
    info = XendDomain.instance().domain_lookup_by_name_or_id(domid)
    if not info:
        raise XendInvalidDomain(str(domid))
    return info
コード例 #46
0
ファイル: XendBootloader.py プロジェクト: changliwei/suse_xen
    # for it.
    if os.uname()[0] != 'SunOS' and os.uname()[0] != 'NetBSD':
        tty.setraw(m1)
        os.close(s1)
    else:
        tty.setraw(s1)

    fcntl.fcntl(m1, fcntl.F_SETFL, os.O_NDELAY)

    slavename = ptsname.ptsname(m1)
    dom.storeDom("console/tty", slavename)

    # Release the domain lock here, because we definitely don't want 
    # a stuck bootloader to deny service to other xend clients.
    from xen.xend import XendDomain
    domains = XendDomain.instance()
    domains.domains_lock.release()
    
    (child, m2) = pty.fork()
    if (not child):
        args = [ blexec ]
        if kernel:
            args.append("--kernel=%s" % kernel)
        if ramdisk:
            args.append("--ramdisk=%s" % ramdisk)
        if kernel_args:
            args.append("--args=%s" % kernel_args)
        if quiet:
            args.append("-q")
        args.append("--output=%s" % fifo)
        if blargs:
コード例 #47
0
def domains(detail=1):
    if detail < 1:
        return XendDomain.instance().list_names()
    else:
        domains = XendDomain.instance().list_sorted()
        return map(lambda dom: fixup_sxpr(dom.sxpr()), domains)
コード例 #48
0
    except Exception, exn:
        log.exception("Can't create directory '/var/lib/xen'")
        raise XendError("Can't create directory '/var/lib/xen'")

    write_exact(fd, SIGNATURE, "could not write guest state file: signature")

    sxprep = dominfo.sxpr()

    if node > -1:
        insert_after(sxprep, 'vcpus', ['node', str(node)])

    for device_sxp in sxp.children(sxprep, 'device'):
        backend = sxp.child(device_sxp[1], 'backend')
        if backend == None:
            continue
        bkdominfo = XendDomain.instance().domain_lookup_nr(backend[1])
        if bkdominfo == None:
            raise XendError("Could not find backend: %s" % backend[1])
        if bkdominfo.getDomid() == XendDomain.DOM0_ID:
            # Skip for compatibility of checkpoint data format
            continue
        backend[1] = bkdominfo.getName()

    config = sxp.to_string(sxprep)

    domain_name = dominfo.getName()
    # Rename the domain temporarily, so that we don't get a name clash if this
    # domain is migrating (live or non-live) to the local host.  Doing such a
    # thing is useful for debugging.
    dominfo.setName('migrating-' + domain_name)
コード例 #49
0
def domain_restore(src):
    info = XendDomain.instance().domain_restore(src)
    return fixup_sxpr(info.sxpr())
コード例 #50
0
def domain_create(config):
    info = XendDomain.instance().domain_create(config)
    return fixup_sxpr(info.sxpr())
コード例 #51
0
def domain_restore(src, paused=False):
    info = XendDomain.instance().domain_restore(src, paused)
    return fixup_sxpr(info.sxpr())
コード例 #52
0
ファイル: SrvDomain.py プロジェクト: ryos36/xen-arm
 def __init__(self, dom):
     SrvDir.__init__(self)
     self.dom = dom
     self.xd = XendDomain.instance()
コード例 #53
0
def lookup(domid):
    info = XendDomain.instance().domain_lookup_by_name_or_id(domid)
    if not info:
        raise XendInvalidDomain(str(domid))
    return info