def delete(self):
     log.info("Deleting vnet %s", self.id)
     Brctl.vif_bridge_rem({'bridge': self.bridge, 'vif': self.vnetif})
     Brctl.bridge_del(self.bridge)
     val = vnet_cmd(['vnet.del', self.id])
     xstransact.Remove(self.dbpath)
     return val
Esempio n. 2
0
    def getDeviceDetails(self, config):
        """@see DevController.getDeviceDetails"""

        devid = self.allocateDeviceID()
        inst = int(config.get('pref_instance', -1))
        if inst == -1:
            inst = int(config.get('instance', 0))

        typ    = config.get('type')
        uuid   = config.get('uuid')

        log.info("The domain has a TPM with pref. instance %d and devid %d.",
                 inst, devid)
        back  = { 'pref_instance' : "%i" % inst,
                  'resume'        : "%s" % (self.vm.getResume()) }
        if typ:
            back['type'] = typ
        if uuid:
            back['uuid'] = uuid

            data = self.vm.info['devices'].get(uuid)
            if data:
                other = data[1].get('other_config')
                if type(other) == dict:
                    for key, item in other.items():
                        back['oc_' + key] = item

        front = { 'handle' : "%i" % devid }

        return (devid, back, front)
Esempio n. 3
0
    def migrate(self, deviceConfig, network, dst, step, domName):
        """@see DevContoller.migrate"""
        if network:
            tool = xoptions.get_external_migration_tool()
            if tool != '':
                log.info("Request to network-migrate device to %s. step=%d.",
                         dst, step)

                if step == DEV_MIGRATE_TEST:
                    """Assuming for now that everything is ok and migration
                       with the given tool can proceed.
                    """
                    return 0
                else:
                    fd = os.popen("%s -type vtpm -step %d -host %s -domname %s" %
                                  (tool, step, dst, domName),
                                  'r')
                    for line in fd.readlines():
                        mo = re.search('Error', line)
                        if mo:
                            raise XendError("vtpm: Fatal error in migration step %d: %s" %
                                            (step, line))
                    return 0
            else:
                log.debug("External migration tool not in configuration.")
                return -1
        return 0
Esempio n. 4
0
    def __init__(self, maxpolicies):
        """ Create a management class for managing the system's
            policies.

            @param maxpolicies: The max. number of policies allowed
                                on the system (currently '1')
        """
        self.maxpolicies = maxpolicies
        self.policies = {}
        self.xsobjs = {}

        act_pol_name = self.get_hv_loaded_policy_name()
        initialize()

        ref = uuid.createString()
        try:
            self.xsobjs[ref] = ACMPolicy(name=act_pol_name, ref=ref)
            self.policies[ref] = (act_pol_name, xsconstants.ACM_POLICY_ID)
        except Exception, e:
            log.error("Could not find XML representation of policy '%s': "
                      "%s" % (act_pol_name, e))
            rc, errors, acmpol_def = ACMPolicy.force_default_policy()
            if rc == xsconstants.XSERR_SUCCESS:
                self.xsobjs[ref] = acmpol_def
                self.policies[ref] = (acmpol_def.get_name(),
                                      xsconstants.ACM_POLICY_ID)
                log.info("Switched to DEFAULT policy.")
Esempio n. 5
0
 def _sentinel_watch(self):
     log.info("waiting for sentinel_fifo")
     try: self.sentinel_fifo.read(1)
     except OSError, e: pass
     self.sentinel_lock.acquire()
     if self.pid:
         try:
             (p,st) = os.waitpid(self.pid, os.WNOHANG)
             if p == self.pid:
                 message = oshelp.waitstatus_description(st)
             else:
                 # obviously it is malfunctioning, kill it now
                 try:
                     os.kill(self.pid, signal.SIGKILL)
                     message = "malfunctioning (closed sentinel), killed"
                 except:
                     message = "malfunctioning or died ?"
             message = "pid %d: %s" % (self.pid, message)
         except Exception, e:
             message = "waitpid failed: %s" % utils.exception_string(e)
         message = "device model failure: %s" % message
         try: message += "; see %s " % self.logfile
         except: pass
         self._dmfailed(message)
         self.pid = None
Esempio n. 6
0
 def delete(self):
     log.info("Deleting vnet %s", self.id)
     Brctl.vif_bridge_rem({'bridge': self.bridge, 'vif': self.vnetif})
     Brctl.bridge_del(self.bridge)
     val = vnet_cmd(['vnet.del', self.id])
     xstransact.Remove(self.dbpath)
     return val
Esempio n. 7
0
 def _sentinel_watch(self):
     log.info("waiting for sentinel_fifo")
     try: self.sentinel_fifo.read(1)
     except OSError, e: pass
     self.sentinel_lock.acquire()
     if self.pid:
         try:
             (p,st) = os.waitpid(self.pid, os.WNOHANG)
             if p == self.pid:
                 message = oshelp.waitstatus_description(st)
             else:
                 # obviously it is malfunctioning, kill it now
                 try:
                     os.kill(self.pid, signal.SIGKILL)
                     message = "malfunctioning (closed sentinel), killed"
                 except:
                     message = "malfunctioning or died ?"
             message = "pid %d: %s" % (self.pid, message)
         except Exception, e:
             message = "waitpid failed: %s" % utils.exception_string(e)
         message = "device model failure: %s" % message
         try: message += "; see %s " % self.logfile
         except: pass
         self._dmfailed(message)
         self.pid = None
Esempio n. 8
0
    def getDeviceDetails(self, config):
        """@see DevController.getDeviceDetails"""

        devid = self.allocateDeviceID()
        inst = int(config.get("pref_instance", -1))
        if inst == -1:
            inst = int(config.get("instance", 0))

        typ = config.get("type")
        uuid = config.get("uuid")

        log.info("The domain has a TPM with pref. instance %d and devid %d.", inst, devid)
        back = {"pref_instance": "%i" % inst, "resume": "%s" % (self.vm.getResume())}
        if typ:
            back["type"] = typ
        if uuid:
            back["uuid"] = uuid

            data = self.vm.info["devices"].get(uuid)
            if data:
                other = data[1].get("other_config")
                if type(other) == dict:
                    for key, item in other.items():
                        back["oc_" + key] = item

        front = {"handle": "%i" % devid}

        return (devid, back, front)
