Remove a triple-X message that is no longer needed
[pykickstart.git] / pykickstart / base.py
blob41230ca68b915b0a0a5d25235ba2c2515bee0578
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 *
48 from pykickstart.ko import *
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 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 def parse(self, args):
129 """Parse the list of args and set data on the KickstartCommand object.
130 This method must be provided by all subclasses.
132 raise TypeError("parse() not implemented for KickstartCommand")
134 def apply(self, instroot="/"):
135 """Write out the configuration related to the KickstartCommand object.
136 Subclasses which do not provide this method will not have their
137 configuration written out.
139 return
141 def dataList(self):
142 """For commands that can occur multiple times in a single kickstart
143 file (like network, part, etc.), return the list that we should
144 append more data objects to.
146 return None
148 def deleteRemovedAttrs(self):
149 """Remove all attributes from self that are given in the removedAttrs
150 list. This method should be called from __init__ in a subclass,
151 but only after the superclass's __init__ method has been called.
153 for attr in filter(lambda k: hasattr(self, k), self.removedAttrs):
154 delattr(self, attr)
156 # Set the contents of the opts object (an instance of optparse.Values
157 # returned by parse_args) as attributes on the KickstartCommand object.
158 # It's useful to call this from KickstartCommand subclasses after parsing
159 # the arguments.
160 def _setToSelf(self, optParser, opts):
161 self._setToObj(optParser, opts, self)
163 # Sets the contents of the opts object (an instance of optparse.Values
164 # returned by parse_args) as attributes on the provided object obj. It's
165 # useful to call this from KickstartCommand subclasses that handle lists
166 # of objects (like partitions, network devices, etc.) and need to populate
167 # a Data object.
168 def _setToObj(self, optParser, opts, obj):
169 for key in filter (lambda k: getattr(opts, k) != None, optParser.keys()):
170 setattr(obj, key, getattr(opts, key))
172 class DeprecatedCommand(KickstartCommand):
173 """Specify that a command is deprecated and no longer has any function.
174 Any command that is deprecated should be subclassed from this class,
175 only specifying an __init__ method that calls the superclass's __init__.
176 This is an abstract class.
178 def __init__(self, writePriority=None, *args, **kwargs):
179 # We don't want people using this class by itself.
180 if self.__class__ is KickstartCommand:
181 raise TypeError("DeprecatedCommand is an abstract class.")
183 # Create a new DeprecatedCommand instance.
184 KickstartCommand.__init__(self, writePriority, *args, **kwargs)
186 def __str__(self):
187 """Placeholder since DeprecatedCommands don't work anymore."""
188 return ""
190 def parse(self, args):
191 """Print a warning message if the command is seen in the input file."""
192 mapping = {"lineno": self.lineno, "cmd": self.currentCmd}
193 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)
197 ### HANDLERS
199 class BaseHandler(KickstartObject):
200 """Each version of kickstart syntax is provided by a subclass of this
201 class. These subclasses are what users will interact with for parsing,
202 extracting data, and writing out kickstart files. This is an abstract
203 class.
205 version -- The version this syntax handler supports. This is set by
206 a class attribute of a BaseHandler subclass and is used to
207 set up the command dict. It is for read-only use.
209 version = None
211 def __init__(self, mapping=None, dataMapping=None, commandUpdates=None,
212 dataUpdates=None, *args, **kwargs):
213 """Create a new BaseHandler instance. This method must be provided by
214 all subclasses, but subclasses must call BaseHandler.__init__ first.
216 mapping -- A custom map from command strings to classes,
217 useful when creating your own handler with
218 special command objects. It is otherwise unused
219 and rarely needed. If you give this argument,
220 the mapping takes the place of the default one
221 and so must include all commands you want
222 recognized.
223 dataMapping -- This is the same as mapping, but for data
224 objects. All the same comments apply.
225 commandUpdates -- This is similar to mapping, but does not take
226 the place of the defaults entirely. Instead,
227 this mapping is applied after the defaults and
228 updates it with just the commands you want to
229 modify.
230 dataUpdates -- This is the same as commandUpdates, but for
231 data objects.
234 Instance attributes:
236 commands -- A mapping from a string command to a KickstartCommand
237 subclass object that handles it. Multiple strings can
238 map to the same object, but only one instance of the
239 command object should ever exist. Most users should
240 never have to deal with this directly, as it is
241 manipulated internally and called through dispatcher.
242 currentLine -- The current unprocessed line from the input file
243 that caused this handler to be run.
244 packages -- An instance of pykickstart.parser.Packages which
245 describes the packages section of the input file.
246 platform -- A string describing the hardware platform, which is
247 needed only by system-config-kickstart.
248 scripts -- A list of pykickstart.parser.Script instances, which is
249 populated by KickstartParser.addScript and describes the
250 %pre/%post/%traceback script section of the input file.
253 # We don't want people using this class by itself.
254 if self.__class__ is BaseHandler:
255 raise TypeError("BaseHandler is an abstract class.")
257 KickstartObject.__init__(self, *args, **kwargs)
259 # This isn't really a good place for these, but it's better than
260 # everything else I can think of.
261 self.scripts = []
262 self.packages = Packages()
263 self.platform = ""
265 # These will be set by the dispatcher.
266 self.commands = {}
267 self.currentLine = 0
269 # A dict keyed by an integer priority number, with each value being a
270 # list of KickstartCommand subclasses. This dict is maintained by
271 # registerCommand and used in __str__. No one else should be touching
272 # it.
273 self._writeOrder = {}
275 self._registerCommands(mapping, dataMapping, commandUpdates, dataUpdates)
277 def __str__(self):
278 """Return a string formatted for output to a kickstart file."""
279 retval = ""
281 if self.platform != "":
282 retval += "#platform=%s\n" % self.platform
284 retval += "#version=%s\n" % versionToString(self.version)
286 lst = self._writeOrder.keys()
287 lst.sort()
289 for prio in lst:
290 for obj in self._writeOrder[prio]:
291 obj_str = obj.__str__()
292 if type(obj_str) == types.UnicodeType:
293 obj_str = obj_str.encode("utf-8")
294 retval += obj_str
296 for script in self.scripts:
297 script_str = script.__str__()
298 if type(script_str) == types.UnicodeType:
299 script_str = script_str.encode("utf-8")
300 retval += script_str
302 retval += self.packages.__str__()
304 return retval
306 def _insertSorted(self, lst, obj):
307 length = len(lst)
308 i = 0
310 while i < length:
311 # If the two classes have the same name, it's because we are
312 # overriding an existing class with one from a later kickstart
313 # version, so remove the old one in favor of the new one.
314 if obj.__class__.__name__ > lst[i].__class__.__name__:
315 i += 1
316 elif obj.__class__.__name__ == lst[i].__class__.__name__:
317 lst[i] = obj
318 return
319 elif obj.__class__.__name__ < lst[i].__class__.__name__:
320 break
322 if i >= length:
323 lst.append(obj)
324 else:
325 lst.insert(i, obj)
327 def _setCommand(self, cmdObj):
328 # Add an attribute on this version object. We need this to provide a
329 # way for clients to access the command objects. We also need to strip
330 # off the version part from the front of the name.
331 if cmdObj.__class__.__name__.find("_") != -1:
332 name = unicode(cmdObj.__class__.__name__.split("_", 1)[1])
333 else:
334 name = unicode(cmdObj.__class__.__name__).lower()
336 setattr(self, name.lower(), cmdObj)
338 # Also, add the object into the _writeOrder dict in the right place.
339 if cmdObj.writePriority is not None:
340 if self._writeOrder.has_key(cmdObj.writePriority):
341 self._insertSorted(self._writeOrder[cmdObj.writePriority], cmdObj)
342 else:
343 self._writeOrder[cmdObj.writePriority] = [cmdObj]
345 def _registerCommands(self, mapping=None, dataMapping=None, commandUpdates=None,
346 dataUpdates=None):
347 if mapping == {} or mapping == None:
348 from pykickstart.handlers.control import commandMap
349 cMap = commandMap[self.version]
350 else:
351 cMap = mapping
353 if dataMapping == {} or dataMapping == None:
354 from pykickstart.handlers.control import dataMap
355 dMap = dataMap[self.version]
356 else:
357 dMap = dataMapping
359 if type(commandUpdates) == types.DictType:
360 cMap.update(commandUpdates)
362 if type(dataUpdates) == types.DictType:
363 dMap.update(dataUpdates)
365 for (cmdName, cmdClass) in cMap.iteritems():
366 # First make sure we haven't instantiated this command handler
367 # already. If we have, we just need to make another mapping to
368 # it in self.commands.
369 # NOTE: We can't use the resetCommand method here since that relies
370 # upon cmdClass already being instantiated. We'll just have to keep
371 # these two code blocks in sync.
372 cmdObj = None
374 for (key, val) in self.commands.iteritems():
375 if val.__class__.__name__ == cmdClass.__name__:
376 cmdObj = val
377 break
379 # If we didn't find an instance in self.commands, create one now.
380 if cmdObj == None:
381 cmdObj = cmdClass()
382 self._setCommand(cmdObj)
384 # Finally, add the mapping to the commands dict.
385 self.commands[cmdName] = cmdObj
386 self.commands[cmdName].handler = self
388 # We also need to create attributes for the various data objects.
389 # No checks here because dMap is a bijection. At least, that's what
390 # the comment says. Hope no one screws that up.
391 for (dataName, dataClass) in dMap.iteritems():
392 setattr(self, dataName, dataClass)
394 def resetCommand(self, cmdName):
395 """Given the name of a command that's already been instantiated, create
396 a new instance of it that will take the place of the existing
397 instance. This is equivalent to quickly blanking out all the
398 attributes that were previously set.
400 This method raises a KeyError if cmdName is invalid.
402 if cmdName not in self.commands:
403 raise KeyError
405 cmdObj = self.commands[cmdName].__class__()
407 self._setCommand(cmdObj)
408 self.commands[cmdName] = cmdObj
409 self.commands[cmdName].handler = self
411 def dispatcher(self, args, lineno):
412 """Call the appropriate KickstartCommand handler for the current line
413 in the kickstart file. A handler for the current command should
414 be registered, though a handler of None is not an error. Returns
415 the data object returned by KickstartCommand.parse.
417 args -- A list of arguments to the current command
418 lineno -- The line number in the file, for error reporting
420 cmd = args[0]
422 if not self.commands.has_key(cmd):
423 raise KickstartParseError(formatErrorMsg(lineno, msg=_("Unknown command: %s" % cmd)))
424 elif self.commands[cmd] != None:
425 self.commands[cmd].currentCmd = cmd
426 self.commands[cmd].currentLine = self.currentLine
427 self.commands[cmd].lineno = lineno
428 self.commands[cmd].seen = True
430 # The parser returns the data object that was modified. This could
431 # be a BaseData subclass that should be put into a list, or it
432 # could be the command handler object itself.
433 obj = self.commands[cmd].parse(args[1:])
434 lst = self.commands[cmd].dataList()
435 if lst is not None:
436 lst.append(obj)
438 return obj
440 def maskAllExcept(self, lst):
441 """Set all entries in the commands dict to None, except the ones in
442 the lst. All other commands will not be processed.
444 self._writeOrder = {}
446 for (key, val) in self.commands.iteritems():
447 if not key in lst:
448 self.commands[key] = None
450 def hasCommand(self, cmd):
451 """Return true if there is a handler for the string cmd."""
452 return hasattr(self, cmd)
456 ### DATA
458 class BaseData(KickstartObject):
459 """The base class for all data objects. This is an abstract class."""
460 removedKeywords = []
461 removedAttrs = []
463 def __init__(self, *args, **kwargs):
464 """Create a new BaseData instance.
466 lineno -- Line number in the ks-file where this object was defined
469 # We don't want people using this class by itself.
470 if self.__class__ is BaseData:
471 raise TypeError("BaseData is an abstract class.")
473 KickstartObject.__init__(self, *args, **kwargs)
474 self.lineno = 0
476 def __str__(self):
477 """Return a string formatted for output to a kickstart file."""
478 return ""
480 def __call__(self, *args, **kwargs):
481 """Set multiple attributes on a subclass of BaseData at once via
482 keyword arguments. Valid attributes are anything specified in a
483 subclass, but unknown attributes will be ignored.
485 for (key, val) in kwargs.items():
486 # Ignore setting attributes that were removed in a subclass, as
487 # if they were unknown attributes.
488 if key in self.removedAttrs:
489 continue
491 if hasattr(self, key):
492 setattr(self, key, val)
494 def deleteRemovedAttrs(self):
495 """Remove all attributes from self that are given in the removedAttrs
496 list. This method should be called from __init__ in a subclass,
497 but only after the superclass's __init__ method has been called.
499 for attr in filter(lambda k: hasattr(self, k), self.removedAttrs):
500 delattr(self, attr)