Пример #1
0
    def runTest(self):
        handler = KickstartHandler()
        self.assertEqual(str(handler), "")

        handler = KickstartHandler()
        handler.registerCommand('autopart', F23_AutoPart)
        handler.registerCommand('btrfs', F17_BTRFS)
        handler.registerData('BTRFSData', F23_BTRFSData)
        handler.registerData('ZFCPData', F14_ZFCPData)

        self.assertEqual(len(handler.commands.keys()), 2)
        self.assertTrue(isinstance(handler.commands['autopart'], F23_AutoPart))
        self.assertTrue(isinstance(handler.commands['btrfs'], F17_BTRFS))

        self.assertTrue(hasattr(handler, 'BTRFSData'))
        self.assertEqual(getattr(handler, 'BTRFSData'), F23_BTRFSData)
        self.assertTrue(hasattr(handler, 'ZFCPData'))
        self.assertEqual(getattr(handler, 'ZFCPData'), F14_ZFCPData)

        handler = KickstartHandler()
        handler.registerCommand('cdrom', FC3_Cdrom)
        handler.version = F25

        parser = KickstartParser(handler)
        parser.readKickstartFromString("cdrom")
        self.assertEqual(str(handler), "# Use CDROM installation media\ncdrom\n")
Пример #2
0
class RevisorKickstart:
    def __init__(self, cfg=None):
        self.cfg = cfg

    def create_parser(self):
        self.handler = makeVersion()
        self.parser = KickstartParser(self.handler)

    def read_file(self, url):
        if not hasattr(self, "parser"):
            self.create_parser()
        self.parser.readKickstart(url)

    def _reset(self):
        self.parser._reset()

    def __str__(self):
        return "%s" % self.handler.__str__()

    def _get(self, item=None, val=None):
        if not item == None:
            if hasattr(self.handler, item):
                if not val is None:
                    if hasattr(getattr(self.handler, item), val):
                        return getattr(getattr(self.handler, item), val)
                    elif isinstance(getattr(self.handler, item), dict):
                        return getattr(self.handler, item)[val]
                    else:
                        return None
                else:
                    return getattr(self.handler, item)
            elif hasattr(self.handler, val):
                return getattr(self.handler, val)
        else:
            return self.handler
def process_kickstart(ksfile):
    # pykickstart refs
    # https://jlaska.fedorapeople.org/pykickstart-doc/pykickstart.commands.html
    ksparser = KickstartParser(makeVersion())
    try:
        ksparser.readKickstart(ksfile)
    except KickstartError as e:
        sys.stderr.write(str(e))
        sys.exit(1)
    user_data = '#!/bin/bash'
    # repo
    for repo in ksparser.handler.repo.repoList:
        if repo.mirrorlist:
            repo_url = 'metalink=%s' % repo.mirrorlist
        else:
            repo_url = 'baseurl=%s' % repo.baseurl
        user_data += """
cat <<"EOF" >/etc/yum.repos.d/%s.repo
[%s]
name=%s
%s
enabled=1
gpgcheck=0
EOF
""" % (repo.name,
       repo.name,
       repo.name,
       repo_url)  
    # rootpw
    if ksparser.handler.rootpw.isCrypted:
        user_data += 'echo "root:%s" | chpasswd -e\n' % ksparser.handler.rootpw.password
    else:
        user_data += 'echo "root:%s" | chpasswd\n' % ksparser.handler.rootpw.password
    # selinux
    if ksparser.handler.selinux.selinux is 0:
        selinux_status = 'disabled'
    elif ksparser.handler.selinux.selinux is 2:
        selinux_status = 'enforcing'
    else:
        selinux_status = 'enforcing'
    user_data += "sed -i 's/SELINUX=.*/SELINUX=%s/' /etc/selinux/config\n" % selinux_status
    # %packages
    packages = []
    for group in ksparser.handler.packages.groupList:
        packages.append("@%s" % group.name)
    for package in ksparser.handler.packages.packageList:
        packages.append(package)
    if packages:
        user_data += "yum -y install %s\n" % ' '.join(packages)
    # skip %prep
    # %post
    user_data += ksparser.handler.scripts[1].script
    # remove cloud-init package and reboot
    user_data += 'yum -y remove cloud-init\nreboot'
    print user_data
Пример #4
0
    def runTest(self):
        for version, command_map in control.commandMap.items():

            handler = makeVersion(version)
            parser = KickstartParser(handler)

            for command_name, command_class in command_map.items():
                if not issubclass(command_class, DeprecatedCommand):
                    continue

                with warnings.catch_warnings(record=True):
                    # The deprecated commands should be ignored with
                    # a warning when they are parsed. Make sure that
                    # they will not cause any errors.
                    parser.readKickstartFromString(command_name)