Esempio n. 9
0
    def signalDeviceModel(self, cmd, ret, par = None):
        if self.device_model is None:
            return
        # Signal the device model to for action
        if cmd is '' or ret is '':
            raise VmError('need valid command and result when signal device model')

        orig_state = xstransact.Read("/local/domain/0/device-model/%i/state"
                                % self.vm.getDomid())

        if par is not None:
            xstransact.Store("/local/domain/0/device-model/%i"
                             % self.vm.getDomid(), ('parameter', par))

        xstransact.Store("/local/domain/0/device-model/%i"
                         % self.vm.getDomid(), ('command', cmd))
        # Wait for confirmation.  Could do this with a watch but we'd
        # still end up spinning here waiting for the watch to fire. 
        state = ''
        count = 0
        while state != ret:
            state = xstransact.Read("/local/domain/0/device-model/%i/state"
                                    % self.vm.getDomid())
            time.sleep(0.1)
            count += 1
            if count > 100:
                raise VmError('Timed out waiting for device model action')

        #resotre orig state
        xstransact.Store("/local/domain/0/device-model/%i"
                         % self.vm.getDomid(), ('state', orig_state))
        log.info("signalDeviceModel:restore dm state to %s", orig_state)
    def __init__(self, maxpolicies):
        """ Create a management class for managing the system's
            policies.

            @param maxpolicies: The max. number of policies allowed
                                on the system (currently '1')
        """
        self.maxpolicies = maxpolicies
        self.policies = {}
        self.xsobjs = {}

        act_pol_name = self.get_hv_loaded_policy_name()
        initialize()

        ref = uuid.createString()
        try:
            self.xsobjs[ref] = ACMPolicy(name=act_pol_name, ref=ref)
            self.policies[ref] = (act_pol_name, xsconstants.ACM_POLICY_ID)
        except Exception, e:
            log.error("Could not find XML representation of policy '%s': "
                      "%s" % (act_pol_name,e))
            rc, errors, acmpol_def = ACMPolicy.force_default_policy()
            if rc == xsconstants.XSERR_SUCCESS:
                self.xsobjs[ref] = acmpol_def
                self.policies[ref] = (acmpol_def.get_name(),
                                      xsconstants.ACM_POLICY_ID)
                log.info("Switched to DEFAULT policy.")
Esempio n. 11
0
def _loadConfig(servers, root, reload):
    if xoptions.get_xend_http_server():
        servers.add(HttpServer(root,
                               xoptions.get_xend_address(),
                               xoptions.get_xend_port()))
    if  xoptions.get_xend_unix_server():
        path = xoptions.get_xend_unix_path()
        log.info('unix path=' + path)
        servers.add(UnixHttpServer(root, path))

    api_cfg = xoptions.get_xen_api_server()
    if api_cfg:
        try:
            for server_cfg in api_cfg:
                # Parse the xen-api-server config
                
                ssl_key_file = None
                ssl_cert_file = None
                auth_method = XendAPI.AUTH_NONE
                hosts_allowed = None
                
                host_addr = server_cfg[0].split(':', 1)
                if len(host_addr) == 1:
                    if host_addr[0].lower() == 'unix':
                        use_tcp = False
                        host = 'localhost'
                        port = 0
                    else:
                        use_tcp = True
                        host = ''
                        port = int(host_addr[0])
                else:
                    use_tcp = True
                    host = str(host_addr[0])
                    port = int(host_addr[1])

                if len(server_cfg) > 1:
                    if server_cfg[1] in [XendAPI.AUTH_PAM, XendAPI.AUTH_NONE]:
                        auth_method = server_cfg[1]

                if len(server_cfg) > 2 and len(server_cfg[2]):
                    hosts_allowed = map(re.compile, server_cfg[2].split(' '))

                if len(server_cfg) > 4:
                    # SSL key and cert file
                    ssl_key_file = server_cfg[3]
                    ssl_cert_file = server_cfg[4]


                servers.add(XMLRPCServer(auth_method, True, use_tcp = use_tcp,
                                         ssl_key_file = ssl_key_file,
                                         ssl_cert_file = ssl_cert_file,
                                         host = host, port = port,
                                         path = XEN_API_SOCKET,
                                         hosts_allowed = hosts_allowed))

        except (ValueError, TypeError), exn:
            log.exception('Xen API Server init failed')
            log.error('Xen-API server configuration %s is invalid.', api_cfg)
Esempio n. 12
0
 def recover_migrate(self, deviceConfig, network, dst, step, domName):
     """@see DevContoller.recover_migrate"""
     if network:
         tool = xoptions.get_external_migration_tool()
         if tool != "":
             log.info("Request to recover network-migrated device. last good step=%d.", step)
             fd = os.popen("%s -type vtpm -step %d -host %s -domname %s -recover" % (tool, step, dst, domName), "r")
     return 0
Esempio n. 13
0
    def configure(self, vmConfig):
        ImageHandler.configure(self, vmConfig)

        self.loader = vmConfig['platform'].get('loader')

        info = xc.xeninfo()
        if 'hvm' not in info['xen_caps']:
            raise HVMRequired()

        xen_platform_pci = int(vmConfig['platform'].get('xen_platform_pci', 1))
        rtc_timeoffset = vmConfig['platform'].get('rtc_timeoffset')

        if not self.display:
            self.display = ''

        store_dmargs = [
            x for x in self.dmargs if x not in ['-sdl', '-disable-opengl']
        ]
        try:
            midx = store_dmargs.index('-monitor')
            store_dmargs[midx + 1] = 'pty'
        except ValueError:
            pass
        self.vm.storeVm(("image/dmargs", " ".join(store_dmargs)),
                        ("image/device-model", self.device_model),
                        ("image/display", self.display))
        self.vm.permissionsVm("image/dmargs", {
            'dom': self.vm.getDomid(),
            'read': True
        })

        if xen_platform_pci == 0:
            disable_pf = 1
            log.info("No need to create platform device.[domid:%d]",
                     self.vm.getDomid())
        else:
            disable_pf = 0
            log.info("Need to create platform device.[domid:%d]",
                     self.vm.getDomid())

        xstransact.Store(
            "/local/domain/0/device-model/%i" % self.vm.getDomid(),
            ('disable_pf', disable_pf))
        self.vm.storeVm(("rtc/timeoffset", rtc_timeoffset))
        self.vm.permissionsVm("rtc/timeoffset", {
            'dom': self.vm.getDomid(),
            'read': True
        })

        self.apic = int(vmConfig['platform'].get('apic', 0))
        self.acpi = int(vmConfig['platform'].get('acpi', 0))
        self.guest_os_type = vmConfig['platform'].get('guest_os_type')
        self.memory_sharing = int(vmConfig['memory_sharing'])
        try:
            xc.dom_set_memshr(self.vm.getDomid(), self.memory_sharing)
        except:
            pass
Esempio n. 14
0
    def getDeviceDetails(self, config):
        """@see DevController.getDeviceDetails"""

        back = {'ssa': "%i" % ssa_default}
        devid = 1
        front = {'virtual-device': "%i" % devid}
        log.info('kpp back :%s', back)
        log.info('kpp front:%s', front)
        return (devid, back, front)
Esempio n. 15
0
    def getDeviceDetails(self,config):

        back = {}
        front = {}
        devid = 977
        front = { 'virtual-device' : "%i" % devid }
        log.info('sback :%s',back)
        log.info('sfront:%s',front)
        return (devid, back, front)
