From: Kurt Garloff Subject: Re: [PATCH] Re: [PATCH 0/3] domUloader Date: Fri, 20 Jan 2006 13:43:05 +0100 Message-ID: <20060120124305.GJ9266@tpkurt.wlan.garloff.de> References: <20060116234330.GC17087@tpkurt.wlan.garloff.de> <20060117123355.GA15336@cray.cl.cam.ac.uk> <1137607621.22846.17.camel@bree.local.net> <20060119130618.GA7984@cray.cl.cam.ac.uk> Mime-Version: 1.0 Content-Type: multipart/mixed; boundary="===============1152378973==" Return-path: In-Reply-To: <20060119130618.GA7984@cray.cl.cam.ac.uk> List-Unsubscribe: , List-Post: List-Help: List-Subscribe: , Mime-version: 1.0 Sender: xen-devel-bounces@lists.xensource.com Errors-To: xen-devel-bounces@lists.xensource.com To: Tim Deegan Cc: Jeremy Katz , xen-devel@lists.xensource.com List-Id: xen-devel@lists.xenproject.org --===============1152378973== Content-Type: multipart/signed; micalg=pgp-sha1; protocol="application/pgp-signature"; boundary="PMULwz+zIGJzpDN9" Content-Disposition: inline --PMULwz+zIGJzpDN9 Content-Type: multipart/mixed; boundary="FUaywKC54iCcLzqT" Content-Disposition: inline --FUaywKC54iCcLzqT Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable Hi Tim, Jeremy, On Thu, Jan 19, 2006 at 01:06:18PM +0000, Tim Deegan wrote: > On Wed, Jan 18, 2006 at 01:07:00PM -0500, Jeremy Katz wrote: > > Sounds reasonable enough, although I'll have to look at it a little > > closer when I get back from Austin. FWIW, partition table handling in > > pygrub should work fine (I'm installing to full disk vbds with partition > > tables regularly) >=20 > The partition handling is only enough to find the "active" partition, so > it doesn't handle extended partitions. That's not a problem for pygrub, > but would need to be done to have the extraction tool handle partitions > properly. pygrub does assume there's one whole disk export which contains a DOS style partition table with the /boot partition marked active. If that one is ext2, everything works fine. (The reiser support failed in my testing.) domUloader is more flexible there. It understands both whole disk=20 devices and partitions, can handle a set of them, finds the /boot partition by having it specified in bootentry or by parsing=20 /etc/fstab on the partition that's been passed to domU with root=3D. Maybe we want to import domUloader in pygrub to just get all this, as the handling is nicely abstracted there. You just don't call domUloader.main(argv) then ... If we do that, the main difference will be that=20 - pygrub offers an interactive (ncurses) mode - pygrub users libraries to get files off the FS, which could be somewhat safer and more easily extensible (but currently is not (yet?) very reliable and limits the FS choice). And I'd really like to advocate for the little changes I have done to XendDomainInfo, XendBootloader and create, so we pass enough information to the bootloader to handle all this. > Also, it doesn't work if your e2fsprogs are too old to have > ext2fs_open2() -- again, not really a bug but the failure mode is a bit > ugly,=20 So I'm not the only that experiences pygrub running OOM? > and the version in the Xen 3 tarball has this problem. Is there > some way of telling from inside a python script whether the pygrub > library is going to be able to read partitions or not? Updated domUloader attached. Best, --=20 Kurt Garloff, Head Architect, Director SUSE Labs (act.), Novell Inc. --FUaywKC54iCcLzqT Content-Type: text/plain; charset=us-ascii Content-Disposition: attachment; filename="domUloader.py" Content-Transfer-Encoding: quoted-printable #!/usr/bin/env python # domUloader.py """Loader for kernel and (optional) ramdisk from domU filesystem =20 Uses bootentry =3D [dev:]kernel[,initrd] to get a kernel [and initrd] from a domU filesystem to boot it for Xen. dev is the disk as seen by domU, filenames are relative to that filesystem. The script uses the disk settings from the config file to find the domU filesystems. The bootentry is passed to the script using --entry=3D Optionally, dev: can be omitted; the script then looks at the root filesystem, parses /etc/fstab to resolve the path to the kernel [and the initrd]. Obviously, the paths relative to the domU root filesystem needs to be specified for the kernel and initrd filenames. The root FS is passed using --root=3D, the filesystem setup in --disks=3D. The disks list is a python list=20 [[uname, dev, mode, backend], [uname, dev, mode, backend], ...] passed as a string. The script writes an sxpr specifying the locations of the copied kernel and initrd into the file specified by --output (default is stdout). Limitations: - It is assumed both kernel and initrd are on the same filesystem. - domUs might use LVM; the script currently does not have support for setting up LVM mappings for domUs; it's not trivial and we=20 might risk namespace conflicts. If you want to use LVM inside domUs, set up a small non-LVM boot partition and specify it in bootentry. =20 The script uses kpartx (multipath-tools) to create mappings for=20 devices that are exported as whole disk devices that are partitioned. (c) 01/2006 Novell Inc License: GNU GPL Author: Kurt Garloff """ import os, sys, getopt =66rom xen.xend import sxp import tempfile # Global options quiet =3D False verbose =3D False tmpdir =3D '/var/lib/xen/tmp' # List of partitions # It's created by setting up the all the devices from the xen disk # config; every entry creates on Wholedisk object, which does necessary # preparatory steps such as losetup and kpartx -a; then a Partition # object is setup for every partition (which may be one or several per # Wholedisk); it references the Wholedisk if needed; python reference # counting will take care of the cleanup. partitions =3D [] # Helper functions def traildigits(strg): "Return the trailing digits, used to split the partition number off" idx =3D len(strg)-1 while strg[idx].isdigit(): if len =3D=3D 0: return strg idx -=3D 1 return strg[idx+1:]=09 def isWholedisk(domUname): "Determines whether dev is a wholedisk dev" return not domUname[-1:].isdigit() def freeLoopDev(): "Finds a free loop device; racy!" loops =3D [] fd =3D os.popen("losetup -a") for ln in fd.readlines(): loops.append(ln.split(':')[0]) for nr in range(0,256): if "/dev/loop%i" % nr not in loops: return "/dev/loop%i" % nr return None def findPart(dev): "Find device dev in list of partitions" if len(dev) > 5 and dev[:5] =3D=3D "/dev/": dev =3D dev[5:] for part in partitions: if dev =3D=3D part.domname: return part return None class Wholedisk: "Class representing a whole disk that has partitions" def __init__(self, domname, physdev, loopfile =3D None): "c'tor: set up" self.domname =3D domname self.physdev =3D physdev self.loopfile =3D loopfile self.mapped =3D 0 self.pcount =3D self.scanpartitions() def loopsetup(self): "Setup the loop mapping" if self.loopfile and not self.physdev: ldev =3D freeLoopDev() if not ldev: raise RuntimeError("domUloader: No free loop device found") if verbose: print "domUloader: losetup %s %s" % (ldev, self.loopfile) fd =3D os.popen("losetup %s %s" % (ldev, self.loopfile)) if fd.close(): raise RuntimeError("domUloader: Failure setting up loop dev") self.physdev =3D ldev def loopclean(self): "Delete the loop mapping" if self.loopfile and self.physdev: if verbose: print "domUloader: losetup -d %s" % self.physdev fd =3D os.popen("losetup -d %s" % self.physdev) self.physdev =3D None return fd.close() =09 def scanpartitions(self): """Scan device for partitions (kpartx -l) and set up data structures, Returns number of partitions found.""" self.loopsetup() if not self.physdev: raise RuntimeError("domUloader: No physical device? %s" % self.__repr__(= )) # TODO: We could use fdisk -l instead and look at the type of # partitions; this way we could also detect LVM and support it. fd =3D os.popen("kpartx -l %s" % self.physdev) pcount =3D 0 for line in fd.readlines(): line =3D line.strip() (pname, params) =3D line.split(':') pno =3D int(traildigits(pname.strip())) #if pname.rfind('/') !=3D -1: # pname =3D pname[pname.rfind('/')+1:] #pname =3D self.physdev[:self.physdev.rfind('/')] + '/' + pname pname =3D "/dev/mapper/" + pname partitions.append(Partition(self, self.domname + '%i' % pno, pname)) pcount +=3D 1 fd.close() if not pcount: if self.loopfile: ref =3D self else: ref =3D None partitions.append(Partition(ref, self.domname, self.physdev)) self.loopclean() return pcount def activatepartitions(self): "Set up loop mapping and device-mapper mappings" if not self.mapped: self.loopsetup() if self.pcount: if verbose: print "domUloader: kpartx -a %s" % self.physdev fd =3D os.popen("kpartx -a %s" % self.physdev) fd.close() self.mapped +=3D 1 =09 def deactivatepartitions(self): "Remove device-mapper mappings and loop mapping" if not self.mapped: return self.mapped -=3D 1 if not self.mapped: if self.pcount: if verbose: print "domUloader: kpartx -d %s" % self.physdev fd =3D os.popen("kpartx -d %s" % self.physdev) fd.close() self.loopclean() def __del__(self): "d'tor: clean up" self.deactivatepartitions() self.loopclean() def __repr__(self): "string representation for debugging" strg =3D "[" + self.domname + "," + self.physdev + ","=20 if self.loopfile: strg +=3D self.loopfile strg +=3D "," + str(self.pcount) + ",mapped %ix]" % self.mapped return strg class Partition: """Class representing a domU filesystem (partition) that can be mounted in dom0""" def __init__(self, whole =3D None, domname =3D None,=20 physdev =3D None): "c'tor: setup" self.wholedisk =3D whole self.domname =3D domname self.physdev =3D physdev self.mountpoint =3D None def __del__(self): "d'tor: cleanup" if self.mountpoint: self.umount() # Not needed: Refcounting will take care of it. #if self.wholedisk: # self.wholedisk.deactivatepartitions() def __repr__(self): "string representation for debugging" strg =3D "[" + self.domname + "," + self.physdev + "," if self.mountpoint: strg +=3D "mounted on " + self.mountpoint + "," else: strg +=3D "not mounted," if self.wholedisk: return strg + self.wholedisk.__repr__() + "]" else: return strg + "]" def mount(self, fstype =3D None, options =3D "ro"): "mount filesystem, sets self.mountpoint" if self.mountpoint: return if self.wholedisk: self.wholedisk.activatepartitions() mtpt =3D tempfile.mkdtemp(prefix =3D "%s." % self.domname, dir =3D tmpdir) mopts =3D "" if fstype: mopts +=3D " -t %s" % fstype mopts +=3D " -o %s" % options if verbose: print "domUloader: mount %s %s %s" % (mopts, self.physdev, mtpt) fd =3D os.popen("mount %s %s %s" % (mopts, self.physdev, mtpt)) err =3D fd.close() if err: raise RuntimeError("domUloader: Error %i from mount %s %s on %s" % \ (err, mopts, self.physdev, mtpt)) self.mountpoint =3D mtpt =09 def umount(self): "umount filesystem at self.mountpoint" if not self.mountpoint: return if verbose: print "domUloader: umount %s" % self.mountpoint fd =3D os.popen("umount %s" % self.mountpoint) err =3D fd.close() os.rmdir(self.mountpoint) if err: raise RuntimeError("Error %i from umount %s" % \ (err, self.mountpoint)) self.mountpoint =3D None if self.wholedisk: self.wholedisk.deactivatepartitions() def setupOneDisk(cfg): """Sets up one exported disk (incl. partitions if existing) @param cfg: 4-tuple (uname, dev, mode, backend)"""=20 from xen.util.blkif import blkdev_uname_to_file (type, dev) =3D cfg[0].split(':') (loopfile, physdev) =3D (None, None) if type =3D=3D "file": loopfile =3D dev elif type =3D=3D "phy": physdev =3D blkdev_uname_to_file(cfg[0]) wdisk =3D Wholedisk(cfg[1], physdev, loopfile) def setupDisks(vbds): """Create a list of all disks from the disk config: @param vbds: The disk config as list of 4-tuples=20 (uname, dev, mode, backend)""" disks =3D eval(eval(vbds)) for disk in disks: setupOneDisk(disk) if verbose: print "Partitions: " + str(partitions) class Fstab: "Class representing an fstab" class FstabEntry: "Class representing one fstab line" def __init__(self, line): "c'tor: parses one line" spline =3D line.split() self.dev, self.mtpt, self.fstype, self.opts =3D \ spline[0], spline[1], spline[2], spline[3] if len(self.mtpt) > 1: self.mtpt =3D self.mtpt.rstrip('/') =09 def __init__(self, filename): "c'tor: parses fstab" self.entries =3D [] fd =3D open(filename) for line in fd.readlines(): line =3D line.strip() if len(line) =3D=3D 0 or line[0] =3D=3D '#': continue self.entries.append(Fstab.FstabEntry(line)) def find(self, fname): "Looks for matching filesystem in fstab" matchlen =3D 0 match =3D None fnmlst =3D fname.split('/') for fs in self.entries: entlst =3D fs.mtpt.split('/') # '/' needs special treatment :-( if entlst =3D=3D ['','']: entlst =3D [''] entln =3D len(entlst) if len(fnmlst) >=3D entln and fnmlst[:entln] =3D=3D entlst \ and entln > matchlen: match =3D fs matchlen =3D entln if not match: return (None, None) return (match.dev, match.mtpt) def fsFromFstab(kernel, initrd, root): """Investigate rootFS fstab, check for filesystem that contains the kernel and return it; also returns adapted kernel and initrd path. """ part =3D findPart(root) if not part: raise RuntimeError("domUloader: Root fs %s not exported?" % root) part.mount() if not os.access(part.mountpoint + '/etc/fstab', os.R_OK): part.umount() raise RuntimeError("domUloader: /etc/fstab not found on %s" % root) fstab =3D Fstab(part.mountpoint + '/etc/fstab') (dev, fs) =3D fstab.find(kernel) if not fs: raise RuntimeError("domUloader: no matching filesystem for image %s found= in fstab" % kernel) #return (None, kernel, initrd) if fs =3D=3D '/': ln =3D 0 # this avoids the stupid /dev/root problem dev =3D root else: ln =3D len(fs) kernel =3D kernel[ln:] if initrd: initrd =3D initrd[ln:] if verbose: print "fsFromFstab: %s %s -- %s,%s" % (dev, fs, kernel, initrd) return (kernel, initrd, dev)=20 def parseEntry(entry): "disects bootentry and returns kernel, initrd, filesys" fs =3D None initrd =3D None fsspl =3D entry.split(':') if len(fsspl) > 1: fs =3D fsspl[0] entry =3D fsspl[1] enspl =3D entry.split(',') # Prepend '/' if missing kernel =3D enspl[0] if kernel[0] !=3D '/': kernel =3D '/' + kernel if len(enspl) > 1: initrd =3D enspl[1] if initrd[0] !=3D '/': initrd =3D '/' + initrd return kernel, initrd, fs def copyFile(src, dst): "Wrapper for shutil.filecopy" import shutil if verbose: print "domUloader: cp %s %s" % (src, dst) stat =3D os.stat(src) if stat.st_size > 16*1024*1024: raise RuntimeError("Too large file %s (%s larger than 16MB)" \ % (src, stat.st_size))=20 try: shutil.copyfile(src, dst) except: os.unlink(dst) raise() def copyKernelAndInitrd(fs, kernel, initrd): """Finds fs in list of partitions, mounts the partition, copies kernel [and initrd] off to dom0 files, umounts the parition again, and returns sxpr pointing to these copies.""" import shutil part =3D findPart(fs) if not part: raise RuntimeError("domUloader: Filesystem %s not exported\n" % fs) part.mount() try: (fd, knm) =3D tempfile.mkstemp(prefix =3D "vmlinuz.", dir =3D tmpdir) os.close(fd) copyFile(part.mountpoint + kernel, knm) except:=20 os.unlink(knm) raise if not quiet: print "Copy kernel %s from %s to %s for booting" % \ (kernel, fs, knm) sxpr =3D "linux (kernel %s)" % knm if (initrd): try: (fd, inm) =3D tempfile.mkstemp(prefix =3D "initrd.", dir =3D tmpdir) os.close(fd) copyFile(part.mountpoint + initrd, inm) except: os.unlink(knm) os.unlink(inm) raise sxpr +=3D "(ramdisk %s)" % inm part.umount() return sxpr def main(argv): "Main routine: Parses options etc." global quiet, verbose, tmpdir def usage(): "Help output (usage info)" global verbose, quiet print >> sys.stderr, "domUloader usage: domUloader --disks=3Ddisklist [--= root=3DrootFS]\n" \ + " --entry=3Dkernel[,initrd] [--output=3Dfd] [--quiet] [--verbose] [--h= elp]\n" print >> sys.stderr, __doc__ #print "domUloader " + str(argv) try: (optlist, args) =3D getopt.gnu_getopt(argv, 'qvh', \ ('disks=3D', 'root=3D', 'entry=3D', 'output=3D',=20 'tmpdir=3D', 'help', 'quiet', 'verbose')) except: usage() sys.exit(1) entry =3D None output =3D None root =3D None disks =3D None for (opt, oarg) in optlist: if opt in ('-h', '--help'): usage() sys.exit(0) elif opt in ('-q', '--quiet'): quiet =3D True elif opt in ('-v', '--verbose'): verbose =3D True elif opt =3D=3D '--root': root =3D oarg elif opt =3D=3D '--output': output =3D oarg elif opt =3D=3D '--disks': disks =3D oarg elif opt =3D=3D '--entry': entry =3D oarg elif opt =3D=3D '--tmpdir': tmpdir =3D oarg if not entry or not disks: usage() sys.exit(1) =09 if output is None or output =3D=3D "-": fd =3D sys.stdout.fileno() else: fd =3D os.open(output, os.O_WRONLY) =09 if not os.access(tmpdir, os.X_OK): os.mkdir(tmpdir) os.chmod(tmpdir, 0750) # We assume kernel and initrd are on the same FS, # so only one fs kernel, initrd, fs =3D parseEntry(entry) setupDisks(disks) if not fs: if not root: usage() raise RuntimeError("domUloader: No root=3D to parse fstab and no disk in= bootentry") sys.exit(1) kernel, initrd, fs =3D fsFromFstab(kernel, initrd, root) =09 sxpr =3D copyKernelAndInitrd(fs, kernel, initrd) sys.stdout.flush() os.write(fd, sxpr) # Call main if called (and not imported) if __name__ =3D=3D "__main__": main(sys.argv) --FUaywKC54iCcLzqT-- --PMULwz+zIGJzpDN9 Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2 (GNU/Linux) iD8DBQFD0NrZxmLh6hyYd04RAjSxAJwIAuIAV5ua211JE93vfSxwGgOgnQCgp4h+ R8ZeMbOKpYquuFEpBX9PDDo= =uROg -----END PGP SIGNATURE----- --PMULwz+zIGJzpDN9-- --===============1152378973== Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Content-Disposition: inline _______________________________________________ Xen-devel mailing list Xen-devel@lists.xensource.com http://lists.xensource.com/xen-devel --===============1152378973==--