Пример #5
0
 def load_or_default(system_ks_path, ks_template):
     """ load system ks or default ks """
     ksparser = KickstartParser(makeVersion())
     try:
         ksparser.readKickstart(system_ks_path)
     except (KickstartError, IOError):
         log_message("Cannot read the system Kickstart at %s." % system_ks_path)
         try:
             ksparser.readKickstart(ks_template)
         except AttributeError:
             log_message("There is no KS_POSTSCRIPT_TEMPLATE specified in settings.py.", level=logging.DEBUG)
         except IOError:
             log_message("Cannot read the Kickstart template %s." % ks_template)
             return None
     return ksparser
Пример #6
0
 def load_or_default(system_ks_path):
     """load system ks or default ks"""
     ksparser = KickstartParser(makeVersion())
     try:
         ksparser.readKickstart(system_ks_path)
     except (KickstartError, IOError):
         log_message("Can't read system kickstart at {0}".format(system_ks_path))
         try:
             ksparser.readKickstart(settings.KS_TEMPLATE)
         except AttributeError:
             log_message("There is no KS_TEMPLATE_POSTSCRIPT specified in settings.py")
         except IOError:
             log_message("Can't read kickstart template {0}".format(settings.KS_TEMPLATE))
             return None
     return ksparser
Пример #7
0
    def add_repo(self, ksfile, siderepo):
        """ Add a repository to an existing KS file """

        # read
        ksparser = KickstartParser(makeVersion())
        ksparser.readKickstart(ksfile)
        
        #obtain the handler dump
        kshandlers = ksparser.handler

        # add a repository
        kshandlers.repo.repoList.extend(['repo --name="siderepo" --baseurl={0:s}\n'.format(siderepo)])

        # Write a new ks file
        outfile = open(ksfile, 'w')
        outfile.write(kshandlers.__str__())
        outfile.close()

        return
Пример #8
0
def main(argv):
    op = argparse.ArgumentParser(usage="%(prog)s [options] ksfile", add_help=False)
    op.add_argument("ksfile", nargs="?",
                    help=_("filename or URL to read from"))
    op.add_argument("-e", "--firsterror", dest="firsterror", action="store_true",
                    default=False, help=_("halt after the first error or warning"))
    op.add_argument("-i", "--followincludes", dest="followincludes",
                    action="store_true", default=False,
                    help=_("parse include files when %%include is seen"))
    op.add_argument("-l", "--listversions", dest="listversions", action="store_true",
                    default=False,
                    help=_("list the available versions of kickstart syntax"))
    op.add_argument("-v", "--version", dest="version", default=DEVEL,
                    help=_("version of kickstart syntax to validate against"))
    op.add_argument("-h", "--help", dest="help", action="store_true", default=False,
                    help=_("show this help message and exit"))

    opts = op.parse_args(argv)

    # parse --help manually b/c we don't want to sys.exit before the
    # tests have finished
    if opts.help:
        return (0, op.format_help().split("\n"))

    if opts.listversions:
        versions = []
        for key in sorted(versionMap.keys()):
            versions.append(key)
        return (0, versions)

    if not opts.ksfile:
        return (1, op.format_usage().split("\n"))

    destdir = tempfile.mkdtemp("", "ksvalidator-tmp-", "/tmp")
    try:
        f = load_to_file(opts.ksfile, "%s/ks.cfg" % destdir)
    except KickstartError as e:
        return (cleanup(destdir),
                [_("Error reading %(filename)s:\n%(version)s") % {"filename": opts.ksfile, "version": e}])

    try:
        handler = makeVersion(opts.version)
    except KickstartVersionError:
        return (cleanup(destdir),
                [_("The version %s is not supported by pykickstart") % opts.version])

    ksparser = KickstartParser(handler, followIncludes=opts.followincludes,
                               errorsAreFatal=opts.firsterror)

    # turn DeprecationWarnings into errors
    warnings.filterwarnings("error")

    processedFile = None

    try:
        processedFile = preprocessKickstart(f)
        ksparser.readKickstart(processedFile)
        return (cleanup(destdir, processedFile, exitval=ksparser.errorsCount), [])
    except DeprecationWarning as err:
        return (cleanup(destdir, processedFile),
                [_("File uses a deprecated option or command.\n%s") % err])
    except KickstartParseError as err:
        return (cleanup(destdir, processedFile), [str(err)])
    except KickstartError:
        return (cleanup(destdir, processedFile),
                [_("General kickstart error in input file")])
    except Exception as e:
        return (cleanup(destdir, processedFile),
                [_("General error in input file:  %s") % e])