Esempio n. 16
0
    def getDeviceDetails(self, config):
        """@see DevController.getDeviceDetails"""

        back = {}
        front = {}
        devid = 1
        log.info('fb back :%s', back)
        log.info('fb front:%s', front)
        return (devid, back, front)
Esempio n. 17
0
    def getDeviceDetails(self,config):
        """@see DevController.getDeviceDetails"""

        back = {}
        front = {}
        devid = 1
        log.info('fb back :%s',back)
	log.info('fb front:%s',front)
        return (devid, back, front)
Esempio n. 18
0
    def getDeviceDetails(self, config):

        back = {}
        front = {}
        devid = 977
        front = {'virtual-device': "%i" % devid}
        log.info('sback :%s', back)
        log.info('sfront:%s', front)
        return (devid, back, front)
Esempio n. 19
0
    def getDeviceDetails(self, config):
        """@see DevController.getDeviceDetails"""

        back = {"ssa": "%i" % ssa_default}
        devid = 1
        front = {"virtual-device": "%i" % devid}
        log.info("kpp back :%s", back)
        log.info("kpp front:%s", front)
        return (devid, back, front)
Esempio n. 20
0
 def recover_migrate(self, deviceConfig, network, dst, step, domName):
     """@see DevContoller.recover_migrate"""
     if network:
         tool = xoptions.get_external_migration_tool()
         if tool != '':
             log.info("Request to recover network-migrated device. last good step=%d.",
                      step)
             fd = os.popen("%s -type vtpm -step %d -host %s -domname %s -recover" %
                           (tool, step, dst, domName),
                           'r')
     return 0
Esempio n. 21
0
 def domain_pause(self, domid):
     """Pause domain execution."""
     try:
         dominfo = self.domain_lookup_by_name_or_id_nr(domid)
         if not dominfo:
             raise XendInvalidDomain(str(domid))
         log.info("Domain %s (%d) paused.", dominfo.getName(),
                  dominfo.getDomid())
         return dominfo.pause()
     except Exception, ex:
         raise XendError(str(ex))
Esempio n. 22
0
def slurp(infile):
    while 1:
        line = infile.readline()
        if line == "":
            break
        else:
            line = line.strip()
            m = re.match(r"^ERROR: (.*)", line)
            if m is None:
                log.info('%s', line)
            else:
                log.error('%s', m.group(1))
Esempio n. 23
0
    def signalDeviceModel(self, cmd, ret, par = None, timeout = True):
        if self.device_model is None:
            return
        # Signal the device model to for action
        if cmd is '' or ret is '':
            raise VmError('need valid command and result when signal device model')

        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('signalDeviceModel: orig_state is None, retrying')

            time.sleep(0.1)
            count += 1
            if count < 100:
                continue

            raise VmError('Device model isn\'t ready for commands')

        if par is not None:
            xstransact.Store("/local/domain/0/device-model/%i"
                             % self.vm.getDomid(), ('parameter', par))

        xstransact.Store("/local/domain/0/device-model/%i"
                         % self.vm.getDomid(), ('command', cmd))
        # Wait for confirmation.  Could do this with a watch but we'd
        # still end up spinning here waiting for the watch to fire. 
        state = ''
        count = 0
        while state != ret:
            state = xstransact.Read("/local/domain/0/device-model/%i/state"
                                    % self.vm.getDomid())
            if state == 'error':
                msg = ("The device model returned an error: %s"
                      % xstransact.Read("/local/domain/0/device-model/%i/error"
                                        % self.vm.getDomid()))
                raise VmError(msg)

            time.sleep(0.1)
            if timeout:
                count += 1
                if count > 100:
                    raise VmError('Timed out waiting for device model action')

        #resotre orig state
        xstransact.Store("/local/domain/0/device-model/%i"
                         % self.vm.getDomid(), ('state', orig_state))
        log.info("signalDeviceModel:restore dm state to %s", orig_state)
def slurp(infile):
    while 1:
        line = infile.readline()
        if line == "":
            break
        else:
            line = line.strip()
            m = re.match(r"^ERROR: (.*)", line)
            if m is None:
                log.info('%s', line)
            else:
                log.error('%s', m.group(1))
Esempio n. 25
0
    def run(self):
        authmsg = (self.auth == XendAPI.AUTH_NONE and 
                   "; authentication has been disabled for this server." or
                   ".")

        try:
            if self.use_tcp:
                using_ssl = self.ssl_key_file and self.ssl_cert_file

                log.info("Opening %s XML-RPC server on %s%d%s",
                         using_ssl and 'HTTPS' or 'TCP',
                         self.host and '%s:' % self.host or
                         'all interfaces, port ',
                         self.port, authmsg)
#                 #sync vms and hosts' status send message
#                 from xen.xend import RunSend
#                 RunSend.main()
#                 
#                 #the follow file was import by shixisheng_cxx
#                 from xen.xend import P_DataCollect
#                 P_DataCollect.main()
                

                if using_ssl:
                    if not ssl_enabled:
                        raise ValueError("pyOpenSSL not installed. "
                                         "Unable to start HTTPS XML-RPC server")
                    self.server = SSLXMLRPCServer(
                        (self.host, self.port),
                        self.hosts_allowed,
                        self.xenapi is not None,
                        logRequests = False,
                        ssl_key_file = self.ssl_key_file,
                        ssl_cert_file = self.ssl_cert_file)
                else:
                    self.server = TCPXMLRPCServer(
                        (self.host, self.port),
                        self.hosts_allowed,
                        self.xenapi is not None,
                        logRequests = False)

            else:
                log.info("Opening Unix domain socket XML-RPC server on %s%s",
                         self.path, authmsg)
                self.server = UnixXMLRPCServer(self.path, self.hosts_allowed,
                                               self.xenapi is not None,
                                               logRequests = False)
        except socket.error, exn:
            log.error('Cannot start server: %s!', exn.args[1])
            ready = True
            running = False
            return
Esempio n. 26
0
 def getDeviceDetails(self, config):
     log.debug('vbfs config=' + sxp.to_string(config))
     luns = sxp.child_value(config, 'luns')
     if not luns:
         log.debug('vbfs: luns param not set')
         raise VmError('luns param not set')
     back = {'luns': luns}
     #        devid = self.allocateDeviceID()
     devid = 1
     front = {'virtual-device': "%i" % devid}
     log.info('bfsback :%s', back)
     log.info('bfsfront:%s', front)
     return (devid, back, front)
Esempio n. 27
0
 def getDeviceDetails(self, config):
     log.debug("vbfs config=" + sxp.to_string(config))
     luns = sxp.child_value(config, "luns")
     if not luns:
         log.debug("vbfs: luns param not set")
         raise VmError("luns param not set")
     back = {"luns": luns}
     #        devid = self.allocateDeviceID()
     devid = 1
     front = {"virtual-device": "%i" % devid}
     log.info("bfsback :%s", back)
     log.info("bfsfront:%s", front)
     return (devid, back, front)
