ia64/xen-unstable

changeset 6947:7e8eac6e96c6

Replaced the device handling mechanism used by XendDomainInfo. Superficially,
this looks like the resurrection of DevController from controller.py, but the
mechanism is actually very different. Device handling is now stateless inside
xend, relying on the store for state management, reducing DevController
instances to one-shot lifetimes. Dev and its subclasses have gone completely.
The device creation code itself has moved from XendDomainInfo.createDevice into
DevController subclasses, and the previous contents of the subclasses has been
discarded (these subclasses were no longer being called, so all this code was
dead).

XendDomainInfo.getDeviceIds has gone, as it was unused.
XendDomainInfo.delete_device has been subsumed by XendDomainInfo.destroyDevice;
since device handling is now stateless inside xend, the distinction between
device 'deletion' and device 'destruction' is meaningless.

The s-expression describing devices has gone, as this information is no longer
available to xend in the same way, and seems to be unused. If it is required,
it can be reinstated by loading device information from Xen or the store.

Signed-off-by: Ewan Mellor <ewan@xensource.com>
author emellor@ewan
date Sun Sep 18 15:41:28 2005 +0100 (2005-09-18)
parents e703abaf6e3d
children 5007bebba2f5
files tools/python/xen/xend/XendDomain.py tools/python/xen/xend/XendDomainInfo.py tools/python/xen/xend/server/DevController.py tools/python/xen/xend/server/blkif.py tools/python/xen/xend/server/netif.py tools/python/xen/xend/server/pciif.py tools/python/xen/xend/server/tpmif.py tools/python/xen/xend/server/usbif.py
line diff
     1.1 --- a/tools/python/xen/xend/XendDomain.py	Sun Sep 18 14:42:13 2005 +0100
     1.2 +++ b/tools/python/xen/xend/XendDomain.py	Sun Sep 18 15:41:28 2005 +0100
     1.3 @@ -660,9 +660,8 @@ class XendDomain:
     1.4          @param type: device type
     1.5          """
     1.6          dominfo = self.domain_lookup(id)
     1.7 -        val = dominfo.device_delete(type, devid)
     1.8 -        dominfo.exportToDB()
     1.9 -        return val
    1.10 +        return dominfo.destroyDevice(type, devid)
    1.11 +
    1.12  
    1.13      def domain_devtype_ls(self, id, type):
    1.14          """Get list of device sxprs for a domain.
     2.1 --- a/tools/python/xen/xend/XendDomainInfo.py	Sun Sep 18 14:42:13 2005 +0100
     2.2 +++ b/tools/python/xen/xend/XendDomainInfo.py	Sun Sep 18 15:41:28 2005 +0100
     2.3 @@ -1,4 +1,4 @@
     2.4 -#============================================================================
     2.5 +#===========================================================================
     2.6  # This library is free software; you can redistribute it and/or
     2.7  # modify it under the terms of version 2.1 of the GNU Lesser General Public
     2.8  # License as published by the Free Software Foundation.
     2.9 @@ -23,23 +23,18 @@ Author: Mike Wray <mike.wray@hp.com>
    2.10  
    2.11  """
    2.12  
    2.13 -import string, re
    2.14 -import os
    2.15 +import string
    2.16  import time
    2.17  import threading
    2.18  import errno
    2.19  
    2.20  import xen.lowlevel.xc; xc = xen.lowlevel.xc.new()
    2.21 -from xen.util.ip import check_subnet, get_current_ipgw
    2.22  from xen.util.blkif import blkdev_uname_to_file
    2.23  
    2.24 -from xen.xend.server import controller
    2.25  from xen.xend.server import SrvDaemon; xend = SrvDaemon.instance()
    2.26  from xen.xend.server.channel import EventChannel
    2.27 -from xen.util.blkif import blkdev_name_to_number, expand_dev_name
    2.28  
    2.29  from xen.xend import sxp
    2.30 -from xen.xend import Blkctl
    2.31  from xen.xend.PrettyPrint import prettyprintstring
    2.32  from xen.xend.XendBootloader import bootloader
    2.33  from xen.xend.XendLogging import log
    2.34 @@ -47,7 +42,7 @@ from xen.xend.XendError import XendError
    2.35  from xen.xend.XendRoot import get_component
    2.36  
    2.37  from xen.xend.uuid import getUuid
    2.38 -from xen.xend.xenstore import DBVar, XenNode, DBMap
    2.39 +from xen.xend.xenstore import DBVar
    2.40  from xen.xend.xenstore.xstransact import xstransact
    2.41  from xen.xend.xenstore.xsutil import IntroduceDomain
    2.42  
    2.43 @@ -248,11 +243,9 @@ class XendDomainInfo:
    2.44          self.store_mfn = None
    2.45          self.console_channel = None
    2.46          self.console_mfn = None
    2.47 -        self.controllers = {}
    2.48          
    2.49          self.info = None
    2.50          self.backend_flags = 0
    2.51 -        self.netif_idx = 0
    2.52          
    2.53          #todo: state: running, suspended
    2.54          self.state = STATE_VM_OK
    2.55 @@ -334,6 +327,12 @@ class XendDomainInfo:
    2.56      def getName(self):
    2.57          return self.name
    2.58  
    2.59 +    def getPath(self):
    2.60 +        return self.path
    2.61 +
    2.62 +    def getUuid(self):
    2.63 +        return self.uuid
    2.64 +
    2.65      def getVCpuCount(self):
    2.66          return self.vcpus
    2.67  
    2.68 @@ -408,150 +407,26 @@ class XendDomainInfo:
    2.69  
    2.70      __repr__ = __str__
    2.71  
    2.72 -    def getDeviceController(self, type, error=True):
    2.73 -        ctrl = self.controllers.get(type)
    2.74 -        if not ctrl and error:
    2.75 -            raise XendError("invalid device type:" + type)
    2.76 -        return ctrl
    2.77 -    
    2.78 -    def findDeviceController(self, type):
    2.79 -        return (self.getDeviceController(type, error=False)
    2.80 -                or self.createDeviceController(type))
    2.81 -
    2.82 -    def createDeviceController(self, type):
    2.83 -        ctrl = controller.createDevController(type, self, recreate=self.recreate)
    2.84 -        self.controllers[type] = ctrl
    2.85 -        return ctrl
    2.86 -
    2.87 -    def createDevice(self, type, devconfig, change=False):
    2.88 -        if self.recreate:
    2.89 -            return
    2.90 -        if type == 'vbd':
    2.91 -            typedev = sxp.child_value(devconfig, 'dev')
    2.92 -            if re.match('^ioemu:', typedev):
    2.93 -	        return;
    2.94 -
    2.95 -            backdom = domain_exists(sxp.child_value(devconfig, 'backend', '0'))
    2.96 -
    2.97 -            devnum = blkdev_name_to_number(sxp.child_value(devconfig, 'dev'))
    2.98 -
    2.99 -            backpath = "%s/backend/%s/%s/%d" % (backdom.path, type,
   2.100 -                                                self.uuid, devnum)
   2.101 -            frontpath = "%s/device/%s/%d" % (self.path, type, devnum)
   2.102 -
   2.103 -            front = { 'backend' : backpath,
   2.104 -                      'backend-id' : "%i" % backdom.domid,
   2.105 -                      'virtual-device' : "%i" % devnum }
   2.106 -            xstransact.Write(frontpath, front)
   2.107  
   2.108 -            (type, params) = string.split(sxp.child_value(devconfig,
   2.109 -                                                          'uname'), ':', 1)
   2.110 -            readonly = sxp.child_value(devconfig, 'mode', 'r')
   2.111 -            back = { 'type' : type,
   2.112 -                     'params' : params,
   2.113 -                     'frontend' : frontpath,
   2.114 -                     'frontend-id' : "%i" % self.domid }
   2.115 -            if readonly == 'r':
   2.116 -                back['read-only'] = ""  # existence indicates read-only
   2.117 -            xstransact.Write(backpath, back)
   2.118 -
   2.119 -            return
   2.120 -
   2.121 -        if type == 'vif':
   2.122 -            from xen.xend import XendRoot
   2.123 -            xroot = XendRoot.instance()
   2.124 +    def getDeviceController(self, name):
   2.125 +        if name not in controllerClasses:
   2.126 +            raise XendError("unknown device type: " + str(name))
   2.127  
   2.128 -            def _get_config_ipaddr(config):
   2.129 -                val = []
   2.130 -                for ipaddr in sxp.children(config, elt='ip'):
   2.131 -                    val.append(sxp.child0(ipaddr))
   2.132 -                return val
   2.133 -
   2.134 -            backdom = domain_exists(sxp.child_value(devconfig, 'backend', '0'))
   2.135 +        return controllerClasses[name](self)
   2.136  
   2.137 -            devnum = self.netif_idx
   2.138 -            self.netif_idx += 1
   2.139 -
   2.140 -            script = sxp.child_value(devconfig, 'script',
   2.141 -                                     xroot.get_vif_script())
   2.142 -            script = os.path.join(xroot.network_script_dir, script)
   2.143 -            bridge = sxp.child_value(devconfig, 'bridge',
   2.144 -                                     xroot.get_vif_bridge())
   2.145 -            mac = sxp.child_value(devconfig, 'mac')
   2.146 -            ipaddr = _get_config_ipaddr(devconfig)
   2.147  
   2.148 -            backpath = "%s/backend/%s/%s/%d" % (backdom.path, type,
   2.149 -                                                self.uuid, devnum)
   2.150 -            frontpath = "%s/device/%s/%d" % (self.path, type, devnum)
   2.151 -
   2.152 -            front = { 'backend' : backpath,
   2.153 -                      'backend-id' : "%i" % backdom.domid,
   2.154 -                      'handle' : "%i" % devnum,
   2.155 -                      'mac' : mac }
   2.156 -            xstransact.Write(frontpath, front)
   2.157 +    def createDevice(self, deviceClass, devconfig):
   2.158 +        return self.getDeviceController(deviceClass).createDevice(devconfig)
   2.159  
   2.160 -            back = { 'script' : script,
   2.161 -                     'domain' : self.name,
   2.162 -                     'mac' : mac,
   2.163 -                     'bridge' : bridge,
   2.164 -                     'frontend' : frontpath,
   2.165 -                     'frontend-id' : "%i" % self.domid,
   2.166 -                     'handle' : "%i" % devnum }
   2.167 -            if ipaddr:
   2.168 -                back['ip'] = ' '.join(ipaddr)
   2.169 -            xstransact.Write(backpath, back)
   2.170 -
   2.171 -            return
   2.172 -        
   2.173 -        if type == 'vtpm':
   2.174 -            backdom = domain_exists(sxp.child_value(devconfig, 'backend', '0'))
   2.175 -
   2.176 -            devnum = int(sxp.child_value(devconfig, 'instance', '0'))
   2.177 -            log.error("The domain has a TPM with instance %d." % devnum)
   2.178 -
   2.179 -            backpath = "%s/backend/%s/%s/%d" % (backdom.path, type,
   2.180 -                                                self.uuid, devnum)
   2.181 -            frontpath = "%s/device/%s/%d" % (self.path, type, devnum)
   2.182  
   2.183 -            front = { 'backend' : backpath,
   2.184 -                      'backend-id' : "%i" % backdom.domid,
   2.185 -                      'handle' : "%i" % devnum }
   2.186 -            xstransact.Write(frontpath, front)
   2.187 -
   2.188 -            back = { 'instance' : "%i" % devnum,
   2.189 -                     'frontend' : frontpath,
   2.190 -                     'frontend-id' : "%i" % self.domid }
   2.191 -            xstransact.Write(backpath, back)
   2.192 -
   2.193 -            return
   2.194 -
   2.195 -        ctrl = self.findDeviceController(type)
   2.196 -        return ctrl.createDevice(devconfig, recreate=self.recreate,
   2.197 -                                 change=change)
   2.198 -
   2.199 -    def configureDevice(self, type, id, devconfig):
   2.200 -        ctrl = self.getDeviceController(type)
   2.201 -        return ctrl.configureDevice(id, devconfig)
   2.202 +    def configureDevice(self, deviceClass, devid, devconfig):
   2.203 +        return self.getDeviceController(deviceClass).configureDevice(
   2.204 +            devid, devconfig)
   2.205  
   2.206 -    def destroyDevice(self, type, id, change=False, reboot=False):
   2.207 -        ctrl = self.getDeviceController(type)
   2.208 -        return ctrl.destroyDevice(id, change=change, reboot=reboot)
   2.209 -
   2.210 -    def deleteDevice(self, type, id):
   2.211 -        ctrl = self.getDeviceController(type)
   2.212 -        return ctrl.deleteDevice(id)
   2.213  
   2.214 -    def getDevice(self, type, id, error=True):
   2.215 -        ctrl = self.getDeviceController(type)
   2.216 -        return ctrl.getDevice(id, error=error)
   2.217 -        
   2.218 -    def getDeviceIds(self, type):
   2.219 -        ctrl = self.getDeviceController(type)
   2.220 -        return ctrl.getDeviceIds()
   2.221 -    
   2.222 -    def getDeviceSxprs(self, type):
   2.223 -        ctrl = self.getDeviceController(type)
   2.224 -        return ctrl.getDeviceSxprs()
   2.225 +    def destroyDevice(self, deviceClass, devid):
   2.226 +        return self.getDeviceController(deviceClass).destroyDevice(devid)
   2.227 +
   2.228  
   2.229      def sxpr(self):
   2.230          sxpr = ['domain',
   2.231 @@ -607,25 +482,10 @@ class XendDomainInfo:
   2.232              sxpr.append(['restart_state', self.restart_state])
   2.233          if self.restart_time:
   2.234              sxpr.append(['restart_time', str(self.restart_time)])
   2.235 -
   2.236 -        devs = self.sxpr_devices()
   2.237 -        if devs:
   2.238 -            sxpr.append(devs)
   2.239          if self.config:
   2.240              sxpr.append(['config', self.config])
   2.241          return sxpr
   2.242  
   2.243 -    def sxpr_devices(self):
   2.244 -        sxpr = []
   2.245 -        for ty in self.controllers.keys():
   2.246 -            devs = self.getDeviceSxprs(ty)
   2.247 -            sxpr += devs
   2.248 -        if sxpr:
   2.249 -            sxpr.insert(0, 'devices')
   2.250 -        else:
   2.251 -            sxpr = None
   2.252 -        return sxpr
   2.253 -
   2.254      def check_name(self, name):
   2.255          """Check if a vm name is valid. Valid names contain alphabetic characters,
   2.256          digits, or characters in '_-.:/+'.
   2.257 @@ -798,19 +658,21 @@ class XendDomainInfo:
   2.258      def release_devices(self):
   2.259          """Release all vm devices.
   2.260          """
   2.261 -        reboot = self.restart_pending()
   2.262 -        for ctrl in self.controllers.values():
   2.263 -            if ctrl.isDestroyed(): continue
   2.264 -            ctrl.destroyController(reboot=reboot)
   2.265 +
   2.266          t = xstransact("%s/device" % self.path)
   2.267 -        for d in t.list("vbd"):
   2.268 -            t.remove(d)
   2.269 -        for d in t.list("vif"):
   2.270 -            t.remove(d)
   2.271 -        for d in t.list("vtpm"):
   2.272 -            t.remove(d)
   2.273 +        for n in controllerClasses.keys():
   2.274 +            for d in t.list(n):
   2.275 +                try:
   2.276 +                    t.remove(d)
   2.277 +                except ex:
   2.278 +                    # Log and swallow any exceptions in removal -- there's
   2.279 +                    # nothing more we can do.
   2.280 +                    log.exception(
   2.281 +                        "Device release failed: %s; %s; %s; %s" %
   2.282 +                        (self.info['name'], n, d, str(ex)))
   2.283          t.commit()
   2.284  
   2.285 +
   2.286      def show(self):
   2.287          """Print virtual machine info.
   2.288          """
   2.289 @@ -866,9 +728,6 @@ class XendDomainInfo:
   2.290                  raise VmError('invalid device')
   2.291              dev_type = sxp.name(dev_config)
   2.292  
   2.293 -            if not controller.isDevControllerClass(dev_type):
   2.294 -                raise VmError('unknown device type: ' + dev_type)
   2.295 -            
   2.296              self.createDevice(dev_type, dev_config)
   2.297  
   2.298  
   2.299 @@ -877,10 +736,7 @@ class XendDomainInfo:
   2.300  
   2.301          @raise: VmError for invalid devices
   2.302          """
   2.303 -        if self.rebooting():
   2.304 -            for ctrl in self.controllers.values():
   2.305 -                ctrl.initController(reboot=True)
   2.306 -        else:
   2.307 +        if not self.rebooting():
   2.308              self.create_configured_devices()
   2.309          self.image.createDeviceModel()
   2.310  
   2.311 @@ -890,47 +746,19 @@ class XendDomainInfo:
   2.312          @param dev_config: device configuration
   2.313          """
   2.314          dev_type = sxp.name(dev_config)
   2.315 -        dev = self.createDevice(dev_type, dev_config, change=True)
   2.316 -        self.config.append(['device', dev.getConfig()])
   2.317 -        return dev.sxpr()
   2.318 -
   2.319 -    def device_configure(self, dev_config, id):
   2.320 -        """Configure an existing device.
   2.321 +        devid = self.createDevice(dev_type, dev_config)
   2.322 +#        self.config.append(['device', dev.getConfig()])
   2.323 +        return self.getDeviceController(dev_type).sxpr(devid)
   2.324  
   2.325 -        @param dev_config: device configuration
   2.326 -        @param id:         device id
   2.327 -        """
   2.328 -        type = sxp.name(dev_config)
   2.329 -        dev = self.getDevice(type, id)
   2.330 -        old_config = dev.getConfig()
   2.331 -        new_config = dev.configure(dev_config, change=True)
   2.332 -        # Patch new config into vm config.
   2.333 -        new_full_config = ['device', new_config]
   2.334 -        old_full_config = ['device', old_config]
   2.335 -        old_index = self.config.index(old_full_config)
   2.336 -        self.config[old_index] = new_full_config
   2.337 -        return new_config
   2.338  
   2.339 -    def device_refresh(self, type, id):
   2.340 -        """Refresh a device.
   2.341 -
   2.342 -        @param type: device type
   2.343 -        @param id:   device id
   2.344 +    def device_configure(self, dev_config, devid):
   2.345 +        """Configure an existing device.
   2.346 +        @param dev_config: device configuration
   2.347 +        @param devid:      device id
   2.348          """
   2.349 -        dev = self.getDevice(type, id)
   2.350 -        dev.refresh()
   2.351 -        
   2.352 -    def device_delete(self, type, id):
   2.353 -        """Destroy and remove a device.
   2.354 +        deviceClass = sxp.name(dev_config)
   2.355 +        self.configureDevice(deviceClass, devid, dev_config)
   2.356  
   2.357 -        @param type: device type
   2.358 -        @param id:   device id
   2.359 -        """
   2.360 -        dev = self.getDevice(type, id)
   2.361 -        dev_config = dev.getConfig()
   2.362 -        if dev_config:
   2.363 -            self.config.remove(['device', dev_config])
   2.364 -        self.deleteDevice(type, dev.getId())
   2.365  
   2.366      def configure_restart(self):
   2.367          """Configure the vm restart mode.
   2.368 @@ -1060,11 +888,6 @@ class XendDomainInfo:
   2.369  
   2.370          """
   2.371          return
   2.372 -        blkif = self.getDeviceController("vbd", error=False)
   2.373 -        if not blkif:
   2.374 -            blkif = self.createDeviceController("vbd")
   2.375 -            backend = blkif.getBackend(0)
   2.376 -            backend.connect(recreate=self.recreate)
   2.377  
   2.378      def configure_fields(self):
   2.379          """Process the vm configuration fields using the registered handlers.
   2.380 @@ -1213,9 +1036,21 @@ config_handlers = {
   2.381  #============================================================================
   2.382  # Register device controllers and their device config types.
   2.383  
   2.384 +"""A map from device-class names to the subclass of DevController that
   2.385 +implements the device control specific to that device-class."""
   2.386 +controllerClasses = {}
   2.387 +
   2.388 +
   2.389 +def addControllerClass(device_class, cls):
   2.390 +    """Register a subclass of DevController to handle the named device-class.
   2.391 +    """
   2.392 +    cls.deviceClass = device_class
   2.393 +    controllerClasses[device_class] = cls
   2.394 +
   2.395 +
   2.396  from xen.xend.server import blkif, netif, tpmif, pciif, usbif
   2.397 -controller.addDevControllerClass("vbd",  blkif.BlkifController)
   2.398 -controller.addDevControllerClass("vif",  netif.NetifController)
   2.399 -controller.addDevControllerClass("vtpm", tpmif.TPMifController)
   2.400 -controller.addDevControllerClass("pci",  pciif.PciController)
   2.401 -controller.addDevControllerClass("usb",  usbif.UsbifController)
   2.402 +addControllerClass('vbd',  blkif.BlkifController)
   2.403 +addControllerClass('vif',  netif.NetifController)
   2.404 +addControllerClass('vtpm', tpmif.TPMifController)
   2.405 +addControllerClass('pci',  pciif.PciController)
   2.406 +addControllerClass('usb',  usbif.UsbifController)
     3.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     3.2 +++ b/tools/python/xen/xend/server/DevController.py	Sun Sep 18 15:41:28 2005 +0100
     3.3 @@ -0,0 +1,175 @@
     3.4 +#============================================================================
     3.5 +# This library is free software; you can redistribute it and/or
     3.6 +# modify it under the terms of version 2.1 of the GNU Lesser General Public
     3.7 +# License as published by the Free Software Foundation.
     3.8 +#
     3.9 +# This library is distributed in the hope that it will be useful,
    3.10 +# but WITHOUT ANY WARRANTY; without even the implied warranty of
    3.11 +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    3.12 +# Lesser General Public License for more details.
    3.13 +#
    3.14 +# You should have received a copy of the GNU Lesser General Public
    3.15 +# License along with this library; if not, write to the Free Software
    3.16 +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
    3.17 +#============================================================================
    3.18 +# Copyright (C) 2004, 2005 Mike Wray <mike.wray@hp.com>
    3.19 +# Copyright (C) 2005 XenSource Ltd
    3.20 +#============================================================================
    3.21 +
    3.22 +
    3.23 +from xen.xend import sxp
    3.24 +from xen.xend.XendError import VmError
    3.25 +from xen.xend.XendLogging import log
    3.26 +from xen.xend.xenstore.xstransact import xstransact
    3.27 +
    3.28 +
    3.29 +class DevController:
    3.30 +    """Abstract base class for a device controller.  Device controllers create
    3.31 +    appropriate entries in the store to trigger the creation, reconfiguration,
    3.32 +    and destruction of devices in guest domains.  Each subclass of
    3.33 +    DevController is responsible for a particular device-class, and
    3.34 +    understands the details of configuration specific to that device-class.
    3.35 +
    3.36 +    DevController itself provides the functionality common to all device
    3.37 +    creation tasks, as well as providing an interface to XendDomainInfo for
    3.38 +    triggering those events themselves.
    3.39 +    """
    3.40 +
    3.41 +    # Set when registered.
    3.42 +    deviceClass = None
    3.43 +
    3.44 +
    3.45 +    ## public:
    3.46 +
    3.47 +    def __init__(self, vm):
    3.48 +        self.vm = vm
    3.49 +
    3.50 +
    3.51 +    def createDevice(self, config):
    3.52 +        """Trigger the creation of a device with the given configuration.
    3.53 +
    3.54 +        @return The ID for the newly created device.
    3.55 +        """
    3.56 +        (devid, back, front) = self.getDeviceDetails(config)
    3.57 +
    3.58 +        self.writeDetails(config, devid, back, front)
    3.59 +
    3.60 +        return devid
    3.61 +
    3.62 +
    3.63 +    def reconfigureDevice(self, devid, config):
    3.64 +        """Reconfigure the specified device.
    3.65 +
    3.66 +        The implementation here just raises VmError.  This may be overridden
    3.67 +        by those subclasses that can reconfigure their devices.
    3.68 +        """
    3.69 +        raise VmError('%s devices may not be reconfigured' % self.deviceClass)
    3.70 +
    3.71 +
    3.72 +    def destroyDevice(self, devid):
    3.73 +        """Destroy the specified device.
    3.74 +
    3.75 +        The implementation here simply deletes the appropriate paths from
    3.76 +        the store.  This may be overridden by subclasses who need to perform
    3.77 +        other tasks on destruction.
    3.78 +        """
    3.79 +
    3.80 +        frontpath = self.frontendPath(devid)
    3.81 +        backpath = xstransact.Read("%s/backend" % frontpath)
    3.82 +
    3.83 +        xstransact.Remove(frontpath)
    3.84 +        xstransact.Remove(backpath)
    3.85 +
    3.86 +
    3.87 +    def sxpr(self, devid):
    3.88 +        """@return an s-expression describing the specified device.
    3.89 +        """
    3.90 +        return [self.deviceClass, ['dom', self.vm.getDomain(),
    3.91 +                                   'id', devid]]
    3.92 +
    3.93 +
    3.94 +    ## protected:
    3.95 +
    3.96 +    def getDeviceDetails(self, config):
    3.97 +        """Compute the details for creation of a device corresponding to the
    3.98 +        given configuration.  These details consist of a tuple of (devID,
    3.99 +        backDetails, frontDetails), where devID is the ID for the new device,
   3.100 +        and backDetails and frontDetails are the device configuration
   3.101 +        specifics for the backend and frontend respectively.
   3.102 +
   3.103 +        backDetails and frontDetails should be dictionaries, the keys and
   3.104 +        values of which will be used as paths in the store.  There is no need
   3.105 +        for these dictionaries to include the references from frontend to
   3.106 +        backend, nor vice versa, as these will be handled by DevController.
   3.107 +
   3.108 +        Abstract; must be implemented by every subclass.
   3.109 +
   3.110 +        @return (devID, backDetails, frontDetails), as specified above.
   3.111 +        """
   3.112 +
   3.113 +        raise NotImplementedError()
   3.114 +
   3.115 +
   3.116 +    def getDomain(self):
   3.117 +        """Stub to {@link XendDomainInfo.getDomain}, for use by our
   3.118 +        subclasses.
   3.119 +        """
   3.120 +        return self.vm.getDomain()
   3.121 +
   3.122 +
   3.123 +    ## private:
   3.124 +
   3.125 +    def writeDetails(self, config, devid, backDetails, frontDetails):
   3.126 +        """Write the details in the store to trigger creation of a device.
   3.127 +        The backend domain ID is taken from the given config, paths for
   3.128 +        frontend and backend are computed, and these are written to the store
   3.129 +        appropriately, including references from frontend to backend and vice
   3.130 +        versa.
   3.131 +
   3.132 +        @param config The configuration of the device, as given to
   3.133 +        {@link #createDevice}.
   3.134 +        @param devid        As returned by {@link #getDeviceDetails}.
   3.135 +        @param backDetails  As returned by {@link #getDeviceDetails}.
   3.136 +        @param frontDetails As returned by {@link #getDeviceDetails}.
   3.137 +        """
   3.138 +
   3.139 +        import xen.xend.XendDomain
   3.140 +        backdom = xen.xend.XendDomain.instance().domain_lookup_by_name(
   3.141 +            sxp.child_value(config, 'backend', '0'))
   3.142 +
   3.143 +        frontpath = self.frontendPath(devid)
   3.144 +        backpath  = self.backendPath(backdom, devid)
   3.145 +        
   3.146 +        frontDetails.update({
   3.147 +            'backend' : backpath,
   3.148 +            'backend-id' : "%i" % backdom.getDomain()
   3.149 +            })
   3.150 +
   3.151 +
   3.152 +        backDetails.update({
   3.153 +            'domain' : self.vm.getName(),
   3.154 +            'frontend' : frontpath,
   3.155 +            'frontend-id' : "%i" % self.vm.getDomain()
   3.156 +            })
   3.157 +
   3.158 +        log.debug('DevController: writing %s to %s.', str(frontDetails),
   3.159 +                  frontpath)
   3.160 +        log.debug('DevController: writing %s to %s.', str(backDetails),
   3.161 +                  backpath)
   3.162 +
   3.163 +        xstransact.Write(frontpath, frontDetails)
   3.164 +        xstransact.Write(backpath, backDetails)
   3.165 +
   3.166 +
   3.167 +    def backendPath(self, backdom, devid):
   3.168 +        """@param backdom [XendDomainInfo] The backend domain info."""
   3.169 +
   3.170 +        return "%s/backend/%s/%s/%d" % (backdom.getPath(),
   3.171 +                                        self.deviceClass,
   3.172 +                                        self.vm.getUuid(), devid)
   3.173 +
   3.174 +
   3.175 +    def frontendPath(self, devid):
   3.176 +        return "%s/device/%s/%d" % (self.vm.getPath(),
   3.177 +                                    self.deviceClass,
   3.178 +                                    devid)
     4.1 --- a/tools/python/xen/xend/server/blkif.py	Sun Sep 18 14:42:13 2005 +0100
     4.2 +++ b/tools/python/xen/xend/server/blkif.py	Sun Sep 18 15:41:28 2005 +0100
     4.3 @@ -13,322 +13,47 @@
     4.4  # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
     4.5  #============================================================================
     4.6  # Copyright (C) 2004, 2005 Mike Wray <mike.wray@hp.com>
     4.7 +# Copyright (C) 2005 XenSource Ltd
     4.8  #============================================================================
     4.9  
    4.10 -"""Support for virtual block devices.
    4.11 -"""
    4.12 +
    4.13 +import re
    4.14  import string
    4.15  
    4.16  from xen.util import blkif
    4.17 -from xen.xend.XendError import XendError, VmError
    4.18 -from xen.xend.XendRoot import get_component
    4.19 -from xen.xend.XendLogging import log
    4.20  from xen.xend import sxp
    4.21 -from xen.xend import Blkctl
    4.22 -from xen.xend.xenstore import DBVar
    4.23 -
    4.24 -from xen.xend.server.controller import Dev, DevController
    4.25 -
    4.26 -class BlkifBackend:
    4.27 -    """ Handler for the 'back-end' channel to a block device driver domain
    4.28 -    on behalf of a front-end domain.
    4.29 -    Must be connected using connect() before it can be used.
    4.30 -    """
    4.31 -
    4.32 -    def __init__(self, controller, id, dom, recreate=False):
    4.33 -        self.controller = controller
    4.34 -        self.id = id
    4.35 -        self.frontendDomain = self.controller.getDomain()
    4.36 -        self.backendDomain = dom
    4.37 -        self.destroyed = False
    4.38 -        self.connected = False
    4.39 -        self.status = None
    4.40 -
    4.41 -    def init(self, recreate=False, reboot=False):
    4.42 -        self.destroyed = False
    4.43 -        self.status = BLKIF_INTERFACE_STATUS_DISCONNECTED
    4.44 -        self.frontendDomain = self.controller.getDomain()
    4.45 -
    4.46 -    def __str__(self):
    4.47 -        return ('<BlkifBackend frontend=%d backend=%d id=%d>'
    4.48 -                % (self.frontendDomain,
    4.49 -                   self.backendDomain,
    4.50 -                   self.id))
    4.51 -
    4.52 -    def getId(self):
    4.53 -        return self.id
    4.54 -
    4.55 -    def connect(self, recreate=False):
    4.56 -        """Connect to the blkif control interface.
    4.57 -
    4.58 -        @param recreate: true if after xend restart
    4.59 -        """
    4.60 -        log.debug("Connecting blkif %s", str(self))
    4.61 -        if recreate or self.connected:
    4.62 -            self.connected = True
    4.63 -            pass
    4.64 -        
    4.65 -    def destroy(self, change=False, reboot=False):
    4.66 -        """Disconnect from the blkif control interface and destroy it.
    4.67 -        """
    4.68 -        self.destroyed = True
    4.69 -        # For change true need to notify front-end, or back-end will do it?
    4.70 -
    4.71 -    def connectInterface(self, val):
    4.72 -        self.status = BLKIF_INTERFACE_STATUS_CONNECTED
    4.73 -            
    4.74 -    def interfaceDisconnected(self):
    4.75 -        self.status = BLKIF_INTERFACE_STATUS_DISCONNECTED
    4.76 -        
    4.77 -class BlkDev(Dev):
    4.78 -    """Info record for a block device.
    4.79 -    """
    4.80 -
    4.81 -    __exports__ = Dev.__exports__ + [
    4.82 -        DBVar('dev',          ty='str'),
    4.83 -        DBVar('vdev',         ty='int'),
    4.84 -        DBVar('mode',         ty='str'),
    4.85 -        DBVar('viftype',      ty='str'),
    4.86 -        DBVar('params',       ty='str'),
    4.87 -        DBVar('node',         ty='str'),
    4.88 -        DBVar('device',       ty='long'),
    4.89 -        DBVar('dev_handle',   ty='long'),
    4.90 -        DBVar('start_sector', ty='long'),
    4.91 -        DBVar('nr_sectors',   ty='long'),
    4.92 -        ]
    4.93 -
    4.94 -    def __init__(self, controller, id, config, recreate=False):
    4.95 -        Dev.__init__(self, controller, id, config, recreate=recreate)
    4.96 -        self.dev = None
    4.97 -        self.uname = None
    4.98 -        self.vdev = None
    4.99 -        self.mode = None
   4.100 -        self.type = None
   4.101 -        self.params = None
   4.102 -        self.node = None
   4.103 -        self.device = None
   4.104 -        self.dev_handle = 0
   4.105 -        self.start_sector = None
   4.106 -        self.nr_sectors = None
   4.107 -        
   4.108 -        self.frontendDomain = self.getDomain()
   4.109 -        self.backendDomain = None
   4.110 -        self.backendId = 0
   4.111 -        self.configure(self.config, recreate=recreate)
   4.112 -
   4.113 -    def exportToDB(self, save=False):
   4.114 -        Dev.exportToDB(self, save=save)
   4.115 -        backend = self.getBackend()
   4.116 -
   4.117 -    def init(self, recreate=False, reboot=False):
   4.118 -        self.frontendDomain = self.getDomain()
   4.119 -        backend = self.getBackend()
   4.120 -        self.backendId = backend.domid
   4.121  
   4.122 -    def configure(self, config, change=False, recreate=False):
   4.123 -        if change:
   4.124 -            raise XendError("cannot reconfigure vbd")
   4.125 -        self.config = config
   4.126 -        self.uname = sxp.child_value(config, 'uname')
   4.127 -        if not self.uname:
   4.128 -            raise VmError('vbd: Missing uname')
   4.129 -        # Split into type and type-specific params (which are passed to the
   4.130 -        # type-specific control script).
   4.131 -        (self.type, self.params) = string.split(self.uname, ':', 1)
   4.132 -        self.dev = sxp.child_value(config, 'dev')
   4.133 -        if not self.dev:
   4.134 -            raise VmError('vbd: Missing dev')
   4.135 -        self.mode = sxp.child_value(config, 'mode', 'r')
   4.136 -        
   4.137 -        self.vdev = blkif.blkdev_name_to_number(self.dev)
   4.138 -        if not self.vdev:
   4.139 -            raise VmError('vbd: Device not found: %s' % self.dev)
   4.140 -        
   4.141 -        try:
   4.142 -            xd = get_component('xen.xend.XendDomain')
   4.143 -            self.backendDomain = xd.domain_lookup_by_name(sxp.child_value(config, 'backend', '0')).domid
   4.144 -        except:
   4.145 -            raise XendError('invalid backend domain')
   4.146 -
   4.147 -        return self.config
   4.148 -
   4.149 -    def attach(self, recreate=False, change=False):
   4.150 -        if recreate:
   4.151 -            pass
   4.152 -        else:
   4.153 -            node = Blkctl.block('bind', self.type, self.params)
   4.154 -            self.setNode(node)
   4.155 -            self.attachBackend()
   4.156 -        if change:
   4.157 -            self.interfaceChanged()
   4.158 -
   4.159 -    def unbind(self):
   4.160 -        if self.node is None: return
   4.161 -        log.debug("Unbinding vbd (type %s) from %s"
   4.162 -                  % (self.type, self.node))
   4.163 -        Blkctl.block('unbind', self.type, self.node)
   4.164 +from xen.xend.server.DevController import DevController
   4.165  
   4.166 -    def setNode(self, node):
   4.167 -    
   4.168 -        # NOTE: 
   4.169 -        # This clause is testing code for storage system experiments.
   4.170 -        # Add a new disk type that will just pass an opaque id in the
   4.171 -        # dev_handle and use an experimental device type.
   4.172 -        # Please contact andrew.warfield@cl.cam.ac.uk with any concerns.
   4.173 -        if self.type == 'parallax':
   4.174 -            self.node   = node
   4.175 -            self.device =  61440 # (240,0)
   4.176 -            self.dev_handle = long(self.params)
   4.177 -            self.nr_sectors = long(0)
   4.178 -            return
   4.179 -        # done.
   4.180 -            
   4.181 -        mounted_mode = self.check_mounted(node)
   4.182 -        if not '!' in self.mode and mounted_mode:
   4.183 -            if mounted_mode == "w":
   4.184 -                raise VmError("vbd: Segment %s is in writable use" %
   4.185 -                              self.uname)
   4.186 -            elif 'w' in self.mode:
   4.187 -                raise VmError("vbd: Segment %s is in read-only use" %
   4.188 -                              self.uname)
   4.189 -            
   4.190 -        segment = blkif.blkdev_segment(node)
   4.191 -        if not segment:
   4.192 -            raise VmError("vbd: Segment not found: uname=%s" % self.uname)
   4.193 -        self.node = node
   4.194 -        self.device = segment['device']
   4.195 -        self.start_sector = segment['start_sector']
   4.196 -        self.nr_sectors = segment['nr_sectors']
   4.197  
   4.198 -    def check_mounted(self, name):
   4.199 -        mode = blkif.mount_mode(name)
   4.200 -        xd = get_component('xen.xend.XendDomain')
   4.201 -        for vm in xd.list():
   4.202 -            ctrl = vm.getDeviceController(self.getType(), error=False)
   4.203 -            if (not ctrl): continue
   4.204 -            for dev in ctrl.getDevices():
   4.205 -                if dev is self: continue
   4.206 -                if dev.type == 'phy' and name == blkif.expand_dev_name(dev.params):
   4.207 -                    mode = dev.mode
   4.208 -                    if 'w' in mode:
   4.209 -                        return 'w'
   4.210 -        if mode and 'r' in mode:
   4.211 -            return 'r'
   4.212 -        return None
   4.213 -
   4.214 -    def readonly(self):
   4.215 -        return 'w' not in self.mode
   4.216 -
   4.217 -    def sxpr(self):
   4.218 -        val = ['vbd',
   4.219 -               ['id', self.id],
   4.220 -               ['vdev', self.vdev],
   4.221 -               ['device', self.device],
   4.222 -               ['mode', self.mode]]
   4.223 -        if self.dev:
   4.224 -            val.append(['dev', self.dev])
   4.225 -        if self.uname:
   4.226 -            val.append(['uname', self.uname])
   4.227 -        if self.node:
   4.228 -            val.append(['node', self.node])
   4.229 -        return val
   4.230 -
   4.231 -    def getBackend(self):
   4.232 -        return self.controller.getBackend(self.backendDomain)
   4.233 -
   4.234 -    def refresh(self):
   4.235 -        log.debug("Refreshing vbd domain=%d id=%s", self.frontendDomain,
   4.236 -                  self.id)
   4.237 -        self.interfaceChanged()
   4.238 -
   4.239 -    def destroy(self, change=False, reboot=False):
   4.240 -        """Destroy the device. If 'change' is true notify the front-end interface.
   4.241 -
   4.242 -        @param change: change flag
   4.243 -        """
   4.244 -        self.destroyed = True
   4.245 -        log.debug("Destroying vbd domain=%d id=%s", self.frontendDomain,
   4.246 -                  self.id)
   4.247 -        if change:
   4.248 -            self.interfaceChanged()
   4.249 -        self.unbind()
   4.250 -
   4.251 -    def interfaceChanged(self):
   4.252 -        """Tell the back-end to notify the front-end that a device has been
   4.253 -        added or removed.
   4.254 -        """
   4.255 -        self.getBackend().interfaceChanged()
   4.256 -
   4.257 -    def attachBackend(self):
   4.258 -        """Attach the device to its controller.
   4.259 -
   4.260 -        """
   4.261 -        self.getBackend().connect()
   4.262 -        
   4.263  class BlkifController(DevController):
   4.264      """Block device interface controller. Handles all block devices
   4.265      for a domain.
   4.266      """
   4.267      
   4.268 -    def __init__(self, vm, recreate=False):
   4.269 +    def __init__(self, vm):
   4.270          """Create a block device controller.
   4.271          """
   4.272 -        DevController.__init__(self, vm, recreate=recreate)
   4.273 -        self.backends = {}
   4.274 -        self.backendId = 0
   4.275 +        DevController.__init__(self, vm)
   4.276  
   4.277 -    def initController(self, recreate=False, reboot=False):
   4.278 -        self.destroyed = False
   4.279 -        if reboot:
   4.280 -            self.rebootBackends()
   4.281 -            self.rebootDevices()
   4.282  
   4.283 -    def sxpr(self):
   4.284 -        val = ['blkif', ['dom', self.getDomain()]]
   4.285 -        return val
   4.286 -
   4.287 -    def rebootBackends(self):
   4.288 -        for backend in self.backends.values():
   4.289 -            backend.init(reboot=True)
   4.290 +    def getDeviceDetails(self, config):
   4.291 +        """@see DevController.getDeviceDetails"""
   4.292 +        
   4.293 +        typedev = sxp.child_value(config, 'dev')
   4.294 +        if re.match('^ioemu:', typedev):
   4.295 +            return
   4.296  
   4.297 -    def getBackendById(self, id):
   4.298 -        return self.backends.get(id)
   4.299 -
   4.300 -    def getBackendByDomain(self, dom):
   4.301 -        for backend in self.backends.values():
   4.302 -            if backend.backendDomain == dom:
   4.303 -                return backend
   4.304 -        return None
   4.305 +        devid = blkif.blkdev_name_to_number(sxp.child_value(config, 'dev'))
   4.306  
   4.307 -    def getBackend(self, dom):
   4.308 -        backend = self.getBackendByDomain(dom)
   4.309 -        if backend: return backend
   4.310 -        backend = BlkifBackend(self, self.backendId, dom)
   4.311 -        self.backendId += 1
   4.312 -        self.backends[backend.getId()] = backend
   4.313 -        backend.init()
   4.314 -        return backend
   4.315 -
   4.316 -    def newDevice(self, id, config, recreate=False):
   4.317 -        """Create a device..
   4.318 +        (typ, params) = string.split(sxp.child_value(config, 'uname'), ':', 1)
   4.319 +        back = { 'type' : typ,
   4.320 +                 'params' : params
   4.321 +                 }
   4.322  
   4.323 -        @param id:      device id
   4.324 -        @param config:   device configuration
   4.325 -        @param recreate: if true it's being recreated (after xend restart)
   4.326 -        @type  recreate: bool
   4.327 -        @return: device
   4.328 -        @rtype:  BlkDev
   4.329 -        """
   4.330 -        return BlkDev(self, id, config, recreate=recreate)
   4.331 -        
   4.332 -    def destroyController(self, reboot=False):
   4.333 -        """Destroy the controller and all devices.
   4.334 -        """
   4.335 -        self.destroyed = True
   4.336 -        log.debug("Destroying blkif domain=%d", self.getDomain())
   4.337 -        self.destroyDevices(reboot=reboot)
   4.338 -        self.destroyBackends(reboot=reboot)
   4.339 +        if 'r' == sxp.child_value(config, 'mode', 'r'):
   4.340 +            back['read-only'] = ""  # existence indicates read-only
   4.341  
   4.342 -    def destroyBackends(self, reboot=False):
   4.343 -        for backend in self.backends.values():
   4.344 -            backend.destroy(reboot=reboot)
   4.345 +        front = { 'virtual-device' : "%i" % devid }
   4.346 +
   4.347 +        return (devid, back, front)
     5.1 --- a/tools/python/xen/xend/server/controller.py	Sun Sep 18 14:42:13 2005 +0100
     5.2 +++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
     5.3 @@ -1,423 +0,0 @@
     5.4 -#============================================================================
     5.5 -# This library is free software; you can redistribute it and/or
     5.6 -# modify it under the terms of version 2.1 of the GNU Lesser General Public
     5.7 -# License as published by the Free Software Foundation.
     5.8 -#
     5.9 -# This library is distributed in the hope that it will be useful,
    5.10 -# but WITHOUT ANY WARRANTY; without even the implied warranty of
    5.11 -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    5.12 -# Lesser General Public License for more details.
    5.13 -#
    5.14 -# You should have received a copy of the GNU Lesser General Public
    5.15 -# License along with this library; if not, write to the Free Software
    5.16 -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
    5.17 -#============================================================================
    5.18 -# Copyright (C) 2004, 2005 Mike Wray <mike.wray@hp.com>
    5.19 -#============================================================================
    5.20 -
    5.21 -"""General support for controllers, which handle devices
    5.22 -for a domain.
    5.23 -"""
    5.24 -
    5.25 -from xen.xend.XendError import XendError
    5.26 -from xen.xend.xenstore import DBVar
    5.27 -
    5.28 -DEBUG = 0
    5.29 -
    5.30 -class DevControllerTable:
    5.31 -    """Table of device controller classes, indexed by type name.
    5.32 -    """
    5.33 -
    5.34 -    def __init__(self):
    5.35 -        self.controllerClasses = {}
    5.36 -
    5.37 -    def getDevControllerClass(self, type):
    5.38 -        return self.controllerClasses.get(type)
    5.39 -
    5.40 -    def addDevControllerClass(self, cls):
    5.41 -        self.controllerClasses[cls.getType()] = cls
    5.42 -
    5.43 -    def delDevControllerClass(self, type):
    5.44 -        if type in self.controllerClasses:
    5.45 -            del self.controllerClasses[type]
    5.46 -
    5.47 -    def createDevController(self, type, vm, recreate=False):
    5.48 -        cls = self.getDevControllerClass(type)
    5.49 -        if not cls:
    5.50 -            raise XendError("unknown device type: " + str(type))
    5.51 -        return cls.createDevController(vm, recreate=recreate)
    5.52 -
    5.53 -def getDevControllerTable():
    5.54 -    """Singleton constructor for the controller table.
    5.55 -    """
    5.56 -    global devControllerTable
    5.57 -    try:
    5.58 -        devControllerTable
    5.59 -    except:
    5.60 -        devControllerTable = DevControllerTable()
    5.61 -    return devControllerTable
    5.62 -
    5.63 -def addDevControllerClass(name, cls):
    5.64 -    """Add a device controller class to the controller table.
    5.65 -    """
    5.66 -    cls.type = name
    5.67 -    getDevControllerTable().addDevControllerClass(cls)
    5.68 -
    5.69 -
    5.70 -def isDevControllerClass(name):
    5.71 -    """@return True if a device controller class has been registered with
    5.72 -    the controller table under the given name."""
    5.73 -    return name in getDevControllerTable().controllerClasses
    5.74 -
    5.75 -
    5.76 -def createDevController(name, vm, recreate=False):
    5.77 -    return getDevControllerTable().createDevController(name, vm, recreate=recreate)
    5.78 -
    5.79 -class DevController:
    5.80 -    """Abstract class for a device controller attached to a domain.
    5.81 -    A device controller manages all the devices of a given type for a domain.
    5.82 -    There is exactly one device controller for each device type for
    5.83 -    a domain.
    5.84 -
    5.85 -    """
    5.86 -
    5.87 -    # State:
    5.88 -    # controller/<type> : for controller
    5.89 -    # device/<type>/<id>   : for each device
    5.90 -
    5.91 -    def createDevController(cls, vm, recreate=False):
    5.92 -        """Class method to create a dev controller.
    5.93 -        """
    5.94 -        ctrl = cls(vm, recreate=recreate)
    5.95 -        ctrl.initController(recreate=recreate)
    5.96 -        ctrl.exportToDB()
    5.97 -        return ctrl
    5.98 -
    5.99 -    createDevController = classmethod(createDevController)
   5.100 -
   5.101 -    def getType(cls):
   5.102 -        return cls.type
   5.103 -
   5.104 -    getType = classmethod(getType)
   5.105 -
   5.106 -    __exports__ = [
   5.107 -        DBVar('type',      'str'),
   5.108 -        DBVar('destroyed', 'bool'),
   5.109 -        ]
   5.110 -
   5.111 -    # Set when registered.
   5.112 -    type = None
   5.113 -
   5.114 -    def __init__(self, vm, recreate=False):
   5.115 -        self.destroyed = False
   5.116 -        self.vm = vm
   5.117 -        self.db = self.getDB()
   5.118 -        self.deviceId = 0
   5.119 -        self.devices = {}
   5.120 -        self.device_order = []
   5.121 -
   5.122 -    def getDB(self):
   5.123 -        """Get the db node to use for a controller.
   5.124 -        """
   5.125 -        return self.vm.db.addChild("/controller/%s" % self.getType())
   5.126 -
   5.127 -    def getDevDB(self, id):
   5.128 -        """Get the db node to use for a device.
   5.129 -        """
   5.130 -        return self.vm.db.addChild("/device/%s/%s" % (self.getType(), id))
   5.131 -
   5.132 -    def exportToDB(self, save=False):
   5.133 -        self.db.exportToDB(self, fields=self.__exports__, save=save)
   5.134 -
   5.135 -    def importFromDB(self):
   5.136 -        self.db.importFromDB(self, fields=self.__exports__)
   5.137 -
   5.138 -    def getDevControllerType(self):
   5.139 -        return self.dctype
   5.140 -
   5.141 -    def getDomain(self):
   5.142 -        return self.vm.getDomain()
   5.143 -
   5.144 -    def getDomainName(self):
   5.145 -        return self.vm.getName()
   5.146 -
   5.147 -    def getDomainInfo(self):
   5.148 -        return self.vm
   5.149 -
   5.150 -    #----------------------------------------------------------------------------
   5.151 -    # Subclass interface.
   5.152 -    # Subclasses should define the unimplemented methods..
   5.153 -    # Redefinitions must have the same arguments.
   5.154 -
   5.155 -    def initController(self, recreate=False, reboot=False):
   5.156 -        """Initialise the controller. Called when the controller is
   5.157 -        first created, and again after the domain is rebooted (with reboot True).
   5.158 -        If called with recreate True (and reboot False) the controller is being
   5.159 -        recreated after a xend restart.
   5.160 -
   5.161 -        As this can be a re-init (after reboot) any controller state should
   5.162 -        be reset. For example the destroyed flag.
   5.163 -        """
   5.164 -        self.destroyed = False
   5.165 -        if reboot:
   5.166 -            self.rebootDevices()
   5.167 -
   5.168 -    def newDevice(self, id, config, recreate=False):
   5.169 -        """Create a device with the given config.
   5.170 -        Must be defined in subclass.
   5.171 -        Called with recreate True when the device is being recreated after a
   5.172 -        xend restart.
   5.173 -
   5.174 -        @return device
   5.175 -        """
   5.176 -        raise NotImplementedError()
   5.177 -
   5.178 -    def createDevice(self, config, recreate=False, change=False):
   5.179 -        """Create a device and attach to its front- and back-ends.
   5.180 -        If recreate is true the device is being recreated after a xend restart.
   5.181 -        If change is true the device is a change to an existing domain,
   5.182 -        i.e. it is being added at runtime rather than when the domain is created.
   5.183 -        """
   5.184 -        dev = self.newDevice(self.nextDeviceId(), config, recreate=recreate)
   5.185 -        if self.vm.recreate:
   5.186 -            dev.importFromDB()
   5.187 -        dev.init(recreate=recreate)
   5.188 -        self.addDevice(dev)
   5.189 -        if not recreate:
   5.190 -            dev.exportToDB()
   5.191 -        dev.attach(recreate=recreate, change=change)
   5.192 -        dev.exportToDB()
   5.193 -
   5.194 -        return dev
   5.195 -
   5.196 -    def configureDevice(self, id, config, change=False):
   5.197 -        """Reconfigure an existing device.
   5.198 -        May be defined in subclass."""
   5.199 -        dev = self.getDevice(id, error=True)
   5.200 -        dev.configure(config, change=change)
   5.201 -
   5.202 -    def destroyDevice(self, id, change=False, reboot=False):
   5.203 -        """Destroy a device.
   5.204 -        May be defined in subclass.
   5.205 -
   5.206 -        If reboot is true the device is being destroyed for a domain reboot.
   5.207 -
   5.208 -        The device is not deleted, since it may be recreated later.
   5.209 -        """
   5.210 -        dev = self.getDevice(id, error=True)
   5.211 -        dev.destroy(change=change, reboot=reboot)
   5.212 -        return dev
   5.213 -
   5.214 -    def deleteDevice(self, id, change=True):
   5.215 -        """Destroy a device and delete it.
   5.216 -        Normally called to remove a device from a domain at runtime.
   5.217 -        """
   5.218 -        dev = self.destroyDevice(id, change=change)
   5.219 -        self.removeDevice(dev)
   5.220 -
   5.221 -    def destroyController(self, reboot=False):
   5.222 -        """Destroy all devices and clean up.
   5.223 -        May be defined in subclass.
   5.224 -        If reboot is true the controller is being destroyed for a domain reboot.
   5.225 -        Called at domain shutdown.
   5.226 -        """
   5.227 -        self.destroyed = True
   5.228 -        self.destroyDevices(reboot=reboot)
   5.229 -
   5.230 -    #----------------------------------------------------------------------------
   5.231 -    
   5.232 -    def isDestroyed(self):
   5.233 -        return self.destroyed
   5.234 -
   5.235 -    def getDevice(self, id, error=False):
   5.236 -        dev = self.devices.get(int(id))
   5.237 -        if error and not dev:
   5.238 -            raise XendError("invalid device id: " + str(id))
   5.239 -        return dev
   5.240 -
   5.241 -    def getDeviceIds(self):
   5.242 -        return [ dev.getId() for dev in self.device_order ]
   5.243 -
   5.244 -    def getDevices(self):
   5.245 -        return self.device_order
   5.246 -
   5.247 -    def getDeviceConfig(self, id):
   5.248 -        return self.getDevice(id).getConfig()
   5.249 -
   5.250 -    def getDeviceConfigs(self):
   5.251 -        return [ dev.getConfig() for dev in self.device_order ]
   5.252 -
   5.253 -    def getDeviceSxprs(self):
   5.254 -        return [ dev.sxpr() for dev in self.device_order ]
   5.255 -
   5.256 -    def addDevice(self, dev):
   5.257 -        self.devices[dev.getId()] = dev
   5.258 -        self.device_order.append(dev)
   5.259 -        return dev
   5.260 -
   5.261 -    def removeDevice(self, dev):
   5.262 -        if dev.getId() in self.devices:
   5.263 -            del self.devices[dev.getId()]
   5.264 -        if dev in self.device_order:
   5.265 -            self.device_order.remove(dev)
   5.266 -
   5.267 -    def rebootDevices(self):
   5.268 -        for dev in self.getDevices():
   5.269 -            dev.reboot()
   5.270 -
   5.271 -    def destroyDevices(self, reboot=False):
   5.272 -        """Destroy all devices.
   5.273 -        """
   5.274 -        for dev in self.getDevices():
   5.275 -            dev.destroy(reboot=reboot)
   5.276 -
   5.277 -    def getMaxDeviceId(self):
   5.278 -        maxid = 0
   5.279 -        for id in self.devices:
   5.280 -            if id > maxid:
   5.281 -                maxid = id
   5.282 -        return maxid
   5.283 -
   5.284 -    def nextDeviceId(self):
   5.285 -        id = self.deviceId
   5.286 -        self.deviceId += 1
   5.287 -        return id
   5.288 -
   5.289 -    def getDeviceCount(self):
   5.290 -        return len(self.devices)
   5.291 -
   5.292 -class Dev:
   5.293 -    """Abstract class for a device attached to a device controller.
   5.294 -
   5.295 -    @ivar id:        identifier
   5.296 -    @type id:        int
   5.297 -    @ivar controller: device controller
   5.298 -    @type controller: DevController
   5.299 -    """
   5.300 -    
   5.301 -    # ./status       : need 2: actual and requested?
   5.302 -    # down-down: initial.
   5.303 -    # up-up: fully up.
   5.304 -    # down-up: down requested, still up. Watch front and back, when both
   5.305 -    # down go to down-down. But what if one (or both) is not connected?
   5.306 -    # Still have front/back trees with status? Watch front/status, back/status?
   5.307 -    # up-down: up requested, still down.
   5.308 -    # Back-end watches ./status, front/status
   5.309 -    # Front-end watches ./status, back/status
   5.310 -    # i.e. each watches the other 2.
   5.311 -    # Each is status/request status/actual?
   5.312 -    #
   5.313 -    # backend?
   5.314 -    # frontend?
   5.315 -
   5.316 -    __exports__ = [
   5.317 -        DBVar('id',        ty='int'),
   5.318 -        DBVar('type',      ty='str'),
   5.319 -        DBVar('config',    ty='sxpr'),
   5.320 -        DBVar('destroyed', ty='bool'),
   5.321 -        ]
   5.322 -
   5.323 -    def __init__(self, controller, id, config, recreate=False):
   5.324 -        self.controller = controller
   5.325 -        self.id = id
   5.326 -        self.config = config
   5.327 -        self.destroyed = False
   5.328 -        self.type = self.getType()
   5.329 -
   5.330 -        self.db = controller.getDevDB(id)
   5.331 -
   5.332 -    def exportToDB(self, save=False):
   5.333 -        self.db.exportToDB(self, fields=self.__exports__, save=save)
   5.334 -
   5.335 -    def importFromDB(self):
   5.336 -        self.db.importFromDB(self, fields=self.__exports__)
   5.337 -
   5.338 -    def getDomain(self):
   5.339 -        return self.controller.getDomain()
   5.340 -
   5.341 -    def getDomainName(self):
   5.342 -        return self.controller.getDomainName()
   5.343 -
   5.344 -    def getDomainInfo(self):
   5.345 -        return self.controller.getDomainInfo()
   5.346 -    
   5.347 -    def getController(self):
   5.348 -        return self.controller
   5.349 -
   5.350 -    def getType(self):
   5.351 -        return self.controller.getType()
   5.352 -
   5.353 -    def getId(self):
   5.354 -        return self.id
   5.355 -
   5.356 -    def getConfig(self):
   5.357 -        return self.config
   5.358 -
   5.359 -    def isDestroyed(self):
   5.360 -        return self.destroyed
   5.361 -
   5.362 -    #----------------------------------------------------------------------------
   5.363 -    # Subclass interface.
   5.364 -    # Define methods in subclass as needed.
   5.365 -    # Redefinitions must have the same arguments.
   5.366 -
   5.367 -    def init(self, recreate=False, reboot=False):
   5.368 -        """Initialization. Called on initial create (when reboot is False)
   5.369 -        and on reboot (when reboot is True). When xend is restarting is
   5.370 -        called with recreate True. Define in subclass if needed.
   5.371 -
   5.372 -        Device instance variables must be defined in the class constructor,
   5.373 -        but given null or default values. The real values should be initialised
   5.374 -        in this method. This allows devices to be re-initialised.
   5.375 -
   5.376 -        Since this can be called to re-initialise a device any state flags
   5.377 -        should be reset.
   5.378 -        """
   5.379 -        self.destroyed = False
   5.380 -
   5.381 -    def attach(self, recreate=False, change=False):
   5.382 -        """Attach the device to its front and back ends.
   5.383 -        Define in subclass if needed.
   5.384 -        """
   5.385 -        pass
   5.386 -
   5.387 -    def reboot(self):
   5.388 -        """Reconnect the device when the domain is rebooted.
   5.389 -        """
   5.390 -        self.init(reboot=True)
   5.391 -        self.attach()
   5.392 -
   5.393 -    def sxpr(self):
   5.394 -        """Get the s-expression for the deivice.
   5.395 -        Implement in a subclass if needed.
   5.396 -
   5.397 -        @return: sxpr
   5.398 -        """
   5.399 -        return self.getConfig()
   5.400 -
   5.401 -    def configure(self, config, change=False):
   5.402 -        """Reconfigure the device.
   5.403 -
   5.404 -        Implement in subclass.
   5.405 -        """
   5.406 -        raise NotImplementedError()
   5.407 -
   5.408 -    def refresh(self):
   5.409 -        """Refresh the device..
   5.410 -        Default no-op. Define in subclass if needed.
   5.411 -        """
   5.412 -        pass
   5.413 -
   5.414 -    def destroy(self, change=False, reboot=False):
   5.415 -        """Destroy the device.
   5.416 -        If change is True notify destruction (runtime change).
   5.417 -        If reboot is True the device is being destroyed for a reboot.
   5.418 -        Redefine in subclass if needed.
   5.419 -
   5.420 -        Called at domain shutdown and when a device is deleted from
   5.421 -        a running domain (with change True).
   5.422 -        """
   5.423 -        self.destroyed = True
   5.424 -        pass
   5.425 -    
   5.426 -    #----------------------------------------------------------------------------
     6.1 --- a/tools/python/xen/xend/server/netif.py	Sun Sep 18 14:42:13 2005 +0100
     6.2 +++ b/tools/python/xen/xend/server/netif.py	Sun Sep 18 15:41:28 2005 +0100
     6.3 @@ -13,396 +13,64 @@
     6.4  # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
     6.5  #============================================================================
     6.6  # Copyright (C) 2004, 2005 Mike Wray <mike.wray@hp.com>
     6.7 +# Copyright (C) 2005 XenSource Ltd
     6.8  #============================================================================
     6.9  
    6.10 +
    6.11  """Support for virtual network interfaces.
    6.12  """
    6.13  
    6.14 -import random
    6.15 -
    6.16 -from xen.util.mac import macFromString, macToString
    6.17 +import os
    6.18  
    6.19  from xen.xend import sxp
    6.20 -from xen.xend import Vifctl
    6.21 -from xen.xend.XendError import XendError, VmError
    6.22 -from xen.xend.XendLogging import log
    6.23 -from xen.xend import XendVnet
    6.24 -from xen.xend.XendRoot import get_component
    6.25 -from xen.xend.xenstore import DBVar
    6.26 -
    6.27 -from xen.xend.server.controller import Dev, DevController
    6.28 -
    6.29 -class NetDev(Dev):
    6.30 -    """A network device.
    6.31 -    """
    6.32 -
    6.33 -    # State:
    6.34 -    # inherited + 
    6.35 -    # ./config
    6.36 -    # ./mac
    6.37 -    # ./be_mac
    6.38 -    # ./bridge
    6.39 -    # ./script
    6.40 -    # ./ipaddr ?
    6.41 -    #
    6.42 -    # ./credit
    6.43 -    # ./period
    6.44 -    #
    6.45 -    # ./vifctl: up/down?
    6.46 -    # ./vifname
    6.47 -    #
    6.48 -    #
    6.49 -    # Poss should have no backend state here - except for ref to backend's own tree
    6.50 -    # for the device? And a status - the one we want.
    6.51 -    # ./back/dom
    6.52 -    # ./back/devid - id for back-end (netif_handle) - same as front/devid
    6.53 -    # ./back/id    - backend id (if more than one b/e per domain)
    6.54 -    # ./back/status
    6.55 -    # ./back/tx_shmem_frame  - actually these belong in back-end state
    6.56 -    # ./back/rx_shmem_frame
    6.57 -    #
    6.58 -    # ./front/dom
    6.59 -    # ./front/devid
    6.60 -    # ./front/status - need 2: one for requested, one for actual? Or drive from dev status
    6.61 -    # and this is front status only.
    6.62 -    # ./front/tx_shmem_frame
    6.63 -    # ./front/rx_shmem_frame
    6.64 -    #
    6.65 -    # ./evtchn/front - here or in front/back?
    6.66 -    # ./evtchn/back
    6.67 -    # ./evtchn/status ?
    6.68 -    # At present created by dev: but should be created unbound by front/back
    6.69 -    # separately and then bound (by back)?
    6.70 -
    6.71 -    __exports__ = Dev.__exports__ + [
    6.72 -        DBVar('config',  ty='sxpr'),
    6.73 -        DBVar('mac',     ty='mac'),
    6.74 -        DBVar('be_mac',  ty='mac'),
    6.75 -        DBVar('bridge',  ty='str'),
    6.76 -        DBVar('script',  ty='str'),
    6.77 -        DBVar('credit',  ty='int'),
    6.78 -        DBVar('period',  ty='int'),
    6.79 -        DBVar('vifname', ty='str'),
    6.80 -        ]
    6.81 -
    6.82 -    def __init__(self, controller, id, config, recreate=False):
    6.83 -        Dev.__init__(self, controller, id, config, recreate=recreate)
    6.84 -        self.vif = int(self.id)
    6.85 -        self.status = None
    6.86 -        self.frontendDomain = self.getDomain()
    6.87 -        self.backendDomain = None
    6.88 -        self.credit = None
    6.89 -        self.period = None
    6.90 -        self.mac = None
    6.91 -        self.be_mac = None
    6.92 -        self.bridge = None
    6.93 -        self.script = None
    6.94 -        self.ipaddr = None
    6.95 -        self.mtu = None
    6.96 -        self.vifname = None
    6.97 -        self.configure(self.config, recreate=recreate)
    6.98 -
    6.99 -    def exportToDB(self, save=False):
   6.100 -        Dev.exportToDB(self, save=save)
   6.101  
   6.102 -    def init(self, recreate=False, reboot=False):
   6.103 -        self.destroyed = False
   6.104 -        self.status = NETIF_INTERFACE_STATUS_DISCONNECTED
   6.105 -        self.frontendDomain = self.getDomain()
   6.106 -
   6.107 -    def _get_config_mac(self, config):
   6.108 -        vmac = sxp.child_value(config, 'mac')
   6.109 -        if not vmac: return None
   6.110 -        try:
   6.111 -            mac = macFromString(vmac)
   6.112 -        except:
   6.113 -            raise XendError("invalid mac: %s" % vmac)
   6.114 -        return mac
   6.115 -
   6.116 -    def _get_config_be_mac(self, config):
   6.117 -        vmac = sxp.child_value(config, 'be_mac')
   6.118 -        if not vmac: return None
   6.119 -        try:
   6.120 -            mac = macFromString(vmac)
   6.121 -        except:
   6.122 -            raise XendError("invalid backend mac: %s" % vmac)
   6.123 -        return mac
   6.124 -
   6.125 -    def _get_config_ipaddr(self, config):
   6.126 -        ips = sxp.children(config, elt='ip')
   6.127 -        if ips:
   6.128 -            val = []
   6.129 -            for ipaddr in ips:
   6.130 -                val.append(sxp.child0(ipaddr))
   6.131 -        else:
   6.132 -            val = None
   6.133 -        return val
   6.134 -
   6.135 -    def _get_config_mtu(self, config):
   6.136 -        mtu = sxp.child_value(config, 'mtu')
   6.137 -        if not mtu: return None
   6.138 -        try:
   6.139 -            mtu = int(mtu)
   6.140 -        except:
   6.141 -            raise XendError("invalid mtu: %s" & mtu)
   6.142 -        return mtu
   6.143 +from xen.xend.server.DevController import DevController
   6.144  
   6.145 -    def configure(self, config, change=False, recreate=False):
   6.146 -        if change:
   6.147 -            return self.reconfigure(config)
   6.148 -        self.config = config
   6.149 -        self.mac = None
   6.150 -        self.be_mac = None
   6.151 -        self.bridge = None
   6.152 -        self.script = None
   6.153 -        self.ipaddr = []
   6.154 -        self.vifname = None
   6.155 -
   6.156 -        self.vifname = sxp.child_value(config, 'vifname')
   6.157 -        if self.vifname is None:
   6.158 -            self.vifname = self.default_vifname()
   6.159 -        if len(self.vifname) > 15:
   6.160 -            raise XendError('invalid vifname: too long: ' + self.vifname)
   6.161 -        mac = self._get_config_mac(config)
   6.162 -        if mac is None:
   6.163 -            raise XendError("invalid mac")
   6.164 -        self.mac = mac
   6.165 -        self.be_mac = self._get_config_be_mac(config)
   6.166 -        self.bridge = sxp.child_value(config, 'bridge')
   6.167 -        self.script = sxp.child_value(config, 'script')
   6.168 -        self.ipaddr = self._get_config_ipaddr(config) or []
   6.169 -        self.mtu = self._get_config_mtu(config)
   6.170 -        self._config_credit_limit(config)
   6.171 -        
   6.172 -        try:
   6.173 -            if recreate:
   6.174 -                self.backendDomain = int(sxp.child_value(config, 'backend', '0'))
   6.175 -            else:
   6.176 -                #todo: Code below will fail on xend restart when backend is not domain 0.
   6.177 -                xd = get_component('xen.xend.XendDomain')
   6.178 -                self.backendDomain = xd.domain_lookup_by_name(sxp.child_value(config, 'backend', '0')).domid
   6.179 -        except:
   6.180 -            raise XendError('invalid backend domain')
   6.181 -        return self.config
   6.182 -
   6.183 -    def reconfigure(self, config):
   6.184 -        """Reconfigure the interface with new values.
   6.185 -        Not all configuration parameters can be changed:
   6.186 -        bridge, script and ip addresses can,
   6.187 -        backend and mac cannot.
   6.188 -
   6.189 -        To leave a parameter unchanged, omit it from the changes.
   6.190  
   6.191 -        @param config configuration changes
   6.192 -        @return updated interface configuration
   6.193 -        @raise XendError on errors
   6.194 -        """
   6.195 -        changes = {}
   6.196 -        mac = self._get_config_mac(config)
   6.197 -        be_mac = self._get_config_be_mac(config)
   6.198 -        bridge = sxp.child_value(config, 'bridge')
   6.199 -        script = sxp.child_value(config, 'script')
   6.200 -        ipaddr = self._get_config_ipaddr(config)
   6.201 -        mtu = self._get_config_mtu(config)
   6.202 -        
   6.203 -        xd = get_component('xen.xend.XendDomain')
   6.204 -        backendDomain = xd.domain_lookup_by_name(sxp.child_value(config, 'backend', '0')).domid
   6.205 -
   6.206 -        if (mac is not None) and (mac != self.mac):
   6.207 -            raise XendError("cannot change mac")
   6.208 -        if (be_mac is not None) and (be_mac != self.be_mac):
   6.209 -            raise XendError("cannot change backend mac")
   6.210 -        if (backendDomain is not None) and (backendDomain != self.backendDomain):
   6.211 -            raise XendError("cannot change backend")
   6.212 -        if (bridge is not None) and (bridge != self.bridge):
   6.213 -            changes['bridge'] = bridge
   6.214 -        if (script is not None) and (script != self.script):
   6.215 -            changes['script'] = script
   6.216 -        if (ipaddr is not None) and (ipaddr != self.ipaddr):
   6.217 -            changes['ipaddr'] = ipaddr
   6.218 -        if (mtu is not None) and (mtu != self.mtu):
   6.219 -            changes['mtu'] = mtu
   6.220 -
   6.221 -        if changes:
   6.222 -            self.vifctl("down")
   6.223 -            for (k, v) in changes.items():
   6.224 -                setattr(self, k, v)
   6.225 -            self.config = sxp.merge(config, self.config)
   6.226 -            self.vifctl("up")
   6.227 -
   6.228 -        self._config_credit_limit(config, change=True)
   6.229 -        return self.config
   6.230 -
   6.231 -    def _config_credit_limit(self, config, change=False):
   6.232 -        period = sxp.child_value(config, 'period')
   6.233 -        credit = sxp.child_value(config, 'credit')
   6.234 -        if period and credit:
   6.235 -            try:
   6.236 -                period = int(period)
   6.237 -                credit = int(credit)
   6.238 -            except ex:
   6.239 -                raise XendError('vif: invalid credit limit')
   6.240 -            if change:
   6.241 -                self.setCreditLimit(credit, period)
   6.242 -                self.config = sxp.merge([sxp.name(self.config),
   6.243 -                                         ['credit', credit],
   6.244 -                                         ['period', period]],
   6.245 -                                        self.config)
   6.246 -            else:
   6.247 -                self.period = period
   6.248 -                self.credit = credit
   6.249 -        elif period or credit:
   6.250 -            raise XendError('vif: invalid credit limit')
   6.251 -
   6.252 -    def sxpr(self):
   6.253 -        vif = str(self.vif)
   6.254 -        mac = self.get_mac()
   6.255 -        val = ['vif',
   6.256 -               ['id', self.id],
   6.257 -               ['vif', vif],
   6.258 -               ['mac', mac],
   6.259 -               ['vifname', self.vifname],
   6.260 -               ]
   6.261 -
   6.262 -        if self.be_mac:
   6.263 -            val.append(['be_mac', self.get_be_mac()])
   6.264 -        if self.bridge:
   6.265 -            val.append(['bridge', self.bridge])
   6.266 -        if self.script:
   6.267 -            val.append(['script', self.script])
   6.268 -        for ip in self.ipaddr:
   6.269 -            val.append(['ip', ip])
   6.270 -        if self.credit:
   6.271 -            val.append(['credit', self.credit])
   6.272 -        if self.period:
   6.273 -            val.append(['period', self.period])
   6.274 -        return val
   6.275 +next_devid = 1
   6.276  
   6.277 -    def get_vifname(self):
   6.278 -        """Get the virtual interface device name.
   6.279 -        """
   6.280 -        return self.vifname
   6.281  
   6.282 -    def default_vifname(self):
   6.283 -        return "vif%d.%d" % (self.frontendDomain, self.vif)
   6.284 -    
   6.285 -    def get_mac(self):
   6.286 -        """Get the MAC address as a string.
   6.287 -        """
   6.288 -        return macToString(self.mac)
   6.289 -
   6.290 -    def get_be_mac(self):
   6.291 -        """Get the backend MAC address as a string.
   6.292 -        """
   6.293 -        return macToString(self.be_mac)
   6.294 -
   6.295 -    def vifctl_params(self, vmname=None):
   6.296 -        """Get the parameters to pass to vifctl.
   6.297 -        """
   6.298 -        dom = self.frontendDomain
   6.299 -        if vmname is None:
   6.300 -            xd = get_component('xen.xend.XendDomain')
   6.301 -            try:
   6.302 -                vm = xd.domain_lookup(dom)
   6.303 -                vmname = vm.name
   6.304 -            except:
   6.305 -                vmname = 'Domain-%d' % dom
   6.306 -        return { 'domain': vmname,
   6.307 -                 'vif'   : self.get_vifname(), 
   6.308 -                 'mac'   : self.get_mac(),
   6.309 -                 'bridge': self.bridge,
   6.310 -                 'script': self.script,
   6.311 -                 'ipaddr': self.ipaddr, }
   6.312 -
   6.313 -    def vifctl(self, op, vmname=None):
   6.314 -        """Bring the device up or down.
   6.315 -        The vmname is needed when bringing a device up for a new domain because
   6.316 -        the domain is not yet in the table so we can't look its name up.
   6.317 -
   6.318 -        @param op: operation name (up, down)
   6.319 -        @param vmname: vmname
   6.320 -        """
   6.321 -        if op == 'up':
   6.322 -            Vifctl.set_vif_name(self.default_vifname(), self.vifname)
   6.323 -        Vifctl.vifctl(op, **self.vifctl_params(vmname=vmname))
   6.324 -        vnet = XendVnet.instance().vnet_of_bridge(self.bridge)
   6.325 -        if vnet:
   6.326 -            vnet.vifctl(op, self.get_vifname(), self.get_mac())
   6.327 -
   6.328 -    def attach(self, recreate=False, change=False):
   6.329 -        if recreate:
   6.330 -            pass
   6.331 -        else:
   6.332 -            if self.credit and self.period:
   6.333 -                #self.send_be_creditlimit(self.credit, self.period)
   6.334 -                pass
   6.335 -            self.vifctl('up', vmname=self.getDomainName())
   6.336 -        
   6.337 -    def destroy(self, change=False, reboot=False):
   6.338 -        """Destroy the device's resources and disconnect from the back-end
   6.339 -        device controller. If 'change' is true notify the front-end interface.
   6.340 -
   6.341 -        @param change: change flag
   6.342 -        """
   6.343 -        self.destroyed = True
   6.344 -        self.status = NETIF_INTERFACE_STATUS_CLOSED
   6.345 -        log.debug("Destroying vif domain=%d vif=%d", self.frontendDomain, self.vif)
   6.346 -        self.vifctl('down')
   6.347 -        if change:
   6.348 -            self.reportStatus()
   6.349 -
   6.350 -    def setCreditLimit(self, credit, period):
   6.351 -        #todo: these params should be in sxpr and vif config.
   6.352 -        self.credit = credit
   6.353 -        self.period = period
   6.354 -
   6.355 -    def getCredit(self):
   6.356 -        return self.credit
   6.357 -
   6.358 -    def getPeriod(self):
   6.359 -        return self.period
   6.360 -        
   6.361 -    def interfaceChanged(self):
   6.362 -        """Notify the front-end that a device has been added or removed.
   6.363 -        """
   6.364 -        pass
   6.365 -        
   6.366  class NetifController(DevController):
   6.367      """Network interface controller. Handles all network devices for a domain.
   6.368      """
   6.369      
   6.370 -    def __init__(self, vm, recreate=False):
   6.371 -        DevController.__init__(self, vm, recreate=recreate)
   6.372 +    def __init__(self, vm):
   6.373 +        DevController.__init__(self, vm)
   6.374 +
   6.375 +
   6.376 +    def getDeviceDetails(self, config):
   6.377 +        """@see DevController.getDeviceDetails"""
   6.378 +
   6.379 +        global next_devid
   6.380  
   6.381 -    def initController(self, recreate=False, reboot=False):
   6.382 -        self.destroyed = False
   6.383 -        if reboot:
   6.384 -            self.rebootDevices()
   6.385 +        from xen.xend import XendRoot
   6.386 +        xroot = XendRoot.instance()
   6.387  
   6.388 -    def destroyController(self, reboot=False):
   6.389 -        """Destroy the controller and all devices.
   6.390 -        """
   6.391 -        self.destroyed = True
   6.392 -        log.debug("Destroying netif domain=%d", self.getDomain())
   6.393 -        self.destroyDevices(reboot=reboot)
   6.394 +        def _get_config_ipaddr(config):
   6.395 +            val = []
   6.396 +            for ipaddr in sxp.children(config, elt='ip'):
   6.397 +                val.append(sxp.child0(ipaddr))
   6.398 +            return val
   6.399  
   6.400 -    def sxpr(self):
   6.401 -        val = ['netif', ['dom', self.getDomain()]]
   6.402 -        return val
   6.403 -    
   6.404 -    def newDevice(self, id, config, recreate=False):
   6.405 -        """Create a network device.
   6.406 +        devid = next_devid
   6.407 +        next_devid += 1
   6.408 +
   6.409 +        script = os.path.join(xroot.network_script_dir,
   6.410 +                              sxp.child_value(config, 'script',
   6.411 +                                              xroot.get_vif_script()))
   6.412 +        bridge = sxp.child_value(config, 'bridge',
   6.413 +                                 xroot.get_vif_bridge())
   6.414 +        mac = sxp.child_value(config, 'mac')
   6.415 +        ipaddr = _get_config_ipaddr(config)
   6.416  
   6.417 -        @param id: interface id
   6.418 -        @param config: device configuration
   6.419 -        @param recreate: recreate flag (true after xend restart)
   6.420 -        """
   6.421 -        return NetDev(self, id, config, recreate=recreate)
   6.422 +        back = { 'script' : script,
   6.423 +                 'mac' : mac,
   6.424 +                 'bridge' : bridge,
   6.425 +                 'handle' : "%i" % devid }
   6.426 +        if ipaddr:
   6.427 +            back['ip'] = ' '.join(ipaddr)
   6.428  
   6.429 -    def limitDevice(self, vif, credit, period):        
   6.430 -        if vif not in self.devices:
   6.431 -            raise XendError('device does not exist for credit limit: vif'
   6.432 -                            + str(self.getDomain()) + '.' + str(vif))
   6.433 -        
   6.434 -        dev = self.devices[vif]
   6.435 -        return dev.setCreditLimit(credit, period)
   6.436 +        front = { 'handle' : "%i" % devid,
   6.437 +                  'mac' : mac }
   6.438 +
   6.439 +        return (devid, back, front)
     7.1 --- a/tools/python/xen/xend/server/pciif.py	Sun Sep 18 14:42:13 2005 +0100
     7.2 +++ b/tools/python/xen/xend/server/pciif.py	Sun Sep 18 15:41:28 2005 +0100
     7.3 @@ -13,16 +13,22 @@
     7.4  # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
     7.5  #============================================================================
     7.6  # Copyright (C) 2004, 2005 Mike Wray <mike.wray@hp.com>
     7.7 +# Copyright (C) 2005 XenSource Ltd
     7.8  #============================================================================
     7.9  
    7.10 +
    7.11  import types
    7.12  
    7.13 -import xen.lowlevel.xc; xc = xen.lowlevel.xc.new()
    7.14 +import xen.lowlevel.xc;
    7.15  
    7.16  from xen.xend import sxp
    7.17  from xen.xend.XendError import VmError
    7.18  
    7.19 -from controller import Dev, DevController
    7.20 +from xen.xend.server.DevController import DevController
    7.21 +
    7.22 +
    7.23 +xc = xen.lowlevel.xc.new()
    7.24 +
    7.25  
    7.26  def parse_pci(val):
    7.27      """Parse a pci field.
    7.28 @@ -36,27 +42,32 @@ def parse_pci(val):
    7.29          v = val
    7.30      return v
    7.31  
    7.32 -class PciDev(Dev):
    7.33 +
    7.34 +class PciController(DevController):
    7.35 +
    7.36 +    def __init__(self, vm):
    7.37 +        DevController.__init__(self, vm)
    7.38 +
    7.39 +
    7.40 +    def getDeviceDetails(self, config):
    7.41 +        """@see DevController.getDeviceDetails"""
    7.42  
    7.43 -    def __init__(self, controller, id, config, recreate=False):
    7.44 -        Dev.__init__(self, controller, id, config, recreate=recreate)
    7.45 -        bus = sxp.child_value(self.config, 'bus')
    7.46 -        if not bus:
    7.47 -            raise VmError('pci: Missing bus')
    7.48 -        dev = sxp.child_value(self.config, 'dev')
    7.49 -        if not dev:
    7.50 -            raise VmError('pci: Missing dev')
    7.51 -        func = sxp.child_value(self.config, 'func')
    7.52 -        if not func:
    7.53 -            raise VmError('pci: Missing func')
    7.54 -        try:
    7.55 -            bus = parse_pci(bus)
    7.56 -            dev = parse_pci(dev)
    7.57 -            func = parse_pci(func)
    7.58 -        except:
    7.59 -            raise VmError('pci: invalid parameter')
    7.60 +        def get_param(field):
    7.61 +            try:
    7.62 +                val = sxp.child_value(config, field)
    7.63 +
    7.64 +                if not val:
    7.65 +                    raise VmError('pci: Missing %s config setting' % field)
    7.66  
    7.67 -    def attach(self, recreate=False, change=False):
    7.68 +                return parse_pci(val)
    7.69 +            except:
    7.70 +                raise VmError('pci: Invalid config setting %s: %s' %
    7.71 +                              (field, val))
    7.72 +        
    7.73 +        bus  = get_param('bus')
    7.74 +        dev  = get_param('dev')
    7.75 +        func = get_param('func')
    7.76 +
    7.77          rc = xc.physdev_pci_access_modify(dom    = self.getDomain(),
    7.78                                            bus    = bus,
    7.79                                            dev    = dev,
    7.80 @@ -64,13 +75,8 @@ class PciDev(Dev):
    7.81                                            enable = True)
    7.82          if rc < 0:
    7.83              #todo non-fatal
    7.84 -            raise VmError('pci: Failed to configure device: bus=%s dev=%s func=%s' %
    7.85 -                          (bus, dev, func))
    7.86 +            raise VmError(
    7.87 +                'pci: Failed to configure device: bus=%s dev=%s func=%s' %
    7.88 +                (bus, dev, func))
    7.89  
    7.90 -    def destroy(self, change=False, reboot=False):
    7.91 -        pass
    7.92 -
    7.93 -class PciController(DevController):
    7.94 -
    7.95 -    def newDevice(self, id, config, recreate=False):
    7.96 -        return PciDev(self, id, config, recreate=recreate)
    7.97 +        return (dev, {}, {})
     8.1 --- a/tools/python/xen/xend/server/tpmif.py	Sun Sep 18 14:42:13 2005 +0100
     8.2 +++ b/tools/python/xen/xend/server/tpmif.py	Sun Sep 18 15:41:28 2005 +0100
     8.3 @@ -1,45 +1,47 @@
     8.4 +#============================================================================
     8.5 +# This library is free software; you can redistribute it and/or
     8.6 +# modify it under the terms of version 2.1 of the GNU Lesser General Public
     8.7 +# License as published by the Free Software Foundation.
     8.8 +#
     8.9 +# This library is distributed in the hope that it will be useful,
    8.10 +# but WITHOUT ANY WARRANTY; without even the implied warranty of
    8.11 +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    8.12 +# Lesser General Public License for more details.
    8.13 +#
    8.14 +# You should have received a copy of the GNU Lesser General Public
    8.15 +# License along with this library; if not, write to the Free Software
    8.16 +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
    8.17 +#============================================================================
    8.18 +# Copyright (C) 2004 Mike Wray <mike.wray@hp.com>
    8.19  # Copyright (C) 2005 IBM Corporation
    8.20 -#   Authort: Stefan Berger, stefanb@us.ibm.com
    8.21 -# Derived from netif.py:
    8.22 -# Copyright (C) 2004 Mike Wray <mike.wray@hp.com>
    8.23 +#   Author: Stefan Berger, stefanb@us.ibm.com
    8.24 +# Copyright (C) 2005 XenSource Ltd
    8.25 +#============================================================================
    8.26 +
    8.27  """Support for virtual TPM interfaces.
    8.28  """
    8.29  
    8.30 -import random
    8.31 -
    8.32  from xen.xend import sxp
    8.33 -from xen.xend.XendError import XendError, VmError
    8.34  from xen.xend.XendLogging import log
    8.35 -from xen.xend.XendRoot import get_component
    8.36 -from xen.xend.xenstore import DBVar
    8.37  
    8.38 -from xen.xend.server.controller import Dev, DevController
    8.39 +from xen.xend.server.DevController import DevController
    8.40 +
    8.41  
    8.42  class TPMifController(DevController):
    8.43      """TPM interface controller. Handles all TPM devices for a domain.
    8.44      """
    8.45  
    8.46 -    def __init__(self, vm, recreate=False):
    8.47 -        DevController.__init__(self, vm, recreate=recreate)
    8.48 -
    8.49 -    def initController(self, recreate=False, reboot=False):
    8.50 -        self.destroyed = False
    8.51 +    def __init__(self, vm):
    8.52 +        DevController.__init__(self, vm)
    8.53  
    8.54 -    def destroyController(self, reboot=False):
    8.55 -        """Destroy the controller and all devices.
    8.56 -        """
    8.57 -        self.destroyed = True
    8.58 -        self.destroyDevices(reboot=reboot)
    8.59  
    8.60 -    def sxpr(self):
    8.61 -        val = ['tpmif', ['dom', self.getDomain()]]
    8.62 -        return val
    8.63 +    def getDeviceDetails(self, config):
    8.64 +        """@see DevController.getDeviceDetails"""
    8.65 +        
    8.66 +        devid = int(sxp.child_value(config, 'instance', '0'))
    8.67 +        log.error("The domain has a TPM with instance %d." % devid)
    8.68  
    8.69 -    def newDevice(self, id, config, recreate=False):
    8.70 -        """Create a TPM device.
    8.71 +        back  = { 'instance' : "%i" % devid }
    8.72 +        front = { 'handle' : "%i" % devid }
    8.73  
    8.74 -        @param id: interface id
    8.75 -        @param config: device configuration
    8.76 -        @param recreate: recreate flag (true after xend restart)
    8.77 -        """
    8.78 -        return None
    8.79 +        return (devid, back, front)
     9.1 --- a/tools/python/xen/xend/server/usbif.py	Sun Sep 18 14:42:13 2005 +0100
     9.2 +++ b/tools/python/xen/xend/server/usbif.py	Sun Sep 18 15:41:28 2005 +0100
     9.3 @@ -1,185 +1,50 @@
     9.4 +#============================================================================
     9.5 +# This library is free software; you can redistribute it and/or
     9.6 +# modify it under the terms of version 2.1 of the GNU Lesser General Public
     9.7 +# License as published by the Free Software Foundation.
     9.8 +#
     9.9 +# This library is distributed in the hope that it will be useful,
    9.10 +# but WITHOUT ANY WARRANTY; without even the implied warranty of
    9.11 +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    9.12 +# Lesser General Public License for more details.
    9.13 +#
    9.14 +# You should have received a copy of the GNU Lesser General Public
    9.15 +# License along with this library; if not, write to the Free Software
    9.16 +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
    9.17 +#============================================================================
    9.18  # Copyright (C) 2004 Mike Wray <mike.wray@hp.com>
    9.19  # Copyright (C) 2004 Intel Research Cambridge
    9.20  # Copyright (C) 2004 Mark Williamson <mark.williamson@cl.cam.ac.uk>
    9.21 +# Copyright (C) 2005 XenSource Ltd
    9.22 +#============================================================================
    9.23 +
    9.24 +
    9.25  """Support for virtual USB hubs.
    9.26  """
    9.27  
    9.28 -from xen.xend import sxp
    9.29 -from xen.xend.XendLogging import log
    9.30 -from xen.xend.XendError import XendError
    9.31 -from xen.xend.xenstore import DBVar
    9.32 -
    9.33 -from xen.xend.server.controller import Dev, DevController
    9.34 -
    9.35 -class UsbBackend:
    9.36 -    """Handler for the 'back-end' channel to a USB device driver domain
    9.37 -    on behalf of a front-end domain.
    9.38 -    """
    9.39 -    def __init__(self, controller, id, dom):
    9.40 -        self.controller = controller
    9.41 -        self.id = id
    9.42 -        self.destroyed = False
    9.43 -        self.connected = False
    9.44 -        self.connecting = False
    9.45 -        self.frontendDomain = self.controller.getDomain()
    9.46 -        self.backendDomain = dom
    9.47 -
    9.48 -    def init(self, recreate=False, reboot=False):
    9.49 -        pass
    9.50 -    
    9.51 -    def __str__(self):
    9.52 -        return ('<UsbifBackend frontend=%d backend=%d id=%d>'
    9.53 -                % (self.frontendDomain,
    9.54 -                   self.backendDomain,
    9.55 -                   self.id))
    9.56 -
    9.57 -    def connect(self, recreate=False):
    9.58 -        """Connect the controller to the usbif control interface.
    9.59 -
    9.60 -        @param recreate: true if after xend restart
    9.61 -        """
    9.62 -        log.debug("Connecting usbif %s", str(self))
    9.63 -        if recreate or self.connected or self.connecting:
    9.64 -            pass
    9.65 -        
    9.66 -    def destroy(self, reboot=False):
    9.67 -        """Disconnect from the usbif control interface and destroy it.
    9.68 -        """
    9.69 -        self.destroyed = True
    9.70 -        
    9.71 -    def interfaceChanged(self):
    9.72 -        pass
    9.73 +from xen.xend.server.DevController import DevController
    9.74  
    9.75  
    9.76 -class UsbDev(Dev):
    9.77 -
    9.78 -    __exports__ = Dev.__exports__ + [
    9.79 -        DBVar('port', ty='int'),
    9.80 -        DBVar('path', ty='str'),
    9.81 -        ]
    9.82 -    
    9.83 -    def __init__(self, controller, id, config, recreate=False):
    9.84 -        Dev.__init__(self, controller, id, config, recreate=recreate)
    9.85 -        self.port = id
    9.86 -        self.path = None
    9.87 -        self.frontendDomain = self.getDomain()
    9.88 -        self.backendDomain = 0
    9.89 -        self.configure(self.config, recreate=recreate)
    9.90 -
    9.91 -    def init(self, recreate=False, reboot=False):
    9.92 -        self.destroyed = False
    9.93 -        self.frontendDomain = self.getDomain()
    9.94 -        
    9.95 -    def configure(self, config, change=False, recreate=False):
    9.96 -        if change:
    9.97 -            raise XendError("cannot reconfigure usb")
    9.98 -        #todo: FIXME: Use sxp access methods to get this value.
    9.99 -        # Must not use direct indexing.
   9.100 -        self.path = config[1][1]
   9.101 -        
   9.102 -        #todo: FIXME: Support configuring the backend domain.
   9.103 -##         try:
   9.104 -##             self.backendDomain = int(sxp.child_value(config, 'backend', '0'))
   9.105 -##         except:
   9.106 -##             raise XendError('invalid backend domain')
   9.107 +next_devid = 1
   9.108  
   9.109 -    def attach(self, recreate=False, change=False):
   9.110 -        if recreate:
   9.111 -            pass
   9.112 -        else:
   9.113 -            self.attachBackend()
   9.114 -        if change:
   9.115 -            self.interfaceChanged()
   9.116 -            
   9.117 -    def sxpr(self):
   9.118 -        val = ['usb',
   9.119 -               ['id', self.id],
   9.120 -               ['port', self.port],
   9.121 -               ['path', self.path],
   9.122 -               ]
   9.123 -        return val
   9.124 -
   9.125 -    def getBackend(self):
   9.126 -        return self.controller.getBackend(self.backendDomain)
   9.127 -
   9.128 -    def destroy(self, change=False, reboot=False):
   9.129 -        """Destroy the device. If 'change' is true notify the front-end interface.
   9.130 -
   9.131 -        @param change: change flag
   9.132 -        """
   9.133 -        self.destroyed = True
   9.134 -        log.debug("Destroying usb domain=%d id=%s", self.frontendDomain, self.id)
   9.135 -        if change:
   9.136 -            self.interfaceChanged()
   9.137 -
   9.138 -    def interfaceChanged(self):
   9.139 -        """Tell the back-end to notify the front-end that a device has been
   9.140 -        added or removed.
   9.141 -        """
   9.142 -        self.getBackend().interfaceChanged()
   9.143 -
   9.144 -    def attachBackend(self):
   9.145 -        """Attach the device to its controller.
   9.146 -
   9.147 -        """
   9.148 -        self.getBackend().connect()
   9.149  
   9.150  class UsbifController(DevController):
   9.151      """USB device interface controller. Handles all USB devices
   9.152      for a domain.
   9.153      """
   9.154      
   9.155 -    def __init__(self, vm, recreate=False):
   9.156 +    def __init__(self, vm):
   9.157          """Create a USB device controller.
   9.158          """
   9.159 -        DevController.__init__(self, vm, recreate=recreate)
   9.160 -        self.backends = {}
   9.161 -        self.backendId = 0
   9.162 +        DevController.__init__(self, vm)
   9.163  
   9.164 -    def init(self, recreate=False, reboot=False):
   9.165 -        self.destroyed = False
   9.166 -        if reboot:
   9.167 -            self.rebootBackends()
   9.168 -            self.rebootDevices()
   9.169  
   9.170 -    def sxpr(self):
   9.171 -        val = ['usbif',
   9.172 -               ['dom', self.getDomain()]]
   9.173 -        return val
   9.174 -
   9.175 -    def newDevice(self, id, config, recreate=False):
   9.176 -        return UsbDev(self, id, config, recreate=recreate)
   9.177 -
   9.178 -    def destroyController(self, reboot=False):
   9.179 -        """Destroy the controller and all devices.
   9.180 -        """
   9.181 -        self.destroyed = True
   9.182 -        log.debug("Destroying blkif domain=%d", self.getDomain())
   9.183 -        self.destroyDevices(reboot=reboot)
   9.184 -        self.destroyBackends(reboot=reboot)
   9.185 +    def getDeviceDetails(self, _):
   9.186 +        """@see DevController.getDeviceDetails"""
   9.187  
   9.188 -    def rebootBackends(self):
   9.189 -        for backend in self.backends.values():
   9.190 -            backend.init(reboot=True)
   9.191 -
   9.192 -    def getBackendById(self, id):
   9.193 -        return self.backends.get(id)
   9.194 -
   9.195 -    def getBackendByDomain(self, dom):
   9.196 -        for backend in self.backends.values():
   9.197 -            if backend.backendDomain == dom:
   9.198 -                return backend
   9.199 -        return None
   9.200 +        global next_devid
   9.201  
   9.202 -    def getBackend(self, dom):
   9.203 -        backend = self.getBackendByDomain(dom)
   9.204 -        if backend: return backend
   9.205 -        backend = UsbBackend(self, self.backendId, dom)
   9.206 -        self.backendId += 1
   9.207 -        self.backends[backend.getId()] = backend
   9.208 -        backend.init()
   9.209 -        return backend
   9.210 -    
   9.211 -    def destroyBackends(self, reboot=False):
   9.212 -        for backend in self.backends.values():
   9.213 -            backend.destroy(reboot=reboot)
   9.214 +        devid = next_devid
   9.215 +        next_devid += 1
   9.216 +
   9.217 +        return (devid, {}, {})