Skip to contentSkip to conversation

pygrub support for Grub2 grub.cfg syntax

PATCH In review [email protected] 3 participants 12 messages Nov 22, 2009 – Nov 23, 2009

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 pygrub support for Grub2 grub.cfg syntax

The following patches implement very basic support for Grub 2's grub.cfg syntax. It's pretty minimal but sufficient for booting Debian Squeeze which now uses grub2 by default.

There are also some more generic fixes.

Since grub2 is starting to be used by distros this might be worth porting to the 3.4 branch once it has baked for a while.

#1 lore raw

PATCH 1/1 pygrub: if default entry is "saved" then use first entry

# HG changeset patch
# User Ian Campbell <[email protected]>
# Date 1258917181 0
# Node ID b50b4a265d3879f4c334361a433f4d23d5a65314 # Parent 32354b647470b843c18bd8261ab0b5f803a66289
pygrub: if default entry is "saved" then use first entry.

pygrub doesn't support the "savedefault" command and will error out if menu.lst uses the "default saved" directive. We might as well start on the first entry in this case instead of failing.

tools/pygrub/src/GrubConf.py +1 -1
diff -r 32354b647470 -r b50b4a265d38 tools/pygrub/src/GrubConf.py
@@ -258,7 +258,7 @@
         return self._default
     def _set_default(self, val):
         if val == "saved":
-            self._default = -1
+            self._default = 0
         else:
             self._default = int(val)
#2 lore raw

PATCH 1/1 pygrub: expands tabs before displaying menus

In reply to [email protected]

# HG changeset patch
# User Ian Campbell <[email protected]>
# Date 1258917181 0
# Node ID 13311ab2b104f238a88b3842a05d0053eb8569dc # Parent b50b4a265d3879f4c334361a433f4d23d5a65314
pygrub: expands tabs before displaying menus.

Otherwise the highlighting and line length trimming does not work as expected and the display appears corrupted.

tools/pygrub/src/pygrub +2 -2
diff -r b50b4a265d38 -r 13311ab2b104 tools/pygrub/src/pygrub
@@ -239,7 +239,7 @@
                 break
             if y == self.selected_image:
                 self.entry_win.attron(curses.A_REVERSE)
-            self.entry_win.addstr(y + 1 - self.start_image, 2, i.title.ljust(70))
+            self.entry_win.addstr(y + 1 - self.start_image, 2, i.title.expandtabs().ljust(70))
             if y == self.selected_image:
                 self.entry_win.attroff(curses.A_REVERSE)
         self.entry_win.noutrefresh()
@@ -271,7 +271,7 @@
                     self.entry_win.attron(curses.A_REVERSE)
 
                 # trim the line
-                l = img.lines[idx].ljust(70)
+                l = img.lines[idx].expandtabs().ljust(70)
                 if len(l) > 70:
                     l = l[:69] + ">"
#3 lore raw

PATCH 1/1 pygrub: factor generic Grub functionality into GrubConf base classes

In reply to [email protected]

# HG changeset patch
# User Ian Campbell <[email protected]>
# Date 1258917181 0
# Node ID d641f06a4889748dc7efec62398b5d333ad0df87
# Parent 13311ab2b104f238a88b3842a05d0053eb8569dc
pygrub: factor generic Grub functionality into GrubConf base classes and inherit from these classes to implement Grub-legacy functionality.

Use a tuple of (parser-object,configuration-file) in pygrub to allow for multiple parsers.

Makes way for grub2 support.

tools/pygrub/src/GrubConf.py +77 -66
diff -r 13311ab2b104 -r d641f06a4889 tools/pygrub/src/GrubConf.py
@@ -78,7 +78,7 @@
         self._part = int(val)
     part = property(get_part, set_part)
 
-class GrubImage(object):
+class _GrubImage(object):
     def __init__(self, lines):
         self.reset(lines)
 
@@ -89,30 +89,14 @@
                 "  args: %s\n"
                 "  initrd: %s\n" %(self.title, self.root, self.kernel,
                                    self.args, self.initrd))
+    def _parse(self, lines):
+        map(self.set_from_line, lines)
 
     def reset(self, lines):
         self._root = self._initrd = self._kernel = self._args = None
         self.title = ""
         self.lines = []
-        map(self.set_from_line, lines)
-
-    def set_from_line(self, line, replace = None):
-        (com, arg) = grub_exact_split(line, 2)
-
-        if self.commands.has_key(com):
-            if self.commands[com] is not None:
-                setattr(self, self.commands[com], arg.strip())
-            else:
-                logging.info("Ignored image directive %s" %(com,))
-        else:
-            logging.warning("Unknown image directive %s" %(com,))
-
-        # now put the line in the list of lines
-        if replace is None:
-            self.lines.append(line)
-        else:
-            self.lines.pop(replace)
-            self.lines.insert(replace, line)
+        self._parse(lines)
 
     def set_root(self, val):
         self._root = GrubDiskPart(val)
@@ -141,6 +125,28 @@
         return self._initrd
     initrd = property(get_initrd, set_initrd)
 