Esempio n. 28
0
    def signalDeviceModel(self, cmd, ret, par=None):
        if self.device_model is None:
            return
        # Signal the device model to for action
        if cmd is '' or ret is '':
            raise VmError(
                'need valid command and result when signal device model')

        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('signalDeviceModel: orig_state is None, retrying')

            time.sleep(0.1)
            count += 1
            if count < 100:
                continue

            raise VmError('Device model isn\'t ready for commands')

        if par is not None:
            xstransact.Store(
                "/local/domain/0/device-model/%i" % self.vm.getDomid(),
                ('parameter', par))

        xstransact.Store(
            "/local/domain/0/device-model/%i" % self.vm.getDomid(),
            ('command', cmd))
        # Wait for confirmation.  Could do this with a watch but we'd
        # still end up spinning here waiting for the watch to fire.
        state = ''
        count = 0
        while state != ret:
            state = xstransact.Read("/local/domain/0/device-model/%i/state" %
                                    self.vm.getDomid())
            time.sleep(0.1)
            count += 1
            if count > 100:
                raise VmError('Timed out waiting for device model action')

        #resotre orig state
        xstransact.Store(
            "/local/domain/0/device-model/%i" % self.vm.getDomid(),
            ('state', orig_state))
        log.info("signalDeviceModel:restore dm state to %s", orig_state)
Esempio n. 29
0
    def run(self, status):
        try:
            log.info("Xend Daemon started")

            xc = xen.lowlevel.xc.xc()
            xinfo = xc.xeninfo()
            log.info("Xend changeset: %s.", xinfo['xen_changeset'])
            del xc

            try:
                from xen import VERSION
                log.info("Xend version: %s", VERSION)
            except ImportError:
                log.info("Xend version: Unknown.")

            relocate.listenRelocation()
            servers = SrvServer.create()
            servers.start(status)
            del servers

        except Exception, ex:
            print >> sys.stderr, 'Exception starting xend:', ex
            if XEND_DEBUG:
                traceback.print_exc()
            log.exception("Exception starting xend (%s)" % ex)
            if status:
                status.write('1')
                status.close()
            sys.exit(1)
Esempio n. 30
0
    def run(self, status):
        try:
            log.info("Xend Daemon started")

            xc = xen.lowlevel.xc.xc()
            xinfo = xc.xeninfo()
            log.info("Xend changeset: %s.", xinfo['xen_changeset'])
            del xc

            try:
                from xen import VERSION
                log.info("Xend version: %s", VERSION)
            except ImportError:
                log.info("Xend version: Unknown.")

            relocate.listenRelocation()
            servers = SrvServer.create()
            servers.start(status)
            del servers
            
        except Exception, ex:
            print >>sys.stderr, 'Exception starting xend:', ex
            if XEND_DEBUG:
                traceback.print_exc()
            log.exception("Exception starting xend (%s)" % ex)
            if status:
                status.write('1')
                status.close()
            sys.exit(1)
Esempio n. 31
0
 def recover_migrate(self, deviceConfig, network, dst, step, domName):
     """ Recover from device migration. The given step was the
         last one that was successfully executed.
     """
     tool = xoptions.get_external_migration_tool()
     if tool:
         log.info("Calling external migration tool")
         fd = os.popen("%s -type %s -step %d -host %s -domname %s -recover" %
                       (tool, self.deviceClass, step, dst, domName))
         for line in fd:
             log.info(line.rstrip())
         rc = fd.close()
         if rc:
             raise VmError('Migration tool returned %d' % (rc >> 8))
     return 0
Esempio n. 32
0
    def getDeviceDetails(self, config):
        """@see DevController.getDeviceDetails"""

        devid = self.allocateDeviceID()
        inst = int(sxp.child_value(config, 'pref_instance', '-1'))
        if inst == -1:
            inst = int(sxp.child_value(config, 'instance' , '0'))

        log.info("The domain has a TPM with instance %d and devid %d.",
                 inst, devid)
        back  = { 'pref_instance' : "%i" % inst,
                  'resume'        : "%s" % (self.vm.getResume()) }
        front = { 'handle' : "%i" % devid }

        return (devid, back, front)
 def recover_migrate(self, deviceConfig, network, dst, step, domName):
     """ Recover from device migration. The given step was the
         last one that was successfully executed.
     """
     tool = xoptions.get_external_migration_tool()
     if tool:
         log.info("Calling external migration tool")
         fd = os.popen("%s -type %s -step %d -host %s -domname %s -recover" %
                       (tool, self.deviceClass, step, dst, domName))
         for line in fd:
             log.info(line.rstrip())
         rc = fd.close()
         if rc:
             raise VmError('Migration tool returned %d' % (rc >> 8))
     return 0
Esempio n. 34
0
    def configure(self, vmConfig):
        ImageHandler.configure(self, vmConfig)

        self.loader = vmConfig['platform'].get('loader')

        info = xc.xeninfo()
        if 'hvm' not in info['xen_caps']:
            raise HVMRequired()

        xen_platform_pci = int(vmConfig['platform'].get('xen_platform_pci',1))
        rtc_timeoffset = vmConfig['platform'].get('rtc_timeoffset')

        if not self.display :
            self.display = ''

        store_dmargs = [ x for x in self.dmargs
                         if x not in ['-sdl', '-disable-opengl'] ]
        try :
            midx = store_dmargs.index('-monitor')
            store_dmargs[midx + 1] = 'pty'
        except ValueError :
            pass
        self.vm.storeVm(("image/dmargs", " ".join(store_dmargs)),
                        ("image/device-model", self.device_model),
                        ("image/display", self.display))
        self.vm.permissionsVm("image/dmargs", { 'dom': self.vm.getDomid(), 'read': True } )

        if xen_platform_pci == 0:
            disable_pf = 1
            log.info("No need to create platform device.[domid:%d]", self.vm.getDomid())
        else:
            disable_pf = 0
            log.info("Need to create platform device.[domid:%d]", self.vm.getDomid())

        xstransact.Store("/local/domain/0/device-model/%i"%self.vm.getDomid(),
                                      ('disable_pf', disable_pf))
        self.vm.storeVm(("rtc/timeoffset", rtc_timeoffset))
        self.vm.permissionsVm("rtc/timeoffset", { 'dom': self.vm.getDomid(), 'read': True } )

        self.apic = int(vmConfig['platform'].get('apic', 0))
        self.acpi = int(vmConfig['platform'].get('acpi', 0))
        self.extid = int(vmConfig['platform'].get('extid', 0))
        self.guest_os_type = vmConfig['platform'].get('guest_os_type')
        self.memory_sharing = int(vmConfig['memory_sharing'])
        try:
            xc.dom_set_memshr(self.vm.getDomid(), self.memory_sharing)
        except:
            pass
