Add the --nombr bootloader option in pykickstart
[pykickstart.git] / pykickstart / base.py
blobb2c92c1de3c73b41e0f6910c820364aa9e6aaa65
2 # Chris Lumens <clumens@redhat.com>
4 # Copyright 2006, 2007, 2008, 2012 Red Hat, Inc.
6 # This copyrighted material is made available to anyone wishing to use, modify,
7 # copy, or redistribute it subject to the terms and conditions of the GNU
8 # General Public License v.2. This program is distributed in the hope that it
9 # will be useful, but WITHOUT ANY WARRANTY expressed or implied, including the
10 # implied warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
11 # See the GNU General Public License for more details.
13 # You should have received a copy of the GNU General Public License along with
14 # this program; if not, write to the Free Software Foundation, Inc., 51
15 # Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Any Red Hat
16 # trademarks that are incorporated in the source code or documentation are not
17 # subject to the GNU General Public License and may only be used or replicated
18 # with the express permission of Red Hat, Inc.
20 """
21 Base classes for creating commands and syntax version object.
23 This module exports several important base classes:
25 BaseData - The base abstract class for all data objects. Data objects
26 are contained within a BaseHandler object.
28 BaseHandler - The base abstract class from which versioned kickstart
29 handler are derived. Subclasses of BaseHandler hold
30 BaseData and KickstartCommand objects.
32 DeprecatedCommand - An abstract subclass of KickstartCommand that should
33 be further subclassed by users of this module. When
34 a subclass is used, a warning message will be
35 printed.
37 KickstartCommand - The base abstract class for all kickstart commands.
38 Command objects are contained within a BaseHandler
39 object.
40 """
41 import gettext
42 gettext.textdomain("pykickstart")
43 _ = lambda x: gettext.ldgettext("pykickstart", x)
45 import types
46 import warnings
47 from pykickstart.errors import KickstartParseError, formatErrorMsg
48 from pykickstart.ko import KickstartObject
49 from pykickstart.parser import Packages
50 from pykickstart.version import versionToString
52 ###
53 ### COMMANDS
54 ###
55 class KickstartCommand(KickstartObject):
56 """The base class for all kickstart commands. This is an abstract class."""
57 removedKeywords = []
58 removedAttrs = []
60 def __init__(self, writePriority=0, *args, **kwargs):
61 """Create a new KickstartCommand instance. This method must be
62 provided by all subclasses, but subclasses must call
63 KickstartCommand.__init__ first. Instance attributes:
65 currentCmd -- The name of the command in the input file that
66 caused this handler to be run.
67 currentLine -- The current unprocessed line from the input file
68 that caused this handler to be run.
69 handler -- A reference to the BaseHandler subclass this
70 command is contained withing. This is needed to
71 allow referencing of Data objects.
72 lineno -- The current line number in the input file.
73 seen -- If this command was ever used in the kickstart file,
74 this attribute will be set to True. This allows
75 for differentiating commands that were omitted
76 from those that default to unset.
77 writePriority -- An integer specifying when this command should be
78 printed when iterating over all commands' __str__
79 methods. The higher the number, the later this
80 command will be written. All commands with the
81 same priority will be written alphabetically.
82 """
84 # We don't want people using this class by itself.
85 if self.__class__ is KickstartCommand:
86 raise TypeError("KickstartCommand is an abstract class.")
88 KickstartObject.__init__(self, *args, **kwargs)
90 self.writePriority = writePriority
92 # These will be set by the dispatcher.
93 self.currentCmd = ""
94 self.currentLine = ""
95 self.handler = None
96 self.lineno = 0
97 self.seen = False
99 # If a subclass provides a removedKeywords list, remove all the
100 # members from the kwargs list before we start processing it. This
101 # ensures that subclasses don't continue to recognize arguments that
102 # were removed.
103 for arg in filter(kwargs.has_key, self.removedKeywords):
104 kwargs.pop(arg)
106 def __call__(self, *args, **kwargs):
107 """Set multiple attributes on a subclass of KickstartCommand at once
108 via keyword arguments. Valid attributes are anything specified in
109 a subclass, but unknown attributes will be ignored.
111 self.seen = True
113 for (key, val) in list(kwargs.items()):
114 # Ignore setting attributes that were removed in a subclass, as
115 # if they were unknown attributes.
116 if key in self.removedAttrs:
117 continue
119 if hasattr(self, key):
120 setattr(self, key, val)
122 def __str__(self):
123 """Return a string formatted for output to a kickstart file. This
124 method must be provided by all subclasses.
126 return KickstartObject.__str__(self)
128 # pylint: disable=unused-argument
129 def parse(self, args):
130 """Parse the list of args and set data on the KickstartCommand object.
131 This method must be provided by all subclasses.
133 raise TypeError("parse() not implemented for KickstartCommand")
135 def dataList(self):
136 """For commands that can occur multiple times in a single kickstart
137 file (like network, part, etc.), return the list that we should
138 append more data objects to.
140 return None
142 def deleteRemovedAttrs(self):
143 """Remove all attributes from self that are given in the removedAttrs
144 list. This method should be called from __init__ in a subclass,
145 but only after the superclass's __init__ method has been called.
147 for attr in [k for k in self.removedAttrs if hasattr(self, k)]:
148 delattr(self, attr)
150 # Set the contents of the opts object (an instance of optparse.Values
151 # returned by parse_args) as attributes on the KickstartCommand object.
152 # It's useful to call this from KickstartCommand subclasses after parsing
153 # the arguments.
154 def _setToSelf(self, optParser, opts):
155 self._setToObj(optParser, opts, self)
157 # Sets the contents of the opts object (an instance of optparse.Values
158 # returned by parse_args) as attributes on the provided object obj. It's
159 # useful to call this from KickstartCommand subclasses that handle lists
160 # of objects (like partitions, network devices, etc.) and need to populate
161 # a Data object.
162 def _setToObj(self, optParser, opts, obj):
163 for key in [k for k in list(optParser.keys()) if getattr(opts, k) != None]:
164 setattr(obj, key, getattr(opts, key))
166 class DeprecatedCommand(KickstartCommand):
167 """Specify that a command is deprecated and no longer has any function.
168 Any command that is deprecated should be subclassed from this class,
169 only specifying an __init__ method that calls the superclass's __init__.
170 This is an abstract class.
172 def __init__(self, writePriority=None, *args, **kwargs):
173 # We don't want people using this class by itself.
174 if self.__class__ is DeprecatedCommand:
175 raise TypeError("DeprecatedCommand is an abstract class.")
177 # Create a new DeprecatedCommand instance.
178 KickstartCommand.__init__(self, writePriority, *args, **kwargs)
180 def __str__(self):
181 """Placeholder since DeprecatedCommands don't work anymore."""
182 return ""
184 def parse(self, args):
185 """Print a warning message if the command is seen in the input file."""
186 mapping = {"lineno": self.lineno, "cmd": self.currentCmd}
187 warnings.warn(_("Ignoring deprecated command on line %(lineno)s: The %(cmd)s command has been deprecated and no longer has any effect. It may be removed from future releases, which will result in a fatal error from kickstart. Please modify your kickstart file to remove this command.") % mapping, DeprecationWarning)
191 ### HANDLERS
193 class BaseHandler(KickstartObject):
194 """Each version of kickstart syntax is provided by a subclass of this
195 class. These subclasses are what users will interact with for parsing,
196 extracting data, and writing out kickstart files. This is an abstract
197 class.
199 version -- The version this syntax handler supports. This is set by
200 a class attribute of a BaseHandler subclass and is used to
201 set up the command dict. It is for read-only use.
203 version = None
205 def __init__(self, mapping=None, dataMapping=None, commandUpdates=None,
206 dataUpdates=None, *args, **kwargs):
207 """Create a new BaseHandler instance. This method must be provided by
208 all subclasses, but subclasses must call BaseHandler.__init__ first.
210 mapping -- A custom map from command strings to classes,
211 useful when creating your own handler with
212 special command objects. It is otherwise unused
213 and rarely needed. If you give this argument,
214 the mapping takes the place of the default one
215 and so must include all commands you want
216 recognized.
217 dataMapping -- This is the same as mapping, but for data
218 objects. All the same comments apply.
219 commandUpdates -- This is similar to mapping, but does not take
220 the place of the defaults entirely. Instead,
221 this mapping is applied after the defaults and
222 updates it with just the commands you want to
223 modify.
224 dataUpdates -- This is the same as commandUpdates, but for
225 data objects.
228 Instance attributes:
230 commands -- A mapping from a string command to a KickstartCommand
231 subclass object that handles it. Multiple strings can
232 map to the same object, but only one instance of the
233 command object should ever exist. Most users should
234 never have to deal with this directly, as it is
235 manipulated internally and called through dispatcher.
236 currentLine -- The current unprocessed line from the input file
237 that caused this handler to be run.
238 packages -- An instance of pykickstart.parser.Packages which
239 describes the packages section of the input file.
240 platform -- A string describing the hardware platform, which is
241 needed only by system-config-kickstart.
242 scripts -- A list of pykickstart.parser.Script instances, which is
243 populated by KickstartParser.addScript and describes the
244 %pre/%post/%traceback script section of the input file.
247 # We don't want people using this class by itself.
248 if self.__class__ is BaseHandler:
249 raise TypeError("BaseHandler is an abstract class.")
251 KickstartObject.__init__(self, *args, **kwargs)
253 # This isn't really a good place for these, but it's better than
254 # everything else I can think of.
255 self.scripts = []
256 self.packages = Packages()
257 self.platform = ""
259 # These will be set by the dispatcher.
260 self.commands = {}
261 self.currentLine = 0
263 # A dict keyed by an integer priority number, with each value being a
264 # list of KickstartCommand subclasses. This dict is maintained by
265 # registerCommand and used in __str__. No one else should be touching
266 # it.
267 self._writeOrder = {}
269 self._registerCommands(mapping, dataMapping, commandUpdates, dataUpdates)
271 def __str__(self):
272 """Return a string formatted for output to a kickstart file."""
273 retval = ""
275 if self.platform != "":
276 retval += "#platform=%s\n" % self.platform
278 retval += "#version=%s\n" % versionToString(self.version)
280 lst = list(self._writeOrder.keys())
281 lst.sort()
283 for prio in lst:
284 for obj in self._writeOrder[prio]:
285 obj_str = obj.__str__()
286 if type(obj_str) == types.UnicodeType:
287 obj_str = obj_str.encode("utf-8")
288 retval += obj_str
290 for script in self.scripts:
291 script_str = script.__str__()
292 if type(script_str) == types.UnicodeType:
293 script_str = script_str.encode("utf-8")
294 retval += script_str
296 retval += self.packages.__str__()
298 return retval
300 def _insertSorted(self, lst, obj):
301 length = len(lst)
302 i = 0
304 while i < length:
305 # If the two classes have the same name, it's because we are
306 # overriding an existing class with one from a later kickstart
307 # version, so remove the old one in favor of the new one.
308 if obj.__class__.__name__ > lst[i].__class__.__name__:
309 i += 1
310 elif obj.__class__.__name__ == lst[i].__class__.__name__:
311 lst[i] = obj
312 return
313 elif obj.__class__.__name__ < lst[i].__class__.__name__:
314 break
316 if i >= length:
317 lst.append(obj)
318 else:
319 lst.insert(i, obj)
321 def _setCommand(self, cmdObj):
322 # Add an attribute on this version object. We need this to provide a
323 # way for clients to access the command objects. We also need to strip
324 # off the version part from the front of the name.
325 if cmdObj.__class__.__name__.find("_") != -1:
326 name = unicode(cmdObj.__class__.__name__.split("_", 1)[1])
327 else:
328 name = unicode(cmdObj.__class__.__name__).lower()
330 setattr(self, name.lower(), cmdObj)
332 # Also, add the object into the _writeOrder dict in the right place.
333 if cmdObj.writePriority is not None:
334 if cmdObj.writePriority in self._writeOrder:
335 self._insertSorted(self._writeOrder[cmdObj.writePriority], cmdObj)
336 else:
337 self._writeOrder[cmdObj.writePriority] = [cmdObj]
339 def _registerCommands(self, mapping=None, dataMapping=None, commandUpdates=None,
340 dataUpdates=None):
341 if mapping == {} or mapping == None:
342 from pykickstart.handlers.control import commandMap
343 cMap = commandMap[self.version]
344 else:
345 cMap = mapping
347 if dataMapping == {} or dataMapping == None:
348 from pykickstart.handlers.control import dataMap
349 dMap = dataMap[self.version]
350 else:
351 dMap = dataMapping
353 if type(commandUpdates) == dict:
354 cMap.update(commandUpdates)
356 if type(dataUpdates) == dict:
357 dMap.update(dataUpdates)
359 for (cmdName, cmdClass) in list(cMap.items()):
360 # First make sure we haven't instantiated this command handler
361 # already. If we have, we just need to make another mapping to
362 # it in self.commands.
363 # NOTE: We can't use the resetCommand method here since that relies
364 # upon cmdClass already being instantiated. We'll just have to keep
365 # these two code blocks in sync.
366 cmdObj = None
368 for (_key, val) in list(self.commands.items()):
369 if val.__class__.__name__ == cmdClass.__name__:
370 cmdObj = val
371 break
373 # If we didn't find an instance in self.commands, create one now.
374 if cmdObj == None:
375 cmdObj = cmdClass()
376 self._setCommand(cmdObj)
378 # Finally, add the mapping to the commands dict.
379 self.commands[cmdName] = cmdObj
380 self.commands[cmdName].handler = self
382 # We also need to create attributes for the various data objects.
383 # No checks here because dMap is a bijection. At least, that's what
384 # the comment says. Hope no one screws that up.
385 for (dataName, dataClass) in list(dMap.items()):
386 setattr(self, dataName, dataClass)
388 def resetCommand(self, cmdName):
389 """Given the name of a command that's already been instantiated, create
390 a new instance of it that will take the place of the existing
391 instance. This is equivalent to quickly blanking out all the
392 attributes that were previously set.
394 This method raises a KeyError if cmdName is invalid.
396 if cmdName not in self.commands:
397 raise KeyError
399 cmdObj = self.commands[cmdName].__class__()
401 self._setCommand(cmdObj)
402 self.commands[cmdName] = cmdObj
403 self.commands[cmdName].handler = self
405 def dispatcher(self, args, lineno):
406 """Call the appropriate KickstartCommand handler for the current line
407 in the kickstart file. A handler for the current command should
408 be registered, though a handler of None is not an error. Returns
409 the data object returned by KickstartCommand.parse.
411 args -- A list of arguments to the current command
412 lineno -- The line number in the file, for error reporting
414 cmd = args[0]
416 if cmd not in self.commands:
417 raise KickstartParseError(formatErrorMsg(lineno, msg=_("Unknown command: %s" % cmd)))
418 elif self.commands[cmd] != None:
419 self.commands[cmd].currentCmd = cmd
420 self.commands[cmd].currentLine = self.currentLine
421 self.commands[cmd].lineno = lineno
422 self.commands[cmd].seen = True
424 # The parser returns the data object that was modified. This could
425 # be a BaseData subclass that should be put into a list, or it
426 # could be the command handler object itself.
427 obj = self.commands[cmd].parse(args[1:])
428 lst = self.commands[cmd].dataList()
429 if lst is not None:
430 lst.append(obj)
432 return obj
434 def maskAllExcept(self, lst):
435 """Set all entries in the commands dict to None, except the ones in
436 the lst. All other commands will not be processed.
438 self._writeOrder = {}
440 for (key, _val) in list(self.commands.items()):
441 if not key in lst:
442 self.commands[key] = None
444 def hasCommand(self, cmd):
445 """Return true if there is a handler for the string cmd."""
446 return hasattr(self, cmd)
450 ### DATA
452 class BaseData(KickstartObject):
453 """The base class for all data objects. This is an abstract class."""
454 removedKeywords = []
455 removedAttrs = []
457 def __init__(self, *args, **kwargs):
458 """Create a new BaseData instance.
460 lineno -- Line number in the ks-file where this object was defined
463 # We don't want people using this class by itself.
464 if self.__class__ is BaseData:
465 raise TypeError("BaseData is an abstract class.")
467 KickstartObject.__init__(self, *args, **kwargs)
468 self.lineno = 0
470 def __str__(self):
471 """Return a string formatted for output to a kickstart file."""
472 return ""
474 def __call__(self, *args, **kwargs):
475 """Set multiple attributes on a subclass of BaseData at once via
476 keyword arguments. Valid attributes are anything specified in a
477 subclass, but unknown attributes will be ignored.
479 for (key, val) in list(kwargs.items()):
480 # Ignore setting attributes that were removed in a subclass, as
481 # if they were unknown attributes.
482 if key in self.removedAttrs:
483 continue
485 if hasattr(self, key):
486 setattr(self, key, val)
488 def deleteRemovedAttrs(self):
489 """Remove all attributes from self that are given in the removedAttrs
490 list. This method should be called from __init__ in a subclass,
491 but only after the superclass's __init__ method has been called.
493 for attr in [k for k in self.removedAttrs if hasattr(self, k)]:
494 delattr(self, attr)