+class GrubImage(_GrubImage):
+    def __init__(self, lines):
+        _GrubImage.__init__(self, lines)
+    
+    def set_from_line(self, line, replace = None):
+        (com, arg) = grub_exact_split(line, 2)
+
+        if self.commands.has_key(com):
+            if self.commands[com] is not None:
+                setattr(self, self.commands[com], arg.strip())
+            else:
+                logging.info("Ignored image directive %s" %(com,))
+        else:
+            logging.warning("Unknown image directive %s" %(com,))
+
+        # now put the line in the list of lines
+        if replace is None:
+            self.lines.append(line)
+        else:
+            self.lines.pop(replace)
+            self.lines.insert(replace, line)
+
     # set up command handlers
     commands = { "title": "title",
                  "root": "root",
@@ -149,9 +155,8 @@
                  "initrd": "initrd",
                  "chainloader": None,
                  "module": None}
-        
 
-class GrubConfigFile(object):
+class _GrubConfigFile(object):
     def __init__(self, fn = None):
         self.filename = fn
         self.images = []
@@ -164,50 +169,7 @@
             self.parse()
 
     def parse(self, buf = None):
-        if buf is None:
-            if self.filename is None:
-                raise ValueError, "No config file defined to parse!"
-
-            f = open(self.filename, 'r')
-            lines = f.readlines()
-            f.close()
-        else:
-            lines = buf.split("\n")
-
-        img = []
-        for l in lines:
-            l = l.strip()
-            # skip blank lines
-            if len(l) == 0:
-                continue
-            # skip comments
-            if l.startswith('#'):
-                continue
-            # new image
-            if l.startswith("title"):
-                if len(img) > 0:
-                    self.add_image(GrubImage(img))
-                img = [l]
-                continue
-                
-            if len(img) > 0:
-                img.append(l)
-                continue
-
-            (com, arg) = grub_exact_split(l, 2)
-            if self.commands.has_key(com):
-                if self.commands[com] is not None:
-                    setattr(self, self.commands[com], arg.strip())
-                else:
-                    logging.info("Ignored directive %s" %(com,))
-            else:
-                logging.warning("Unknown directive %s" %(com,))
-                
-        if len(img) > 0:
-            self.add_image(GrubImage(img))
-
-        if self.hasPassword():
-            self.setPasswordAccess(False)
+        raise RuntimeError, "unimplemented parse function"   
 
     def hasPasswordAccess(self):
         return self.passwordAccess
@@ -285,7 +247,56 @@
         commands[c] = None
     del c
 
+class GrubConfigFile(_GrubConfigFile):
+    def __init__(self, fn = None):
+        _GrubConfigFile.__init__(self,fn)
+        
+    def parse(self, buf = None):
+        if buf is None:
+            if self.filename is None:
+                raise ValueError, "No config file defined to parse!"
 
+            f = open(self.filename, 'r')
+            lines = f.readlines()
+            f.close()
+        else:
+            lines = buf.split("\n")
+
+        img = []
+        for l in lines:
+            l = l.strip()
+            # skip blank lines
+            if len(l) == 0:
+                continue
+            # skip comments
+            if l.startswith('#'):
+                continue
+            # new image
+            if l.startswith("title"):
+                if len(img) > 0:
+                    self.add_image(GrubImage(img))
+                img = [l]
+                continue
+                
+            if len(img) > 0:
+                img.append(l)
+                continue
+
+            (com, arg) = grub_exact_split(l, 2)
+            if self.commands.has_key(com):
+                if self.commands[com] is not None:
+                    setattr(self, self.commands[com], arg.strip())
+                else:
+                    logging.info("Ignored directive %s" %(com,))
+            else:
+                logging.warning("Unknown directive %s" %(com,))
+                
+        if len(img) > 0:
+            self.add_image(GrubImage(img))
+
+        if self.hasPassword():
+            self.setPasswordAccess(False)
+    
 if __name__ == "__main__":
     if sys.argv < 2:
         raise RuntimeError, "Need a grub.conf to read"
tools/pygrub/src/pygrub +13 -11
diff -r 13311ab2b104 -r d641f06a4889 tools/pygrub/src/pygrub
@@ -371,17 +371,17 @@
             raise RuntimeError, "Unable to access %s" %(fn,)
 
         if platform.machine() == 'ia64':
-            self.cf = grub.LiloConf.LiloConfigFile()
-            # common distributions
-            file_list = ("/efi/debian/elilo.conf", "/efi/gentoo/elilo.conf", 
-                         "/efi/redflag/elilo.conf", "/efi/redhat/elilo.conf", 
-                         "/efi/SuSE/elilo.conf",)
-            # fallbacks
-            file_list += ("/efi/boot/elilo.conf", "/elilo.conf",)
+            cfg_list = map(lambda x: (x,grub.LiloConf.LiloConfigFile), 
+                           # common distributions
+                           ["/efi/debian/elilo.conf", "/efi/gentoo/elilo.conf", 
+                            "/efi/redflag/elilo.conf", "/efi/redhat/elilo.conf", 
+                            "/efi/SuSE/elilo.conf",] + 
+                           # fallbacks
+                           ["/efi/boot/elilo.conf", "/elilo.conf",])
         else:
-            self.cf = grub.GrubConf.GrubConfigFile()
-            file_list = ("/boot/grub/menu.lst", "/boot/grub/grub.conf",
-                         "/grub/menu.lst", "/grub/grub.conf")
+            cfg_list = map(lambda x: (x,grub.GrubConf.GrubConfigFile),
+                           ["/boot/grub/menu.lst", "/boot/grub/grub.conf",
+                            "/grub/menu.lst", "/grub/grub.conf"])
 
         if not fs:
             # set the config file and parse it