Esempio n. 35
0
 def createXenPaging(self):
     if not self.vm.info.is_hvm():
         return
     if self.actmem == "0":
         return
     if self.xenpaging_pid:
         return
     xenpaging_bin = auxbin.pathTo("xenpaging")
     args = [xenpaging_bin]
     args = args + ([ "-f", "/var/lib/xen/xenpaging/%s.%d.paging" % (str(self.vm.info['name_label']), self.vm.getDomid())])
     if self.xenpaging_extra:
         args = args + (self.xenpaging_extra)
     args = args + ([ "-d", "%d" % self.vm.getDomid()])
     self.xenpaging_logfile = "/var/log/xen/xenpaging-%s.log" %  str(self.vm.info['name_label'])
     logfile_mode = os.O_WRONLY|os.O_CREAT|os.O_APPEND|os.O_TRUNC
     null = os.open("/dev/null", os.O_RDONLY)
     try:
         os.unlink(self.xenpaging_logfile)
     except:
         pass
     logfd = os.open(self.xenpaging_logfile, logfile_mode, 0644)
     sys.stderr.flush()
     contract = osdep.prefork("%s:%d" % (self.vm.getName(), self.vm.getDomid()))
     xenpaging_pid = os.fork()
     if xenpaging_pid == 0: #child
         try:
             osdep.postfork(contract)
             os.dup2(null, 0)
             os.dup2(logfd, 1)
             os.dup2(logfd, 2)
             try:
                 env = dict(os.environ)
                 log.info("starting %s" % args)
                 os.execve(xenpaging_bin, args, env)
             except Exception, e:
                 log.warn('failed to execute xenpaging: %s' % utils.exception_string(e))
                 os._exit(126)
         except:
             log.warn("starting xenpaging failed")
             os._exit(127)
     else:
         osdep.postfork(contract, abandon=True)
         self.xenpaging_pid = xenpaging_pid
         os.close(null)
         os.close(logfd)
     self.vm.storeDom("xenpaging/xenpaging-pid", self.xenpaging_pid)
     self.vm.storeDom("memory/target-tot_pages", int(self.actmem) * 1024)
Esempio n. 36
0
    def configure(self, vmConfig):
        ImageHandler.configure(self, vmConfig)

        self.loader = vmConfig["platform"].get("loader")

        info = xc.xeninfo()
        if "hvm" not in info["xen_caps"]:
            raise HVMRequired()

        xen_platform_pci = int(vmConfig["platform"].get("xen_platform_pci", 1))
        rtc_timeoffset = vmConfig["platform"].get("rtc_timeoffset")

        if not self.display:
            self.display = ""

        store_dmargs = [x for x in self.dmargs if x not in ["-sdl", "-disable-opengl"]]
        try:
            midx = store_dmargs.index("-monitor")
            store_dmargs[midx + 1] = "pty"
        except ValueError:
            pass
        self.vm.storeVm(
            ("image/dmargs", " ".join(store_dmargs)),
            ("image/device-model", self.device_model),
            ("image/display", self.display),
        )
        self.vm.permissionsVm("image/dmargs", {"dom": self.vm.getDomid(), "read": True})

        if xen_platform_pci == 0:
            disable_pf = 1
            log.info("No need to create platform device.[domid:%d]", self.vm.getDomid())
        else:
            disable_pf = 0
            log.info("Need to create platform device.[domid:%d]", self.vm.getDomid())

        xstransact.Store("/local/domain/0/device-model/%i" % self.vm.getDomid(), ("disable_pf", disable_pf))
        self.vm.storeVm(("rtc/timeoffset", rtc_timeoffset))
        self.vm.permissionsVm("rtc/timeoffset", {"dom": self.vm.getDomid(), "read": True})

        self.apic = int(vmConfig["platform"].get("apic", 0))
        self.acpi = int(vmConfig["platform"].get("acpi", 0))
        self.guest_os_type = vmConfig["platform"].get("guest_os_type")
        self.memory_sharing = int(vmConfig["memory_sharing"])
        try:
            xc.dom_set_memshr(self.vm.getDomid(), self.memory_sharing)
        except:
            pass
Esempio n. 37
0
 def createXenPaging(self):
     if not self.vm.info.is_hvm():
         return
     if self.actmem == "0":
         return
     if self.xenpaging_pid:
         return
     xenpaging_bin = auxbin.pathTo("xenpaging")
     args = [xenpaging_bin]
     args = args + ([ "-f", "/var/lib/xen/xenpaging/%s.%d.paging" % (str(self.vm.info['name_label']), self.vm.getDomid())])
     if self.xenpaging_extra:
         args = args + (self.xenpaging_extra)
     args = args + ([ "-d", "%d" % self.vm.getDomid()])
     self.xenpaging_logfile = "/var/log/xen/xenpaging-%s.log" %  str(self.vm.info['name_label'])
     logfile_mode = os.O_WRONLY|os.O_CREAT|os.O_APPEND|os.O_TRUNC
     null = os.open("/dev/null", os.O_RDONLY)
     try:
         os.unlink(self.xenpaging_logfile)
     except:
         pass
     logfd = os.open(self.xenpaging_logfile, logfile_mode, 0644)
     sys.stderr.flush()
     contract = osdep.prefork("%s:%d" % (self.vm.getName(), self.vm.getDomid()))
     xenpaging_pid = os.fork()
     if xenpaging_pid == 0: #child
         try:
             osdep.postfork(contract)
             os.dup2(null, 0)
             os.dup2(logfd, 1)
             os.dup2(logfd, 2)
             try:
                 env = dict(os.environ)
                 log.info("starting %s" % args)
                 os.execve(xenpaging_bin, args, env)
             except Exception, e:
                 log.warn('failed to execute xenpaging: %s' % utils.exception_string(e))
                 os._exit(126)
         except:
             log.warn("starting xenpaging failed")
             os._exit(127)
     else:
         osdep.postfork(contract, abandon=True)
         self.xenpaging_pid = xenpaging_pid
         os.close(null)
         os.close(logfd)
     self.vm.storeDom("xenpaging/xenpaging-pid", self.xenpaging_pid)
     self.vm.storeDom("memory/target-tot_pages", int(self.actmem) * 1024)
Esempio n. 38
0
        def saveInputHandler(line, tochild):
            log.debug("In saveInputHandler %s", line)
            if line == "suspend":
                log.debug("Suspending %d ...", dominfo.getDomid())
                dominfo.shutdown("suspend")
                dominfo.waitForSuspend()
            if line in ("suspend", "suspended"):
                dominfo.migrateDevices(network, dst, DEV_MIGRATE_STEP2, domain_name)
                log.info("Domain %d suspended.", dominfo.getDomid())
                dominfo.migrateDevices(network, dst, DEV_MIGRATE_STEP3, domain_name)
                if hvm:
                    dominfo.image.saveDeviceModel()

            if line == "suspend":
                tochild.write("done\n")
                tochild.flush()
                log.debug("Written done")