Пример #9
0
def main():

    ##
    ## OPTION PROCESSING
    ##

    op = argparse.ArgumentParser()
    op.add_argument("-i", "--input", dest="input",
                    help=_("a basis file to use for seeding the kickstart data (optional)"))
    op.add_argument("-o", "--output", dest="output",
                    help=_("the location to write the finished kickstart file, or stdout if not given"))
    op.add_argument("-v", "--version", dest="version", default=DEVEL,
                    help=_("version of kickstart syntax to validate against"))

    opts = op.parse_args(sys.argv[1:])

    ##
    ## SETTING UP PYKICKSTART
    ##

    try:
        kshandler = makeVersion(opts.version)
    except KickstartVersionError:
        print(_("The version %s is not supported by pykickstart") % opts.version)
        sys.exit(1)

    ksparser = KickstartParser(kshandler, followIncludes=True, errorsAreFatal=False)

    if opts.input:
        try:
            processedFile = preprocessKickstart(opts.input)
            ksparser.readKickstart(processedFile)
            os.remove(processedFile)
        except KickstartError as e:
            # Errors should just dump you to the prompt anyway.
            print(_("Warning:  The following error occurred when processing the input file:\n%s\n") % e)

    internalCommands = {".clear": ClearCommand(),
                        ".show": ShowCommand(),
                        ".quit": QuitCommand()}

    ##
    ## SETTING UP READLINE
    ##

    readline.parse_and_bind("tab: complete")
    readline.set_completer(KickstartCompleter(kshandler, internalCommands).complete)

    # Since everything in kickstart looks like a command line arg, we need to
    # remove '-' from the delimiter string.
    delims = readline.get_completer_delims()
    readline.set_completer_delims(delims.replace('-', ''))

    ##
    ## REPL
    ##

    print("Press ^D to exit.")

    while True:
        try:
            line = six.moves.input("ks> ")  # pylint: disable=no-member
        except EOFError:
            # ^D was hit, time to quit.
            break
        except KeyboardInterrupt:
            # ^C was hit, time to quit.  Don't be like other programs.
            break

        # All internal commands start with a ., so if that's the beginning of the
        # line, we need to dispatch ourselves.
        if line.startswith("."):
            words = line.split()
            if words[0] in internalCommands:
                try:
                    internalCommands[words[0]].execute(ksparser)
                except EOFError:
                    # ".quit" was typed, time to quit.
                    break
            else:
                print(_("Internal command %s not recognized.") % words[0])

            continue

        # Now process the line of input as if it were a kickstart file - just an
        # extremely short one.
        try:
            ksparser.readKickstartFromString(line)
        except KickstartError as e:
            print(e)

    # And finally, print the output kickstart file.
    if opts.output:
        with open(opts.output, "w") as fd:
            fd.write(str(ksparser.handler))
    else:
        print("\n" + str(ksparser.handler))
Пример #10
0
    def handleCommand(self, lineno, args):
        if not self.handler:
            return

        return KickstartParser.handleCommand(self, lineno, args)
Пример #11
0
op.add_argument("-v", "--version", dest="version", default=DEVEL,
                help=_("version of kickstart syntax to validate against"))

opts = op.parse_args(sys.argv[1:])

##
## SETTING UP PYKICKSTART
##

try:
    kshandler = makeVersion(opts.version)
except KickstartVersionError:
    print(_("The version %s is not supported by pykickstart") % opts.version)
    sys.exit(1)

ksparser = KickstartParser(kshandler, followIncludes=True, errorsAreFatal=False)

if opts.input:
    try:
        processedFile = preprocessKickstart(opts.input)
        ksparser.readKickstart(processedFile)
        os.remove(processedFile)
    except KickstartError as e:
        # Errors should just dump you to the prompt anyway.
        print(_("Warning:  The following error occurred when processing the input file:\n%s\n") % e)

internalCommands = {".clear": ClearCommand(),
                    ".show": ShowCommand(),
                    ".quit": QuitCommand()}

##
Пример #12
0
    sys.exit(1)

destdir = tempfile.mkdtemp("", "ksvalidator-tmp-", "/tmp")
try:
    f = load_to_file(opts.ksfile, "%s/ks.cfg" % destdir)
except KickstartError as e:
    print(_("Error reading %(filename)s:\n%(version)s") % {"filename": opts.ksfile, "version": e})
    cleanup(destdir)

try:
    handler = makeVersion(opts.version)
except KickstartVersionError:
    print(_("The version %s is not supported by pykickstart") % opts.version)
    cleanup(destdir)

ksparser = KickstartParser(handler, followIncludes=opts.followincludes,
                           errorsAreFatal=opts.firsterror)

# turn DeprecationWarnings into errors
warnings.filterwarnings("error")

processedFile = None

try:
    processedFile = preprocessKickstart(f)
    ksparser.readKickstart(processedFile)
    cleanup(destdir, processedFile, exitval=0)
except DeprecationWarning as msg:
    print(_("File uses a deprecated option or command.\n%s") % msg)
    cleanup(destdir, processedFile)
except KickstartParseError as msg:
    print(msg)
Пример #13
0
 def create_parser(self):
     self.handler = makeVersion()
     self.parser = KickstartParser(self.handler)