Append a newline to the reboot command output.
[pykickstart.git] / pykickstart / base.py
blob07a68b913250cd4bd7aecef3c00a83fd1db0ab4f
2 # Chris Lumens <clumens@redhat.com>
4 # Copyright 2006, 2007, 2008 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 warnings
46 from pykickstart.errors import *
47 from pykickstart.ko import *
48 from pykickstart.parser import Packages
49 from pykickstart.version import versionToString
51 ###
52 ### COMMANDS
53 ###
54 class KickstartCommand(KickstartObject):
55 """The base class for all kickstart commands. This is an abstract class."""
56 removedKeywords = []
57 removedAttrs = []
59 def __init__(self, writePriority=0, *args, **kwargs):
60 """Create a new KickstartCommand instance. This method must be
61 provided by all subclasses, but subclasses must call
62 KickstartCommand.__init__ first. Instance attributes:
64 currentCmd -- The name of the command in the input file that
65 caused this handler to be run.
66 currentLine -- The current unprocessed line from the input file
67 that caused this handler to be run.
68 handler -- A reference to the BaseHandler subclass this
69 command is contained withing. This is needed to
70 allow referencing of Data objects.
71 lineno -- The current line number in the input file.
72 writePriority -- An integer specifying when this command should be
73 printed when iterating over all commands' __str__
74 methods. The higher the number, the later this
75 command will be written. All commands with the
76 same priority will be written alphabetically.
77 """
79 # We don't want people using this class by itself.
80 if self.__class__ is KickstartCommand:
81 raise TypeError, "KickstartCommand is an abstract class."
83 KickstartObject.__init__(self, *args, **kwargs)
85 self.writePriority = writePriority
87 # These will be set by the dispatcher.
88 self.currentCmd = ""
89 self.currentLine = ""
90 self.handler = None
91 self.lineno = 0
93 # If a subclass provides a removedKeywords list, remove all the
94 # members from the kwargs list before we start processing it. This
95 # ensures that subclasses don't continue to recognize arguments that
96 # were removed.
97 for arg in filter(lambda k: kwargs.has_key(k), self.removedKeywords):
98 kwargs.pop(arg)
100 def __call__(self, *args, **kwargs):
101 """Set multiple attributes on a subclass of KickstartCommand at once
102 via keyword arguments. Valid attributes are anything specified in
103 a subclass, but unknown attributes will be ignored.
105 for (key, val) in kwargs.items():
106 # Ignore setting attributes that were removed in a subclass, as
107 # if they were unknown attributes.
108 if key in self.removedAttrs:
109 continue
111 if hasattr(self, key):
112 setattr(self, key, val)
114 def __str__(self):
115 """Return a string formatted for output to a kickstart file. This
116 method must be provided by all subclasses.
118 return KickstartObject.__str__(self)
120 def parse(self, args):
121 """Parse the list of args and set data on the KickstartCommand object.
122 This method must be provided by all subclasses.
124 raise TypeError, "parse() not implemented for KickstartCommand"
126 def apply(self, instroot="/"):
127 """Write out the configuration related to the KickstartCommand object.
128 Subclasses which do not provide this method will not have their
129 configuration written out.
131 return
133 def dataList(self):
134 """For commands that can occur multiple times in a single kickstart
135 file (like network, part, etc.), return the list that we should
136 append more data objects to.
138 return None
140 def deleteRemovedAttrs(self):
141 """Remove all attributes from self that are given in the removedAttrs
142 list. This method should be called from __init__ in a subclass,
143 but only after the superclass's __init__ method has been called.
145 for attr in filter(lambda k: hasattr(self, k), self.removedAttrs):
146 delattr(self, attr)
148 # Set the contents of the opts object (an instance of optparse.Values
149 # returned by parse_args) as attributes on the KickstartCommand object.
150 # It's useful to call this from KickstartCommand subclasses after parsing
151 # the arguments.
152 def _setToSelf(self, optParser, opts):
153 self._setToObj(optParser, opts, self)
155 # Sets the contents of the opts object (an instance of optparse.Values
156 # returned by parse_args) as attributes on the provided object obj. It's
157 # useful to call this from KickstartCommand subclasses that handle lists
158 # of objects (like partitions, network devices, etc.) and need to populate
159 # a Data object.
160 def _setToObj(self, optParser, opts, obj):
161 for key in filter (lambda k: getattr(opts, k) != None, optParser.keys()):
162 setattr(obj, key, getattr(opts, key))
164 class DeprecatedCommand(KickstartCommand):
165 """Specify that a command is deprecated and no longer has any function.
166 Any command that is deprecated should be subclassed from this class,
167 only specifying an __init__ method that calls the superclass's __init__.
168 This is an abstract class.
170 def __init__(self, writePriority=None, *args, **kwargs):
171 # We don't want people using this class by itself.
172 if self.__class__ is KickstartCommand:
173 raise TypeError, "DeprecatedCommand is an abstract class."
175 """Create a new DeprecatedCommand instance."""
176 KickstartCommand.__init__(self, writePriority, *args, **kwargs)
178 def __str__(self):
179 """Placeholder since DeprecatedCommands don't work anymore."""
180 return ""
182 def parse(self, args):
183 """Print a warning message if the command is seen in the input file."""
184 mapping = {"lineno": self.lineno, "cmd": self.currentCmd}
185 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)
189 ### HANDLERS
191 class BaseHandler(KickstartObject):
192 """Each version of kickstart syntax is provided by a subclass of this
193 class. These subclasses are what users will interact with for parsing,
194 extracting data, and writing out kickstart files. This is an abstract
195 class.
198 """version -- The version this syntax handler supports. This is set by
199 a class attribute of a BaseHandler subclass and is used to
200 set up the command dict. It is for read-only use.
202 version = None
204 def __init__(self, mapping={}, *args, **kwargs):
205 """Create a new BaseHandler instance. This method must be provided by
206 all subclasses, but subclasses must call BaseHandler.__init__ first.
207 mapping is a custom map from command strings to classes, useful when
208 creating your own handler with special command objects. It is
209 otherwise unused and rarely needed.
211 Instance attributes:
213 commands -- A mapping from a string command to a KickstartCommand
214 subclass object that handles it. Multiple strings can
215 map to the same object, but only one instance of the
216 command object should ever exist. Most users should
217 never have to deal with this directly, as it is
218 manipulated internally and called through dispatcher.
219 currentLine -- The current unprocessed line from the input file
220 that caused this handler to be run.
221 packages -- An instance of pykickstart.parser.Packages which
222 describes the packages section of the input file.
223 platform -- A string describing the hardware platform, which is
224 needed only by system-config-kickstart.
225 scripts -- A list of pykickstart.parser.Script instances, which is
226 populated by KickstartParser.addScript and describes the
227 %pre/%post/%traceback script section of the input file.
230 # We don't want people using this class by itself.
231 if self.__class__ is BaseHandler:
232 raise TypeError, "BaseHandler is an abstract class."
234 KickstartObject.__init__(self, *args, **kwargs)
236 # This isn't really a good place for these, but it's better than
237 # everything else I can think of.
238 self.scripts = []
239 self.packages = Packages()
240 self.platform = ""
242 # These will be set by the dispatcher.
243 self.commands = {}
244 self.currentLine = 0
246 # A dict keyed by an integer priority number, with each value being a
247 # list of KickstartCommand subclasses. This dict is maintained by
248 # registerCommand and used in __str__. No one else should be touching
249 # it.
250 self._writeOrder = {}
252 self._registerCommands(mapping=mapping)
254 def __str__(self):
255 """Return a string formatted for output to a kickstart file."""
256 retval = ""
258 if self.platform != "":
259 retval += "#platform=%s\n" % self.platform
261 retval += "#version=%s\n" % versionToString(self.version)
263 lst = self._writeOrder.keys()
264 lst.sort()
266 for prio in lst:
267 for obj in self._writeOrder[prio]:
268 retval += obj.__str__()
270 for script in self.scripts:
271 retval += script.__str__()
273 retval += self.packages.__str__()
275 return retval
277 def _insertSorted(self, list, obj):
278 length = len(list)
279 i = 0
281 while i < length:
282 # If the two classes have the same name, it's because we are
283 # overriding an existing class with one from a later kickstart
284 # version, so remove the old one in favor of the new one.
285 if obj.__class__.__name__ > list[i].__class__.__name__:
286 i += 1
287 elif obj.__class__.__name__ == list[i].__class__.__name__:
288 list[i] = obj
289 return
290 elif obj.__class__.__name__ < list[i].__class__.__name__:
291 break
293 if i >= length:
294 list.append(obj)
295 else:
296 list.insert(i, obj)
298 def _setCommand(self, cmdObj):
299 # Add an attribute on this version object. We need this to provide a
300 # way for clients to access the command objects. We also need to strip
301 # off the version part from the front of the name.
302 if cmdObj.__class__.__name__.find("_") != -1:
303 name = unicode(cmdObj.__class__.__name__.split("_", 1)[1])
304 else:
305 name = unicode(cmdObj.__class__.__name__).lower()
307 setattr(self, name.lower(), cmdObj)
309 # Also, add the object into the _writeOrder dict in the right place.
310 if cmdObj.writePriority is not None:
311 if self._writeOrder.has_key(cmdObj.writePriority):
312 self._insertSorted(self._writeOrder[cmdObj.writePriority], cmdObj)
313 else:
314 self._writeOrder[cmdObj.writePriority] = [cmdObj]
316 def _registerCommands(self, mapping={}):
317 if mapping == {}:
318 from pykickstart.handlers.control import commandMap, dataMap
319 cMap = commandMap[self.version]
320 dMap = dataMap[self.version]
321 else:
322 from pykickstart.handlers.control import dataMap
323 cMap = mapping
324 dMap = dataMap[self.version]
326 for (cmdName, cmdClass) in cMap.iteritems():
327 # First make sure we haven't instantiated this command handler
328 # already. If we have, we just need to make another mapping to
329 # it in self.commands.
330 cmdObj = None
332 for (key, val) in self.commands.iteritems():
333 if val.__class__.__name__ == cmdClass.__name__:
334 cmdObj = val
335 break
337 # If we didn't find an instance in self.commands, create one now.
338 if cmdObj == None:
339 cmdObj = cmdClass()
340 self._setCommand(cmdObj)
342 # Finally, add the mapping to the commands dict.
343 self.commands[cmdName] = cmdObj
344 self.commands[cmdName].handler = self
346 # We also need to create attributes for the various data objects.
347 # No checks here because dMap is a bijection. At least, that's what
348 # the comment says. Hope no one screws that up.
349 for (dataName, dataClass) in dMap.iteritems():
350 setattr(self, dataName, dataClass)
352 def dispatcher(self, args, lineno, include=None):
353 """Call the appropriate KickstartCommand handler for the current line
354 in the kickstart file. A handler for the current command should
355 be registered, though a handler of None is not an error.
357 args -- A list of arguments to the current command
358 lineno -- The line number in the file, for error reporting
359 include -- The path to any file %included immediately before the
360 current command
362 cmd = args[0]
364 if not self.commands.has_key(cmd):
365 raise KickstartParseError, formatErrorMsg(lineno, msg=_("Unknown command: %s" % cmd))
366 elif self.commands[cmd] != None:
367 self.commands[cmd].currentCmd = cmd
368 self.commands[cmd].currentLine = self.currentLine
369 self.commands[cmd].lineno = lineno
371 # The parser returns the data object that was modified. This could
372 # be a BaseData subclass that should be put into a list, or it
373 # could be the command handler object itself. If there's an
374 # include that preceeds either, we need to then associated it with
375 # the returned object.
376 obj = self.commands[cmd].parse(args[1:])
377 lst = self.commands[cmd].dataList()
378 if lst is not None:
379 lst.append(obj)
381 if include is not None:
382 obj.preceededInclude = include
384 def maskAllExcept(self, lst):
385 """Set all entries in the commands dict to None, except the ones in
386 the lst. All other commands will not be processed.
388 self._writeOrder = {}
390 for (key, val) in self.commands.iteritems():
391 if not key in lst:
392 self.commands[key] = None
394 def hasCommand(self, cmd):
395 """Return true if there is a handler for the string cmd."""
396 return hasattr(self, cmd)
400 ### DATA
402 class BaseData(KickstartObject):
403 """The base class for all data objects. This is an abstract class."""
404 removedKeywords = []
405 removedAttrs = []
407 def __init__(self, *args, **kwargs):
408 """Create a new BaseData instance. There are no attributes."""
410 # We don't want people using this class by itself.
411 if self.__class__ is BaseData:
412 raise TypeError, "BaseData is an abstract class."
414 KickstartObject.__init__(self, *args, **kwargs)
416 def __str__(self):
417 """Return a string formatted for output to a kickstart file."""
418 return ""
420 def __call__(self, *args, **kwargs):
421 """Set multiple attributes on a subclass of BaseData at once via
422 keyword arguments. Valid attributes are anything specified in a
423 subclass, but unknown attributes will be ignored.
425 for (key, val) in kwargs.items():
426 # Ignore setting attributes that were removed in a subclass, as
427 # if they were unknown attributes.
428 if key in self.removedAttrs:
429 continue
431 if hasattr(self, key):
432 setattr(self, key, val)
434 def deleteRemovedAttrs(self):
435 """Remove all attributes from self that are given in the removedAttrs
436 list. This method should be called from __init__ in a subclass,
437 but only after the superclass's __init__ method has been called.
439 for attr in filter(lambda k: hasattr(self, k), self.removedAttrs):
440 delattr(self, attr)