Esempio n. 39
0
    def getDeviceDetails(self, config):
        """@see DevController.getDeviceDetails"""

        devid = self.allocateDeviceID()
        inst = int(sxp.child_value(config, 'pref_instance', '-1'))
        if inst == -1:
            inst = int(sxp.child_value(config, 'instance', '0'))

        log.info("The domain has a TPM with instance %d and devid %d.", inst,
                 devid)
        back = {
            'pref_instance': "%i" % inst,
            'resume': "%s" % (self.vm.getResume())
        }
        front = {'handle': "%i" % devid}

        return (devid, back, front)
Esempio n. 40
0
    def run(self):
        authmsg = (self.auth == XendAPI.AUTH_NONE
                   and "; authentication has been disabled for this server."
                   or ".")

        try:
            if self.use_tcp:
                using_ssl = self.ssl_key_file and self.ssl_cert_file

                log.info(
                    "Opening %s XML-RPC server on %s%d%s",
                    using_ssl and 'HTTPS' or 'TCP',
                    self.host and '%s:' % self.host or 'all interfaces, port ',
                    self.port, authmsg)

                if using_ssl:
                    if not ssl_enabled:
                        raise ValueError(
                            "pyOpenSSL not installed. "
                            "Unable to start HTTPS XML-RPC server")
                    self.server = SSLXMLRPCServer(
                        (self.host, self.port),
                        self.hosts_allowed,
                        self.xenapi is not None,
                        logRequests=False,
                        ssl_key_file=self.ssl_key_file,
                        ssl_cert_file=self.ssl_cert_file)
                else:
                    self.server = TCPXMLRPCServer((self.host, self.port),
                                                  self.hosts_allowed,
                                                  self.xenapi is not None,
                                                  logRequests=False)

            else:
                log.info("Opening Unix domain socket XML-RPC server on %s%s",
                         self.path, authmsg)
                self.server = UnixXMLRPCServer(self.path,
                                               self.hosts_allowed,
                                               self.xenapi is not None,
                                               logRequests=False)
        except socket.error, exn:
            log.error('Cannot start server: %s!', exn.args[1])
            ready = True
            running = False
            return
    def __acm_init(self):
        act_pol_name = self.get_hv_loaded_policy_name()
        initialize()

        ref = uuid.createString()
        try:
            self.xsobjs[ref] = ACMPolicy(name=act_pol_name, ref=ref)
            self.policies[ref] = (act_pol_name, xsconstants.ACM_POLICY_ID)
            self.xsobjs[ref].validate_enforced_policy_hash()
        except Exception, e:
            log.error("Could not find XML representation of policy '%s': "
                      "%s" % (act_pol_name,e))
            rc, errors, acmpol_def = ACMPolicy.force_default_policy(ref)
            if rc == xsconstants.XSERR_SUCCESS:
                self.xsobjs[ref] = acmpol_def
                self.policies[ref] = (acmpol_def.get_name(),
                                      xsconstants.ACM_POLICY_ID)
                log.info("Switched to DEFAULT policy.")
Esempio n. 42
0
    def __acm_init(self):
        act_pol_name = self.get_hv_loaded_policy_name()
        initialize()

        ref = uuid.createString()
        try:
            self.xsobjs[ref] = ACMPolicy(name=act_pol_name, ref=ref)
            self.policies[ref] = (act_pol_name, xsconstants.ACM_POLICY_ID)
            self.xsobjs[ref].validate_enforced_policy_hash()
        except Exception, e:
            log.error("Could not find XML representation of policy '%s': "
                      "%s" % (act_pol_name, e))
            rc, errors, acmpol_def = ACMPolicy.force_default_policy(ref)
            if rc == xsconstants.XSERR_SUCCESS:
                self.xsobjs[ref] = acmpol_def
                self.policies[ref] = (acmpol_def.get_name(),
                                      xsconstants.ACM_POLICY_ID)
                log.info("Switched to DEFAULT policy.")
Esempio n. 43
0
def create():
    root = SrvDir()
    root.putChild('xend', SrvRoot())
    servers = XendServers()
    if xroot.get_xend_http_server():
        servers.add(
            HttpServer(root, xroot.get_xend_address(), xroot.get_xend_port()))
    if xroot.get_xend_unix_server():
        path = xroot.get_xend_unix_path()
        log.info('unix path=' + path)
        servers.add(UnixHttpServer(root, path))

    if xroot.get_xend_tcp_xmlrpc_server():
        servers.add(XMLRPCServer(True))

    if xroot.get_xend_unix_xmlrpc_server():
        servers.add(XMLRPCServer())
    return servers
Esempio n. 44
0
def create():
    root = SrvDir()
    root.putChild('xend', SrvRoot())
    servers = XendServers()
    if xroot.get_xend_http_server():
        servers.add(HttpServer(root,
                               xroot.get_xend_address(),
                               xroot.get_xend_port()))
    if xroot.get_xend_unix_server():
        path = xroot.get_xend_unix_path()
        log.info('unix path=' + path)
        servers.add(UnixHttpServer(root, path))

    if xroot.get_xend_tcp_xmlrpc_server():
        servers.add(XMLRPCServer(True))

    if xroot.get_xend_unix_xmlrpc_server():
        servers.add(XMLRPCServer())
    return servers
Esempio n. 45
0
        def saveInputHandler(line, tochild):
            log.debug("In saveInputHandler %s", line)
            if line == "suspend":
                log.debug("Suspending %d ...", dominfo.getDomid())
                dominfo.shutdown('suspend')
                dominfo.waitForSuspend()
            if line in ('suspend', 'suspended'):
                dominfo.migrateDevices(network, dst, DEV_MIGRATE_STEP2,
                                       domain_name)
                log.info("Domain %d suspended.", dominfo.getDomid())
                dominfo.migrateDevices(network, dst, DEV_MIGRATE_STEP3,
                                       domain_name)
                if hvm:
                    dominfo.image.saveDeviceModel()

            if line == "suspend":
                tochild.write("done\n")
                tochild.flush()
                log.debug('Written done')
Esempio n. 46
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
     if self.vncconsole:
         args = args + ([ "-vncviewer" ])
     log.info("spawning device models: %s %s", self.device_model, args)
     # keep track of pid and spawned options to kill it later
     self.pid = os.spawnve(os.P_NOWAIT, self.device_model, args, env)
     self.vm.storeDom("image/device-model-pid", self.pid)
     log.info("device model pid: %d", self.pid)
Esempio n. 47
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
     if self.vncconsole:
         args = args + (["-vncviewer"])
     log.info("spawning device models: %s %s", self.device_model, args)
     # keep track of pid and spawned options to kill it later
     self.pid = os.spawnve(os.P_NOWAIT, self.device_model, args, env)
     self.vm.storeDom("image/device-model-pid", self.pid)
     log.info("device model pid: %d", self.pid)