@@ -389,8 +389,10 @@
             self.cf.parse()
             return
 
-        for f in file_list:
+        for f,parser in cfg_list:
             if fs.file_exists(f):
+                print >>sys.stderr, "Using %s to parse %s" % (parser,f)
+                self.cf = parser()
                 self.cf.filename = f
                 break
         if self.cf.filename is None:
#4 lore raw

Re: [PATCH 3 of 5] pygrub: factor generic Grub functionality into GrubConf base classes

Quoted 7 lines · On 22/11/2009 19:15, "[email protected]" <[email protected]> wrote:

pygrub: factor generic Grub functionality into GrubConf base classes and inherit from these classes to implement Grub-legacy functionality.

Use a tuple of (parser-object,configuration-file) in pygrub to allow for multiple parsers.

Makes way for grub2 support.

This patch didn't apply for me. It may be due to mangling at my end or yours because of sending the patch inline. Try resending it as an attachment, along with patches 4/5 and 5/5 (I have already successfully applied 1/5 and 2/5).

Thanks,
Keir

#5 lore raw

PATCH 1/1 pygrub support for Grub2 grub.cfg syntax

The following patches implement very basic support for Grub 2's grub.cfg syntax. It's pretty minimal but sufficient for booting Debian Squeeze which now uses grub2 by default.

There are also some more generic fixes.

Since grub2 is starting to be used by distros this might be worth porting to the 3.4 branch once it has baked for a while.

#6 lore raw

PATCH 1/1 pygrub: factor generic Grub functionality into GrubConf base classes

and inherit from these classes to implement Grub-legacy functionality.

Use a tuple of (parser-object,configuration-file) in pygrub to allow for multiple parsers.

Makes way for grub2 support.

# HG changeset patch
# User Ian Campbell <[email protected]>
# Date 1258917181 0
# Node ID d641f06a4889748dc7efec62398b5d333ad0df87
# Parent 13311ab2b104f238a88b3842a05d0053eb8569dc
pygrub: factor generic Grub functionality into GrubConf base classes and inherit from these classes to implement Grub-legacy functionality.

Use a tuple of (parser-object,configuration-file) in pygrub to allow for multiple parsers.

Makes way for grub2 support.

tools/pygrub/src/GrubConf.py +77 -66
diff -r 13311ab2b104 -r d641f06a4889 tools/pygrub/src/GrubConf.py
@@ -78,7 +78,7 @@
         self._part = int(val)
     part = property(get_part, set_part)
 
-class GrubImage(object):
+class _GrubImage(object):
     def __init__(self, lines):
         self.reset(lines)
 
@@ -89,30 +89,14 @@
                 "  args: %s\n"
                 "  initrd: %s\n" %(self.title, self.root, self.kernel,
                                    self.args, self.initrd))
+    def _parse(self, lines):
+        map(self.set_from_line, lines)
 
     def reset(self, lines):
         self._root = self._initrd = self._kernel = self._args = None
         self.title = ""
         self.lines = []
-        map(self.set_from_line, lines)
-
-    def set_from_line(self, line, replace = None):
-        (com, arg) = grub_exact_split(line, 2)
-
-        if self.commands.has_key(com):
-            if self.commands[com] is not None:
-                setattr(self, self.commands[com], arg.strip())
-            else:
-                logging.info("Ignored image directive %s" %(com,))
-        else:
-            logging.warning("Unknown image directive %s" %(com,))
-
-        # now put the line in the list of lines
-        if replace is None:
-            self.lines.append(line)
-        else:
-            self.lines.pop(replace)
-            self.lines.insert(replace, line)
+        self._parse(lines)
 
     def set_root(self, val):
         self._root = GrubDiskPart(val)
@@ -141,6 +125,28 @@
         return self._initrd
     initrd = property(get_initrd, set_initrd)
 
+class GrubImage(_GrubImage):
+    def __init__(self, lines):
+        _GrubImage.__init__(self, lines)
+    
+    def set_from_line(self, line, replace = None):
+        (com, arg) = grub_exact_split(line, 2)
+
+        if self.commands.has_key(com):
+            if self.commands[com] is not None:
+                setattr(self, self.commands[com], arg.strip())
+            else:
+                logging.info("Ignored image directive %s" %(com,))
+        else:
+            logging.warning("Unknown image directive %s" %(com,))
+
+        # now put the line in the list of lines
+        if replace is None:
+            self.lines.append(line)
+        else:
+            self.lines.pop(replace)
+            self.lines.insert(replace, line)
+
     # set up command handlers
     commands = { "title": "title",
                  "root": "root",
@@ -149,9 +155,8 @@
                  "initrd": "initrd",
                  "chainloader": None,
                  "module": None}
-        
 
-class GrubConfigFile(object):
+class _GrubConfigFile(object):
     def __init__(self, fn = None):
         self.filename = fn
         self.images = []
@@ -164,50 +169,7 @@
             self.parse()
 
     def parse(self, buf = None):
-        if buf is None:
-            if self.filename is None:
-                raise ValueError, "No config file defined to parse!"
-
-            f = open(self.filename, 'r')
-            lines = f.readlines()
-            f.close()
-        else:
-            lines = buf.split("\n")
-
-        img = []
-        for l in lines:
-            l = l.strip()
-            # skip blank lines
-            if len(l) == 0:
-                continue
-            # skip comments
-            if l.startswith('#'):
-                continue
-            # new image
-            if l.startswith("title"):
-                if len(img) > 0:
-                    self.add_image(GrubImage(img))
-                img = [l]
-                continue
-                
-            if len(img) > 0:
-                img.append(l)
-                continue
-
-            (com, arg) = grub_exact_split(l, 2)
-            if self.commands.has_key(com):
-                if self.commands[com] is not None:
-                    setattr(self, self.commands[com], arg.strip())
-                else:
-                    logging.info("Ignored directive %s" %(com,))
-            else:
-                logging.warning("Unknown directive %s" %(com,))
-                
-        if len(img) > 0:
-            self.add_image(GrubImage(img))
-
-        if self.hasPassword():
-            self.setPasswordAccess(False)
+        raise RuntimeError, "unimplemented parse function"   
 
     def hasPasswordAccess(self):
         return self.passwordAccess
@@ -285,7 +247,56 @@
         commands[c] = None
     del c
 
+class GrubConfigFile(_GrubConfigFile):
+    def __init__(self, fn = None):
+        _GrubConfigFile.__init__(self,fn)
+        
+    def parse(self, buf = None):
+        if buf is None:
+            if self.filename is None:
+                raise ValueError, "No config file defined to parse!"
 
+            f = open(self.filename, 'r')
+            lines = f.readlines()
+            f.close()
+        else:
+            lines = buf.split("\n")
+
+        img = []
+        for l in lines:
+            l = l.strip()
+            # skip blank lines
+            if len(l) == 0:
+                continue
+            # skip comments
+            if l.startswith('#'):
+                continue
+            # new image
+            if l.startswith("title"):
+                if len(img) > 0:
+                    self.add_image(GrubImage(img))
+                img = [l]
+                continue
+                
+            if len(img) > 0:
+                img.append(l)
+                continue
+
+            (com, arg) = grub_exact_split(l, 2)
+            if self.commands.has_key(com):
+                if self.commands[com] is not None:
+                    setattr(self, self.commands[com], arg.strip())
+                else:
+                    logging.info("Ignored directive %s" %(com,))
+            else:
+                logging.warning("Unknown directive %s" %(com,))
+                
+        if len(img) > 0:
+            self.add_image(GrubImage(img))
+
+        if self.hasPassword():
+            self.setPasswordAccess(False)
+    
 if __name__ == "__main__":
     if sys.argv < 2:
         raise RuntimeError, "Need a grub.conf to read"
tools/pygrub/src/pygrub +13 -11
diff -r 13311ab2b104 -r d641f06a4889 tools/pygrub/src/pygrub
@@ -371,17 +371,17 @@
             raise RuntimeError, "Unable to access %s" %(fn,)
 
         if platform.machine() == 'ia64':
-            self.cf = grub.LiloConf.LiloConfigFile()
-            # common distributions
-            file_list = ("/efi/debian/elilo.conf", "/efi/gentoo/elilo.conf", 
-                         "/efi/redflag/elilo.conf", "/efi/redhat/elilo.conf", 
-                         "/efi/SuSE/elilo.conf",)
-            # fallbacks
-            file_list += ("/efi/boot/elilo.conf", "/elilo.conf",)
+            cfg_list = map(lambda x: (x,grub.LiloConf.LiloConfigFile), 
+                           # common distributions
+                           ["/efi/debian/elilo.conf", "/efi/gentoo/elilo.conf", 
+                            "/efi/redflag/elilo.conf", "/efi/redhat/elilo.conf", 
+                            "/efi/SuSE/elilo.conf",] + 
+                           # fallbacks
+                           ["/efi/boot/elilo.conf", "/elilo.conf",])
         else:
-            self.cf = grub.GrubConf.GrubConfigFile()
-            file_list = ("/boot/grub/menu.lst", "/boot/grub/grub.conf",
-                         "/grub/menu.lst", "/grub/grub.conf")
+            cfg_list = map(lambda x: (x,grub.GrubConf.GrubConfigFile),
+                           ["/boot/grub/menu.lst", "/boot/grub/grub.conf",
+                            "/grub/menu.lst", "/grub/grub.conf"])
 
         if not fs:
             # set the config file and parse it
@@ -389,8 +389,10 @@
             self.cf.parse()
             return
 
-        for f in file_list:
+        for f,parser in cfg_list:
             if fs.file_exists(f):
+                print >>sys.stderr, "Using %s to parse %s" % (parser,f)
+                self.cf = parser()
                 self.cf.filename = f
                 break
         if self.cf.filename is None:

_______________________________________________
Xen-devel mailing list
[email protected]
http://lists.xensource.com/xen-devel

#7 lore raw

PATCH 1/1 pygrub: track the title of an item as an independant field

In reply to [email protected]

separate to the other fields.

This makes the list of lines within a GrubImage 0 based rather than 1 based therefore adjust the user interface parts to suit.

This is in preparation for grub2 support where the syntax for the item title does not fit the existing usage.

# HG changeset patch
# User Ian Campbell <[email protected]>
# Date 1258917181 0
# Node ID 69d318d58ed3e4266bfb76f514d90b69270aed9a # Parent d641f06a4889748dc7efec62398b5d333ad0df87
pygrub: track the title of an item as an independant field separate to the other fields.

This makes the list of lines within a GrubImage 0 based rather than 1 based therefore adjust the user interface parts to suit.

This is in preparation for grub2 support where the syntax for the item title does not fit the existing usage.