Esempio n. 48
0
    def signalDeviceModel(self, cmd, ret, par=None):
        if self.device_model is None:
            return
        # Signal the device model to for action
        if cmd is "" or ret is "":
            raise VmError("need valid command and result when signal device model")

        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("signalDeviceModel: orig_state is None, retrying")

            time.sleep(0.1)
            count += 1
            if count < 100:
                continue

            raise VmError("Device model isn't ready for commands")

        if par is not None:
            xstransact.Store("/local/domain/0/device-model/%i" % self.vm.getDomid(), ("parameter", par))

        xstransact.Store("/local/domain/0/device-model/%i" % self.vm.getDomid(), ("command", cmd))
        # Wait for confirmation.  Could do this with a watch but we'd
        # still end up spinning here waiting for the watch to fire.
        state = ""
        count = 0
        while state != ret:
            state = xstransact.Read("/local/domain/0/device-model/%i/state" % self.vm.getDomid())
            time.sleep(0.1)
            count += 1
            if count > 100:
                raise VmError("Timed out waiting for device model action")

        # resotre orig state
        xstransact.Store("/local/domain/0/device-model/%i" % self.vm.getDomid(), ("state", orig_state))
        log.info("signalDeviceModel:restore dm state to %s", orig_state)
Esempio n. 49
0
    def run(self):
        authmsg = self.auth == XendAPI.AUTH_NONE and "; authentication has been disabled for this server." or "."

        try:
            if self.use_tcp:
                using_ssl = self.ssl_key_file and self.ssl_cert_file

                log.info(
                    "Opening %s XML-RPC server on %s%d%s",
                    using_ssl and "HTTPS" or "TCP",
                    self.host and "%s:" % self.host or "all interfaces, port ",
                    self.port,
                    authmsg,
                )

                if using_ssl:
                    if not ssl_enabled:
                        raise ValueError("pyOpenSSL not installed. " "Unable to start HTTPS XML-RPC server")
                    self.server = SSLXMLRPCServer(
                        (self.host, self.port),
                        self.hosts_allowed,
                        self.xenapi is not None,
                        logRequests=False,
                        ssl_key_file=self.ssl_key_file,
                        ssl_cert_file=self.ssl_cert_file,
                    )
                else:
                    self.server = TCPXMLRPCServer(
                        (self.host, self.port), self.hosts_allowed, self.xenapi is not None, logRequests=False
                    )

            else:
                log.info("Opening Unix domain socket XML-RPC server on %s%s", self.path, authmsg)
                self.server = UnixXMLRPCServer(
                    self.path, self.hosts_allowed, self.xenapi is not None, logRequests=False
                )
        except socket.error, exn:
            log.error("Cannot start server: %s!", exn.args[1])
            ready = True
            running = False
            return
Esempio n. 50
0
    def run(self, status):
        try:
            log.info("Xend Daemon started")

            #xc = xen.lowlevel.xc.xc()
            #xinfo = xc.xeninfo()
            #log.info("Xend changeset: %s.", xinfo['xen_changeset'])
            #del xc

            relocate.listenRelocation()
            servers = SrvServer.create()
            servers.start(status)
        except Exception, ex:
            print >>sys.stderr, 'Exception starting xend:', ex
            if XEND_DEBUG:
                traceback.print_exc()
            log.exception("Exception starting xend (%s)" % ex)
            if status:
                status.write('1')
                status.close()
            sys.exit(1)
Esempio n. 51
0
 def createDeviceModel(self):
     if self.pid:
         return
     # Execute device model.
     #todo: Error handling
     # XXX RN: note that the order of args matter!
     args = [self.device_model]
     vnc = self.vncParams()
     if len(vnc):
         args = args + vnc
     args = args + ([ "-d",  "%d" % self.vm.getDomid(),
               "-m", "%s" % (self.vm.getMemoryTarget() / 1024)])
     args = args + self.dmargs
     env = dict(os.environ)
     if self.display:
         env['DISPLAY'] = self.display
     if self.xauthority:
         env['XAUTHORITY'] = self.xauthority
     log.info("spawning device models: %s %s", self.device_model, args)
     self.pid = os.spawnve(os.P_NOWAIT, self.device_model, args, env)
     log.info("device model pid: %d", self.pid)
Esempio n. 52
0
    def createDomain(self):
        """Build the domain boot image.
        """
        # Set params and call buildDomain().

        if self.kernel and not os.path.isfile(self.kernel):
            raise VmError("Kernel image does not exist: %s" % self.kernel)
        if self.ramdisk and not os.path.isfile(self.ramdisk):
            raise VmError("Kernel ramdisk does not exist: %s" % self.ramdisk)
        if len(self.cmdline) >= MAX_GUEST_CMDLINE:
            log.warning("kernel cmdline too long, domain %d", self.vm.getDomid())

        log.info("buildDomain os=%s dom=%d vcpus=%d", self.ostype, self.vm.getDomid(), self.vm.getVCpuCount())

        result = self.buildDomain()

        if isinstance(result, dict):
            return result
        else:
            raise VmError(
                "Building domain failed: ostype=%s dom=%d err=%s" % (self.ostype, self.vm.getDomid(), str(result))
            )
Esempio n. 53
0
    def createDomain(self):
        """Build the domain boot image.
        """
        # Set params and call buildDomain().

        if self.kernel and not os.path.isfile(self.kernel):
            raise VmError('Kernel image does not exist: %s' % self.kernel)
        if self.ramdisk and not os.path.isfile(self.ramdisk):
            raise VmError('Kernel ramdisk does not exist: %s' % self.ramdisk)
        if len(self.cmdline) >= MAX_GUEST_CMDLINE:
            log.warning('kernel cmdline too long, domain %d',
                        self.vm.getDomid())

        log.info("buildDomain os=%s dom=%d vcpus=%d", self.ostype,
                 self.vm.getDomid(), self.vm.getVCpuCount())

        result = self.buildDomain()

        if isinstance(result, dict):
            return result
        else:
            raise VmError('Building domain failed: ostype=%s dom=%d err=%s' %
                          (self.ostype, self.vm.getDomid(), str(result)))