tools/pygrub/src/GrubConf.py +14 -13
diff -r d641f06a4889 -r 69d318d58ed3 tools/pygrub/src/GrubConf.py
@@ -79,8 +79,9 @@
     part = property(get_part, set_part)
 
 class _GrubImage(object):
-    def __init__(self, lines):
+    def __init__(self, title, lines):
         self.reset(lines)
+        self.title = title.strip()
 
     def __repr__(self):
         return ("title: %s\n" 
@@ -94,7 +95,6 @@
 
     def reset(self, lines):
         self._root = self._initrd = self._kernel = self._args = None
-        self.title = ""
         self.lines = []
         self._parse(lines)
 
@@ -126,8 +126,8 @@
     initrd = property(get_initrd, set_initrd)
 
 class GrubImage(_GrubImage):
-    def __init__(self, lines):
-        _GrubImage.__init__(self, lines)
+    def __init__(self, title, lines):
+        _GrubImage.__init__(self, title, lines)
     
     def set_from_line(self, line, replace = None):
         (com, arg) = grub_exact_split(line, 2)
@@ -148,8 +148,7 @@
             self.lines.insert(replace, line)
 
     # set up command handlers
-    commands = { "title": "title",
-                 "root": "root",
+    commands = { "root": "root",
                  "rootnoverify": "root",
                  "kernel": "kernel",
                  "initrd": "initrd",
@@ -262,7 +261,8 @@
         else:
             lines = buf.split("\n")
 
-        img = []
+        img = None
+        title = ""
         for l in lines:
             l = l.strip()
             # skip blank lines
@@ -273,12 +273,13 @@
                 continue
             # new image
             if l.startswith("title"):
-                if len(img) > 0:
-                    self.add_image(GrubImage(img))
-                img = [l]
+                if img is not None:
+                    self.add_image(GrubImage(title, img))
+                img = []
+                title = l[6:]
                 continue
                 
-            if len(img) > 0:
+            if img is not None:
                 img.append(l)
                 continue
 
@@ -291,8 +292,8 @@
             else:
                 logging.warning("Unknown directive %s" %(com,))
                 
-        if len(img) > 0:
-            self.add_image(GrubImage(img))
+        if img:
+            self.add_image(GrubImage(title, img))
 
         if self.hasPassword():
             self.setPasswordAccess(False)
tools/pygrub/src/pygrub +5 -5
diff -r d641f06a4889 -r 69d318d58ed3 tools/pygrub/src/pygrub
@@ -259,13 +259,13 @@
             self.text_win.move(y - 1, x - 1)
             self.text_win.noutrefresh()
 
-        curline = 1
+        curline = 0
         img = copy.deepcopy(origimg)
         while 1:
             draw()
             self.entry_win.erase()
             self.entry_win.box()
-            for idx in range(1, len(img.lines)):
+            for idx in range(0, len(img.lines)):
                 # current line should be highlighted
                 if idx == curline:
                     self.entry_win.attron(curses.A_REVERSE)
@@ -275,7 +275,7 @@
                 if len(l) > 70:
                     l = l[:69] + ">"
                     
-                self.entry_win.addstr(idx, 2, l)
+                self.entry_win.addstr(idx + 1, 2, l)
                 if idx == curline:
                     self.entry_win.attroff(curses.A_REVERSE)
             self.entry_win.noutrefresh()
@@ -308,8 +308,8 @@
                     return
                 
             # bound at the top and bottom
-            if curline < 1:
-                curline = 1
+            if curline < 0:
+                curline = 0
             elif curline >= len(img.lines):
                 curline = len(img.lines) - 1
 

_______________________________________________
Xen-devel mailing list
[email protected]
http://lists.xensource.com/xen-devel

#8 lore raw

PATCH 1/1 pygrub: add basic support for parsing grub2 style grub.cfg file

In reply to [email protected]

This represents a very simplistic aproach to parsing these file. It is basically sufficient to parse the files produced by Debian Squeeze's version of update-grub. The actual grub.cfg syntax is much more expresive but not apparently documented apart from a few examples...

# HG changeset patch
# User Ian Campbell <[email protected]>
# Date 1258917181 0
# Node ID 870c7bbe259b5fb9dea78ee009d242e5ff006d9e
# Parent 69d318d58ed3e4266bfb76f514d90b69270aed9a
pygrub: add basic support for parsing grub2 style grub.cfg file

This represents a very simplistic aproach to parsing these file. It is basically sufficient to parse the files produced by Debian Squeeze's version of update-grub. The actual grub.cfg syntax is much more expresive but not apparently documented apart from a few examples...

tools/pygrub/src/GrubConf.py +120 -3
diff -r 69d318d58ed3 -r 870c7bbe259b tools/pygrub/src/GrubConf.py
@@ -14,6 +14,7 @@
 
 import os, sys
 import logging
+import re
 
 def grub_split(s, maxsplit = -1):
     eq = s.find('=')
@@ -298,9 +299,125 @@
         if self.hasPassword():
             self.setPasswordAccess(False)
     
+class Grub2Image(_GrubImage):
+    def __init__(self, title, lines):
+        _GrubImage.__init__(self, title, lines)
+
+    def set_from_line(self, line, replace = None):
+        (com, arg) = grub_exact_split(line, 2)
+
+        if com == "set":
+            (com,arg) = grub_split(arg,2)
+            com="set:" + com
+                
+        if self.commands.has_key(com):
+            if self.commands[com] is not None:
+                setattr(self, self.commands[com], arg.strip())
+            else:
+                logging.info("Ignored image directive %s" %(com,))
+        else:
+            logging.warning("Unknown image directive %s" %(com,))
+
+        # now put the line in the list of lines
+        if replace is None:
+            self.lines.append(line)
+        else:
+            self.lines.pop(replace)
+            self.lines.insert(replace, line)
+                
+    commands = {'set:root': 'root',
+                'linux': 'kernel',
+                'initrd': 'initrd',
+                'insmod': None,
+                'search': None}
+    
+class Grub2ConfigFile(_GrubConfigFile):
+    def __init__(self, fn = None):
+        _GrubConfigFile.__init__(self, fn)
+        
+    def parse(self, buf = None):
+        if buf is None:
+            if self.filename is None:
+                raise ValueError, "No config file defined to parse!"
+
+            f = open(self.filename, 'r')
+            lines = f.readlines()
+            f.close()
+        else:
+            lines = buf.split("\n")
+
+        img = None
+        title = ""
+        for l in lines:
+            l = l.strip()
+            # skip blank lines
+            if len(l) == 0:
+                continue
+            # skip comments
+            if l.startswith('#'):
+                continue
+            # new image
+            title_match = re.match('^menuentry "(.*)" {', l)
+            if title_match:
+                if img is not None:
+                    raise RuntimeError, "syntax error 1 %d %s" % (len(img),img)
+                img = []
+                title = title_match.group(1)
+                continue
+            
+            if l.startswith("}"):
+                if img is None:
+                    raise RuntimeError, "syntax error 2 %d %s" % (len(img),img)
+
+                self.add_image(Grub2Image(title, img))
+                img = None
+                continue
+
+            if img is not None:
+                img.append(l)
+                continue
+
+            (com, arg) = grub_exact_split(l, 2)
+        
+            if com == "set":
+                (com,arg) = grub_split(arg,2)
+                com="set:" + com
+                
+            if self.commands.has_key(com):
+                if self.commands[com] is not None:
+                    setattr(self, self.commands[com], arg.strip())
+                else:
+                    logging.info("Ignored directive %s" %(com,))
+            else:
+                logging.warning("Unknown directive %s" %(com,))
+            
+        if img is not None:
+            raise RuntimeError, "syntax error 3 %d %s" % (len(img),img)
+
+        if self.hasPassword():
+            self.setPasswordAccess(False)
+
+    commands = {'set:default': 'default',
+                'set:root': 'root',
+                'set:timeout': 'timeout',
+                'set:gfxmode': None,
+                'set:menu_color_normal': None,
+                'set:menu_color_highlight': None,
+                'terminal': None,
+                'insmod': None,
+                'search': None,
+                'if': None,
+                'fi': None,
+                }
+        
 if __name__ == "__main__":
-    if sys.argv < 2:
-        raise RuntimeError, "Need a grub.conf to read"
-    g = GrubConfigFile(sys.argv[1])
+    if sys.argv < 3:
+        raise RuntimeError, "Need a grub version (\"grub\" or \"grub2\") and a grub.conf or grub.cfg to read"
+    if sys.argv[1] == "grub":
+        g = GrubConfigFile(sys.argv[2])
+    elif sys.argv[1] == "grub2":
+        g = Grub2ConfigFile(sys.argv[2])
+    else:
+        raise RuntimeError, "Unknown config type %s" % sys.argv[1]
     for i in g.images:
         print i #, i.title, i.root, i.kernel, i.args, i.initrd
tools/pygrub/src/pygrub +3 -1
diff -r 69d318d58ed3 -r 870c7bbe259b tools/pygrub/src/pygrub
@@ -381,7 +381,9 @@
         else:
             cfg_list = map(lambda x: (x,grub.GrubConf.GrubConfigFile),
                            ["/boot/grub/menu.lst", "/boot/grub/grub.conf",
-                            "/grub/menu.lst", "/grub/grub.conf"])
+                            "/grub/menu.lst", "/grub/grub.conf"]) + \
+                       map(lambda x: (x,grub.GrubConf.Grub2ConfigFile),
+                           ["/boot/grub/grub.cfg"])
 
         if not fs:
             # set the config file and parse it

_______________________________________________
Xen-devel mailing list
[email protected]
http://lists.xensource.com/xen-devel

#9 lore raw

PATCH 1/1 pygrub: track the title of an item as an independant field

In reply to [email protected]

# HG changeset patch
# User Ian Campbell <[email protected]>
# Date 1258917181 0
# Node ID 69d318d58ed3e4266bfb76f514d90b69270aed9a # Parent d641f06a4889748dc7efec62398b5d333ad0df87
pygrub: track the title of an item as an independant field separate to the other fields.

This makes the list of lines within a GrubImage 0 based rather than 1 based therefore adjust the user interface parts to suit.

This is in preparation for grub2 support where the syntax for the item title does not fit the existing usage.

tools/pygrub/src/GrubConf.py +14 -13
diff -r d641f06a4889 -r 69d318d58ed3 tools/pygrub/src/GrubConf.py
@@ -79,8 +79,9 @@
     part = property(get_part, set_part)
 
 class _GrubImage(object):
-    def __init__(self, lines):
+    def __init__(self, title, lines):
         self.reset(lines)
+        self.title = title.strip()
 
     def __repr__(self):
         return ("title: %s\n" 
@@ -94,7 +95,6 @@
 
     def reset(self, lines):
         self._root = self._initrd = self._kernel = self._args = None
-        self.title = ""
         self.lines = []
         self._parse(lines)
 
@@ -126,8 +126,8 @@
     initrd = property(get_initrd, set_initrd)
 
 class GrubImage(_GrubImage):
-    def __init__(self, lines):
-        _GrubImage.__init__(self, lines)
+    def __init__(self, title, lines):
+        _GrubImage.__init__(self, title, lines)
     
     def set_from_line(self, line, replace = None):
         (com, arg) = grub_exact_split(line, 2)
@@ -148,8 +148,7 @@
             self.lines.insert(replace, line)
 
     # set up command handlers
-    commands = { "title": "title",
-                 "root": "root",
+    commands = { "root": "root",
                  "rootnoverify": "root",
                  "kernel": "kernel",
                  "initrd": "initrd",
@@ -262,7 +261,8 @@
         else:
             lines = buf.split("\n")
 
-        img = []
+        img = None
+        title = ""
         for l in lines:
             l = l.strip()
             # skip blank lines
@@ -273,12 +273,13 @@
                 continue
             # new image
             if l.startswith("title"):
-                if len(img) > 0:
-                    self.add_image(GrubImage(img))
-                img = [l]
+                if img is not None:
+                    self.add_image(GrubImage(title, img))
+                img = []
+                title = l[6:]
                 continue
                 
-            if len(img) > 0:
+            if img is not None:
                 img.append(l)
                 continue
 
@@ -291,8 +292,8 @@
             else:
                 logging.warning("Unknown directive %s" %(com,))
                 
-        if len(img) > 0:
-            self.add_image(GrubImage(img))
+        if img:
+            self.add_image(GrubImage(title, img))
 
         if self.hasPassword():
             self.setPasswordAccess(False)
tools/pygrub/src/pygrub +5 -5
diff -r d641f06a4889 -r 69d318d58ed3 tools/pygrub/src/pygrub
@@ -259,13 +259,13 @@
             self.text_win.move(y - 1, x - 1)
             self.text_win.noutrefresh()
 
-        curline = 1
+        curline = 0
         img = copy.deepcopy(origimg)
         while 1:
             draw()
             self.entry_win.erase()
             self.entry_win.box()
-            for idx in range(1, len(img.lines)):
+            for idx in range(0, len(img.lines)):
                 # current line should be highlighted
                 if idx == curline:
                     self.entry_win.attron(curses.A_REVERSE)
@@ -275,7 +275,7 @@
                 if len(l) > 70:
                     l = l[:69] + ">"
                     
-                self.entry_win.addstr(idx, 2, l)
+                self.entry_win.addstr(idx + 1, 2, l)
                 if idx == curline:
                     self.entry_win.attroff(curses.A_REVERSE)
             self.entry_win.noutrefresh()
@@ -308,8 +308,8 @@
                     return
                 
             # bound at the top and bottom
-            if curline < 1:
-                curline = 1
+            if curline < 0:
+                curline = 0
             elif curline >= len(img.lines):
                 curline = len(img.lines) - 1
#10 lore raw

PATCH 1/1 pygrub: add basic support for parsing grub2 style grub.cfg file

In reply to [email protected]

# HG changeset patch
# User Ian Campbell <[email protected]>
# Date 1258917181 0
# Node ID 870c7bbe259b5fb9dea78ee009d242e5ff006d9e
# Parent 69d318d58ed3e4266bfb76f514d90b69270aed9a
pygrub: add basic support for parsing grub2 style grub.cfg file

This represents a very simplistic aproach to parsing these file. It is basically sufficient to parse the files produced by Debian Squeeze's version of update-grub. The actual grub.cfg syntax is much more expresive but not apparently documented apart from a few examples...

tools/pygrub/src/GrubConf.py +120 -3
diff -r 69d318d58ed3 -r 870c7bbe259b tools/pygrub/src/GrubConf.py
@@ -14,6 +14,7 @@
 
 import os, sys
 import logging
+import re
 
 def grub_split(s, maxsplit = -1):
     eq = s.find('=')
@@ -298,9 +299,125 @@
         if self.hasPassword():
             self.setPasswordAccess(False)
     
+class Grub2Image(_GrubImage):
+    def __init__(self, title, lines):
+        _GrubImage.__init__(self, title, lines)
+
+    def set_from_line(self, line, replace = None):
+        (com, arg) = grub_exact_split(line, 2)
+
+        if com == "set":
+            (com,arg) = grub_split(arg,2)
+            com="set:" + com
+                
+        if self.commands.has_key(com):
+            if self.commands[com] is not None:
+                setattr(self, self.commands[com], arg.strip())
+            else:
+                logging.info("Ignored image directive %s" %(com,))
+        else:
+            logging.warning("Unknown image directive %s" %(com,))
+
+        # now put the line in the list of lines
+        if replace is None:
+            self.lines.append(line)
+        else:
+            self.lines.pop(replace)
+            self.lines.insert(replace, line)
+                
+    commands = {'set:root': 'root',
+                'linux': 'kernel',
+                'initrd': 'initrd',
+                'insmod': None,
+                'search': None}
+    
+class Grub2ConfigFile(_GrubConfigFile):
+    def __init__(self, fn = None):
+        _GrubConfigFile.__init__(self, fn)
+        
+    def parse(self, buf = None):
+        if buf is None:
+            if self.filename is None:
+                raise ValueError, "No config file defined to parse!"
+
+            f = open(self.filename, 'r')
+            lines = f.readlines()
+            f.close()
+        else:
+            lines = buf.split("\n")
+
+        img = None
+        title = ""
+        for l in lines:
+            l = l.strip()
+            # skip blank lines
+            if len(l) == 0:
+                continue
+            # skip comments
+            if l.startswith('#'):
+                continue
+            # new image
+            title_match = re.match('^menuentry "(.*)" {', l)
+            if title_match:
+                if img is not None:
+                    raise RuntimeError, "syntax error 1 %d %s" % (len(img),img)
+                img = []
+                title = title_match.group(1)
+                continue
+            
+            if l.startswith("}"):
+                if img is None:
+                    raise RuntimeError, "syntax error 2 %d %s" % (len(img),img)
+
+                self.add_image(Grub2Image(title, img))
+                img = None
+                continue
+
+            if img is not None:
+                img.append(l)
+                continue
+
+            (com, arg) = grub_exact_split(l, 2)
+        
+            if com == "set":
+                (com,arg) = grub_split(arg,2)
+                com="set:" + com
+                
+            if self.commands.has_key(com):
+                if self.commands[com] is not None:
+                    setattr(self, self.commands[com], arg.strip())
+                else:
+                    logging.info("Ignored directive %s" %(com,))
+            else:
+                logging.warning("Unknown directive %s" %(com,))
+            
+        if img is not None:
+            raise RuntimeError, "syntax error 3 %d %s" % (len(img),img)
+
+        if self.hasPassword():
+            self.setPasswordAccess(False)
+
+    commands = {'set:default': 'default',
+                'set:root': 'root',
+                'set:timeout': 'timeout',
+                'set:gfxmode': None,
+                'set:menu_color_normal': None,
+                'set:menu_color_highlight': None,
+                'terminal': None,
+                'insmod': None,
+                'search': None,
+                'if': None,
+                'fi': None,
+                }
+        
 if __name__ == "__main__":
-    if sys.argv < 2:
-        raise RuntimeError, "Need a grub.conf to read"
-    g = GrubConfigFile(sys.argv[1])
+    if sys.argv < 3:
+        raise RuntimeError, "Need a grub version (\"grub\" or \"grub2\") and a grub.conf or grub.cfg to read"
+    if sys.argv[1] == "grub":
+        g = GrubConfigFile(sys.argv[2])
+    elif sys.argv[1] == "grub2":
+        g = Grub2ConfigFile(sys.argv[2])
+    else:
+        raise RuntimeError, "Unknown config type %s" % sys.argv[1]
     for i in g.images:
         print i #, i.title, i.root, i.kernel, i.args, i.initrd
tools/pygrub/src/pygrub +3 -1
diff -r 69d318d58ed3 -r 870c7bbe259b tools/pygrub/src/pygrub
@@ -381,7 +381,9 @@
         else:
             cfg_list = map(lambda x: (x,grub.GrubConf.GrubConfigFile),
                            ["/boot/grub/menu.lst", "/boot/grub/grub.conf",
-                            "/grub/menu.lst", "/grub/grub.conf"])
+                            "/grub/menu.lst", "/grub/grub.conf"]) + \
+                       map(lambda x: (x,grub.GrubConf.Grub2ConfigFile),
+                           ["/boot/grub/grub.cfg"])
 
         if not fs:
             # set the config file and parse it
#11 lore raw
In reply to [email protected]

Ubuntu 9.10 Server PV DomU at Xen 3.4.1 Dom0 (2.6.31.6 pvops) on top F12 in meantime may be loaded via "pygrub" like this :-

[root@fedora12sda koala]# cat koala.py

name="KarmicPV"

memory=2048

bootloader="/usr/bin/pygrub"

kernel="/boot/vmlinuz-2.6.31-14-server"

ramdisk="/boot/initrd.img-2.6.31-14-server"

vif=['bridge=eth0']

extra="root=/dev/xvda1"

disk=['phy:/dev/sdb11,xvda,w']

vfb=['type=vnc,vncunused=1']

# xm create koala.py
# vncviewer localhost:0

Build  Xen on F12 via xen-3.4.1-5.fc12.src.rpm  with e2fsprogs-devel allows pygrub support ext4fs boot partition Karmic's PV DomU, but cannot detect kernel,ramdisk, root. Please, back port if possible. It will provide an option to manage via "virsh"

Boris.

--- On Sun, 11/22/09, [email protected] <[email protected]> wrote:

From: [email protected] <[email protected]>
Subject: [Xen-devel] [PATCH 0 of 5] pygrub support for Grub2 grub.cfg syntax
To: [email protected]
Date: Sunday, November 22, 2009, 2:14 PM

The following patches implement very basic support for Grub 2's grub.cfg syntax. It's pretty minimal but sufficient for booting Debian Squeeze which now uses grub2 by default.

There are also some more generic fixes.

Since grub2 is starting to be used by distros this might be worth porting to the 3.4 branch once it has baked for a while.

_______________________________________________
Xen-devel mailing list
[email protected]
http://lists.xensource.com/xen-devel

_______________________________________________
Xen-devel mailing list
[email protected]
http://lists.xensource.com/xen-devel