Esempio n. 54
0
 def migrate(self, deviceConfig, network, dst, step, domName):
     """ Migration of a device. The 'network' parameter indicates
         whether the device is network-migrated (True). 'dst' then gives
         the hostname of the machine to migrate to.
     This function is called for 4 steps:
     If step == 0: Check whether the device is ready to be migrated
                   or can at all be migrated; return a '-1' if
                   the device is NOT ready, a '0' otherwise. If it is
                   not ready ( = not possible to migrate this device),
                   migration will not take place.
        step == 1: Called immediately after step 0; migration
                   of the kernel has started;
        step == 2: Called after the suspend has been issued
                   to the domain and the domain is not scheduled anymore.
                   Synchronize with what was started in step 1, if necessary.
                   Now the device should initiate its transfer to the
                   given target. Since there might be more than just
                   one device initiating a migration, this step should
                   put the process performing the transfer into the
                   background and return immediately to achieve as much
                   concurrency as possible.
        step == 3: Synchronize with the migration of the device that
                   was initiated in step 2.
                   Make sure that the migration has finished and only
                   then return from the call.
     """
     tool = xoptions.get_external_migration_tool()
     if tool:
         log.info("Calling external migration tool for step %d" % step)
         fd = os.popen("%s -type %s -step %d -host %s -domname %s" %
                       (tool, self.deviceClass, step, dst, domName))
         for line in fd:
             log.info(line.rstrip())
         rc = fd.close()
         if rc:
             raise VmError('Migration tool returned %d' % (rc >> 8))
     return 0
Esempio n. 55
0
    def start(self, trace=0):
        """Attempts to start the daemons.
        The return value is defined by the LSB:
        0  Success
        4  Insufficient privileges
        """
        xend_pid = self.cleanup_xend(False)

        if self.set_user():
            return 4
        os.chdir("/")

        if xend_pid > 0:
            # Trying to run an already-running service is a success.
            return 0

        ret = 0

        # If we're not going to create a daemon, simply
        # call the run method right here.
        if not XEND_DAEMONIZE:
            self.tracing(trace)
            self.run(None)
            return ret

        # we use a pipe to communicate between the parent and the child process
        # this way we know when the child has actually initialized itself so
        # we can avoid a race condition during startup

        r, w = os.pipe()
        if os.fork():
            os.close(w)
            r = os.fdopen(r, 'r')
            try:
                s = r.read()
            finally:
                r.close()
            if not len(s):
                ret = 1
            else:
                ret = int(s)
        else:
            os.close(r)
            # Child
            self.daemonize()
            self.tracing(trace)

            # If Xend proper segfaults, then we want to restart it.  Thus,
            # we fork a child for running Xend itself, and if it segfaults
            # (or exits any way other than cleanly) then we run it again.
            # The first time through we want the server to write to the (r,w)
            # pipe created above, so that we do not exit until the server is
            # ready to receive requests.  All subsequent restarts we don't
            # want this behaviour, or the pipe will eventually fill up, so
            # we just pass None into run in subsequent cases (by clearing w
            # in the parent of the first fork).  On some operating systems,
            # restart is managed externally, so we won't fork, and just exit.
            while True:

                if not osdep.xend_autorestart:
                    self.run(os.fdopen(w, 'w'))
                    os._exit(0)

                pid = self.fork_pid()
                if pid:
                    if w is not None:
                        os.close(w)
                        w = None

                    (_, status) = os.waitpid(pid, 0)

                    if os.WIFEXITED(status):
                        code = os.WEXITSTATUS(status)
                        log.info('Xend exited with status %d.', code)
                        sys.exit(code)

                    if os.WIFSIGNALED(status):
                        sig = os.WTERMSIG(status)

                        if sig in (signal.SIGINT, signal.SIGTERM):
                            log.info('Xend stopped due to signal %d.', sig)
                            sys.exit(0)
                        else:
                            log.fatal(
                                'Xend died due to signal %d!  Restarting it.',
                                sig)
                else:
                    self.run(w and os.fdopen(w, 'w') or None)
                    # if we reach here, the child should quit.
                    os._exit(0)

        return ret
Esempio n. 56
0
 def configure(self):
     log.info("Configuring vnet %s", self.id)
     val = vnet_cmd(['vnet.add'] + sxp.children(self.config))
     Brctl.bridge_create(self.bridge)
     Brctl.vif_bridge_add({'bridge': self.bridge, 'vif': self.vnetif})
     return val
Esempio n. 57
0
    def __add_acmpolicy_to_system(self, xmltext, flags, overwrite):
        errors = ""
        if security.on() != xsconstants.XS_POLICY_ACM:
            raise SecurityError(-xsconstants.XSERR_POLICY_TYPE_UNSUPPORTED)
        loadedpol = self.get_loaded_policy()
        if loadedpol:
            # This is meant as an update to a currently loaded policy
            if flags & xsconstants.XS_INST_LOAD == 0:
                raise SecurityError(-xsconstants.XSERR_POLICY_LOADED)

            # Remember old flags, so they can be restored if update fails
            old_flags = self.get_policy_flags(loadedpol)

            # Remove policy from bootloader in case of new name of policy
            self.rm_bootpolicy()

            rc, errors = loadedpol.update(xmltext)
            if rc == 0:
                irc = self.activate_xspolicy(loadedpol, flags)
                # policy is loaded; if setting the boot flag fails it's ok.
            else:
                old_flags = old_flags & xsconstants.XS_INST_BOOT
                log.info("OLD FLAGS TO RESTORE: %s" % str(old_flags))
                if old_flags != 0:
                    self.activate_xspolicy(loadedpol, xsconstants.XS_INST_BOOT)

            return (loadedpol, rc, errors)

        try:
            dom = minidom.parseString(xmltext.encode("utf-8"))
        except:
            raise SecurityError(-xsconstants.XSERR_BAD_XML)

        ref = uuid.createString()

        acmpol = ACMPolicy(dom=dom, ref=ref)

        #First some basic tests that do not modify anything:

        if flags & xsconstants.XS_INST_BOOT and not overwrite:
            filename = acmpol.get_filename(".bin", "", dotted=True)
            if bootloader.get_default_policy != None and \
               not bootloader.loads_default_policy(filename):
                raise SecurityError(-xsconstants.XSERR_BOOTPOLICY_INSTALLED)

        if not overwrite and len(self.policies) >= self.maxpolicies:
            raise SecurityError(-xsconstants.XSERR_BOOTPOLICY_INSTALLED)

        if overwrite:
            #This should only give one key since only one policy is
            #allowed.
            keys = self.policies.keys()
            for k in keys:
                self.rm_bootpolicy()
                rc = self.rm_policy_from_system(k, force=overwrite)
                if rc != xsconstants.XSERR_SUCCESS:
                    raise SecurityError(rc)

        rc = acmpol.compile()
        if rc != 0:
            raise SecurityError(rc)

        if flags & xsconstants.XS_INST_LOAD:
            rc = acmpol.loadintohv()
            if rc != 0:
                raise SecurityError(rc)

        if flags & xsconstants.XS_INST_BOOT:
            rc = self.make_boot_policy(acmpol)
            if rc != 0:
                # If it cannot be installed due to unsupported
                # bootloader, let it be ok.
                pass

        if dom:
            new_entry = {
                ref: tuple([acmpol.get_name(), xsconstants.ACM_POLICY_ID])
            }
            self.policies.update(new_entry)
            self.xsobjs[ref] = acmpol
        return (acmpol, xsconstants.XSERR_SUCCESS, errors)