def parseKickstart(handler, f, strict_mode=False, pass_to_boss=False): # preprocessing the kickstart file has already been handled in initramfs. ksparser = AnacondaKSParser(handler) kswarnings = [] showwarning = warnings.showwarning def ksshowwarning(message, category, filename, lineno, file=None, line=None): # Print the warning with default function. showwarning(message, category, filename, lineno, file, line) # Collect pykickstart warnings. if issubclass(category, KickstartParseWarning): kswarnings.append(message) try: # Process warnings differently in this part. with warnings.catch_warnings(): # Set up the warnings module. warnings.showwarning = ksshowwarning warnings.simplefilter("always", category=KickstartParseWarning) # Parse the kickstart file in DBus modules. if pass_to_boss: boss = BOSS.get_proxy() report = KickstartReport.from_structure( boss.ReadKickstartFile(f) ) for warn in report.warning_messages: warnings.warn(warn.message, KickstartParseWarning) if not report.is_valid(): message = "\n\n".join(map(str, report.error_messages)) raise KickstartError(message) # Parse the kickstart file in anaconda. ksparser.readKickstart(f) # Process pykickstart warnings in the strict mode: if strict_mode and kswarnings: raise KickstartError("Please modify your kickstart file to fix the warnings " "or remove the `ksstrict` option.") except KickstartError as e: # We do not have an interface here yet, so we cannot use our error # handling callback. parsing_log.error(e) # Print kickstart warnings in the strict mode. if strict_mode and kswarnings: print(_("\nSome warnings occurred during reading the kickstart file:")) for w in kswarnings: print(str(w).strip()) # Print an error and terminate. print(_("\nAn error occurred during reading the kickstart file:" "\n%s\n\nThe installer will now terminate.") % str(e).strip()) util.ipmi_report(IPMI_ABORTED) time.sleep(10) sys.exit(1)
def download_escrow_certificate(url): """Download the escrow certificate. :param url: an URL of the certificate :return: a content of the certificate """ # Do we need a network connection? if not url.startswith("/") and not url.startswith("file:"): network_proxy = NETWORK.get_proxy() if not network_proxy.Connected: raise KickstartError(_("Escrow certificate %s requires the network.") % url) # Download the certificate. log.info("Downloading an escrow certificate from: %s", url) try: request = util.requests_session().get(url, verify=True) except requests.exceptions.SSLError as e: raise KickstartError(_("SSL error while downloading the escrow certificate:\n\n%s") % e) except requests.exceptions.RequestException as e: raise KickstartError(_("The following error was encountered while downloading the " "escrow certificate:\n\n%s") % e) try: certificate = request.content finally: request.close() return certificate
def _load_url(location): '''Load a location (URL or filename) and return contents as string''' try: request = requests.get(location, verify=SSL_VERIFY) except SSLError as e: raise KickstartError(_('Error securely accessing URL "%s"') % location + ': {e}'.format(e=str(e))) except RequestException as e: raise KickstartError(_('Error accessing URL "%s"') % location + ': {e}'.format(e=str(e))) if request.status_code != requests.codes.ok: raise KickstartError(_('Error accessing URL "%s"') % location + ': {c}'.format(c=str(request.status_code))) return request.text
def readKickstart(self, f, reset=True): """Process a kickstart file, given by the filename f.""" if reset: self._reset() # an %include might not specify a full path. if we don't try to figure # out what the path should have been, then we're unable to find it # requiring full path specification, though, sucks. so let's make # the reading "smart" by keeping track of what the path is at each # include depth. if not os.path.exists(f): if self._includeDepth - 1 in self.currentdir: if os.path.exists(os.path.join(self.currentdir[self._includeDepth - 1], f)): f = os.path.join(self.currentdir[self._includeDepth - 1], f) cd = os.path.dirname(f) if not cd.startswith("/"): cd = os.path.abspath(cd) self.currentdir[self._includeDepth] = cd try: s = load_to_str(f) except KickstartError as e: raise KickstartError(formatErrorMsg(0, msg=_("Unable to open input kickstart file: %s") % str(e))) self.readKickstartFromString(s, reset=False)
def load_to_file(location, destination): '''Load a destination URL or file into a file name. Type of input is inferred automatically. Arguments: location -- URL or file name to load destination -- destination file name to write to Returns: file name with contents Raises: KickstartError on error reading or writing''' if _is_url(location): contents = _load_url(location) # Write to file try: with open(destination, 'w') as fh: fh.write(contents) except IOError as e: raise KickstartError(_('Error writing file "%s":') % location + ': {e}'.format(e=str(e))) return destination else: _copy_file(location, destination) return destination
def _copy_file(filename, destination): '''Copy file to destination''' try: shutil.copyfile(filename, destination) except OSError as e: raise KickstartError(_('Error copying file: %s') % str(e))
def methodToRepo(self): if not self.handler.method.url: raise KickstartError(_("Method must be a url to be added to the repo list."), lineno=self.handler.method.lineno) reponame = "ks-method-url" repourl = self.handler.method.url rd = self.handler.RepoData(name=reponame, baseurl=repourl) return rd
def _load_file(filename): '''Load a file's contents and return them as a string''' try: with open(filename, 'r') as fh: contents = fh.read() except IOError as e: raise KickstartError(_('Error opening file: %s') % str(e)) return contents
def _preprocessStateMachine(lineIter): l = None lineno = 0 # Now open an output kickstart file that we are going to write to one # line at a time. (outF, outName) = tempfile.mkstemp("-ks.cfg", "", "/tmp") while True: try: l = next(lineIter) except StopIteration: break # At the end of the file? if l == "": break lineno += 1 ksurl = None ll = l.strip() if not ll.startswith("%ksappend"): if six.PY3: import sys l = l.encode(sys.getdefaultencoding()) os.write(outF, l) continue # Try to pull down the remote file. try: ksurl = ll.split(' ')[1] except: raise KickstartParseError( formatErrorMsg(lineno, msg=_("Illegal url for %%ksappend: %s") % ll)) try: contents = load_to_str(ksurl) except KickstartError as e: raise KickstartError( formatErrorMsg(lineno, msg=_("Unable to open %%ksappend file: %s") % str(e))) # If that worked, write the remote file to the output kickstart # file in one burst. Then close everything up to get ready to # read ahead in the input file. This allows multiple %ksappend # lines to exist. if contents is not None: os.write(outF, contents) # All done - close the temp file and return its location. os.close(outF) return outName
def _run(self, cmd, args, required=True): if not os.path.lexists(conf.target.system_root + cmd): if required: msg = _("%s is missing. Cannot setup authentication.") % cmd raise KickstartError(msg) else: return try: util.execInSysroot(cmd, args) except RuntimeError as msg: authselect_log.error("Error running %s %s: %s", cmd, args, msg)
def preprocessKickstartToString (f): """Preprocess the kickstart file, given by the filename f. This method is currently only useful for handling %ksappend lines, which need to be fetched before the real kickstart parser can be run. Returns the complete kickstart file as a string. """ try: contents = load_to_str(f) except KickstartError as e: raise KickstartError(formatErrorMsg(0, msg=_("Unable to open input kickstart file: %s") % str(e))) return _preprocessStateMachine(iter(contents.splitlines(True)))
def preprocessKickstart(f): """Preprocess the kickstart file, given by the filename file. This method is currently only useful for handling %ksappend lines, which need to be fetched before the real kickstart parser can be run. Returns the location of the complete kickstart file. """ try: fh = grabber.urlopen(f) except grabber.URLGrabError, e: raise KickstartError( formatErrorMsg(0, msg=_("Unable to open input kickstart file: %s") % e.strerror))
def _preprocessStateMachine(lineIter): l = None lineno = 0 retval = "" if six.PY3: retval = retval.encode(sys.getdefaultencoding()) while True: try: l = next(lineIter) except StopIteration: break # At the end of the file? if l == "": break lineno += 1 ksurl = None ll = l.strip() if not ll.startswith("%ksappend"): if six.PY3: l = l.encode(sys.getdefaultencoding()) retval += l continue # Try to pull down the remote file. try: ksurl = ll.split(' ')[1] except: raise KickstartParseError( formatErrorMsg(lineno, msg=_("Illegal url for %%ksappend: %s") % ll)) try: contents = load_to_str(ksurl) except KickstartError as e: raise KickstartError( formatErrorMsg(lineno, msg=_("Unable to open %%ksappend file: %s") % str(e))) # If that worked, write the remote file to the output kickstart # file in one burst. This allows multiple %ksappend lines to # exist. if contents is not None: retval += contents.encode(sys.getdefaultencoding()) return retval
def execute(self): args = [] firewall_proxy = NETWORK.get_proxy(FIREWALL) # If --use-system-defaults was passed then the user wants # whatever was provided by the rpms or ostree to be the # default, do nothing. if firewall_proxy.FirewallMode == FIREWALL_USE_SYSTEM_DEFAULTS: firewall_log.info("ks file instructs to use system defaults for " "firewall, skipping configuration.") return # enabled is None if neither --enable or --disable is passed # default to enabled if nothing has been set. if firewall_proxy.FirewallMode == FIREWALL_DISABLED: args += ["--disabled"] else: args += ["--enabled"] ssh_service_not_enabled = "ssh" not in firewall_proxy.EnabledServices ssh_service_not_disabled = "ssh" not in firewall_proxy.DisabledServices ssh_port_not_enabled = "22:tcp" not in firewall_proxy.EnabledPorts # always enable SSH unless the service is explicitely disabled if ssh_service_not_enabled and ssh_service_not_disabled and ssh_port_not_enabled: args += ["--service=ssh"] for dev in firewall_proxy.Trusts: args += ["--trust=%s" % (dev, )] for port in firewall_proxy.EnabledPorts: args += ["--port=%s" % (port, )] for remove_service in firewall_proxy.DisabledServices: args += ["--remove-service=%s" % (remove_service, )] for service in firewall_proxy.EnabledServices: args += ["--service=%s" % (service, )] cmd = "/usr/bin/firewall-offline-cmd" if not os.path.exists(util.getSysroot() + cmd): if firewall_proxy.FirewallMode == FIREWALL_ENABLED: msg = _("%s is missing. Cannot setup firewall.") % (cmd, ) raise KickstartError(msg) else: util.execInSysroot(cmd, args)
def runTest(self): # Yes, I am aware I'm just checking off boxes now. self.assertEqual(str(KickstartError("OH NO!")), "OH NO!") self.assertEqual(str(KickstartParseError("OH NO!")), "OH NO!") self.assertEqual(str(KickstartVersionError("OH NO!")), "OH NO!")
def _preprocessStateMachine(lineIter): l = None lineno = 0 # Now open an output kickstart file that we are going to write to one # line at a time. (outF, outName) = tempfile.mkstemp("-ks.cfg", "", "/tmp") while True: try: l = lineIter.next() except StopIteration: break # At the end of the file? if l == "": break lineno += 1 url = None ll = l.strip() if not ll.startswith("%ksappend"): os.write(outF, l) continue # Try to pull down the remote file. try: ksurl = ll.split(' ')[1] except: raise KickstartParseError( formatErrorMsg(lineno, msg=_("Illegal url for %%ksappend: %s") % ll)) try: url = grabber.urlopen(ksurl) except grabber.URLGrabError, e: raise KickstartError( formatErrorMsg(lineno, msg=_("Unable to open %%ksappend file: %s") % e.strerror)) else: # Sanity check result. Sometimes FTP doesn't catch a file # is missing. try: if url.size < 1: raise KickstartError( formatErrorMsg( lineno, msg=_("Unable to open %%ksappend file"))) except: raise KickstartError( formatErrorMsg(lineno, msg=_("Unable to open %%ksappend file"))) # If that worked, write the remote file to the output kickstart # file in one burst. Then close everything up to get ready to # read ahead in the input file. This allows multiple %ksappend # lines to exist. if url is not None: os.write(outF, url.read()) url.close()
def runTest(self): self.assertEqual(str(KickstartError("OH NO!")), "OH NO!") self.assertEqual(str(KickstartParseError("OH NO!")), "OH NO!") self.assertEqual(str(KickstartVersionError("OH NO!")), "OH NO!") err = KickstartError() self.assertEqual(err.message, "") self.assertEqual(err.lineno, None) self.assertEqual(err.value, "") self.assertEqual(str(err), "") err = KickstartError("OH NO!") self.assertEqual(err.message, "OH NO!") self.assertEqual(err.lineno, None) self.assertEqual(err.value, "OH NO!") self.assertEqual(str(err), "OH NO!") err = KickstartError(lineno=0) self.assertEqual(err.message, "") self.assertEqual(err.lineno, 0) self.assertEqual(err.value, _format_error_message(msg="", lineno=0)) self.assertEqual(str(err), _format_error_message(msg="", lineno=0)) err = KickstartError(lineno=1) self.assertEqual(err.message, "") self.assertEqual(err.lineno, 1) self.assertEqual(err.value, _format_error_message(msg="", lineno=1)) self.assertEqual(str(err), _format_error_message(msg="", lineno=1)) err = KickstartError("OH NO!", lineno=0) self.assertEqual(err.message, "OH NO!") self.assertEqual(err.lineno, 0) self.assertEqual(err.value, _format_error_message(msg="OH NO!", lineno=0)) self.assertEqual(str(err), _format_error_message(msg="OH NO!", lineno=0)) err = KickstartError("OH NO!", lineno=1) self.assertEqual(err.message, "OH NO!") self.assertEqual(err.lineno, 1) self.assertEqual(err.value, _format_error_message(msg="OH NO!", lineno=1)) self.assertEqual(str(err), _format_error_message(msg="OH NO!", lineno=1)) err = KickstartError("OH NO!", lineno=1, formatting=True) self.assertEqual(err.message, "OH NO!") self.assertEqual(err.lineno, 1) self.assertEqual(err.value, _format_error_message(msg="OH NO!", lineno=1)) self.assertEqual(str(err), _format_error_message(msg="OH NO!", lineno=1)) err = KickstartError("OH NO!", lineno=1, formatting=False) self.assertEqual(err.message, "OH NO!") self.assertEqual(err.lineno, 1) self.assertEqual(err.value, "OH NO!") self.assertEqual(str(err), "OH NO!") with self.assertWarns(DeprecationWarning): err = KickstartError(formatErrorMsg(lineno=0)) self.assertEqual(err.message, "") self.assertEqual(err.lineno, 0) self.assertEqual(err.value, _format_error_message(msg="", lineno=0)) self.assertEqual(str(err), _format_error_message(msg="", lineno=0)) with self.assertWarns(DeprecationWarning): err = KickstartError(formatErrorMsg(lineno=1)) self.assertEqual(err.message, "") self.assertEqual(err.lineno, 1) self.assertEqual(err.value, _format_error_message(msg="", lineno=1)) self.assertEqual(str(err), _format_error_message(msg="", lineno=1)) with self.assertWarns(DeprecationWarning): err = KickstartError(formatErrorMsg(msg="OH NO!", lineno=0)) self.assertEqual(err.message, "OH NO!") self.assertEqual(err.lineno, 0) self.assertEqual(err.value, _format_error_message(msg="OH NO!", lineno=0)) self.assertEqual(str(err), _format_error_message(msg="OH NO!", lineno=0)) with self.assertWarns(DeprecationWarning): err = KickstartError(formatErrorMsg(msg="OH NO!", lineno=1)) self.assertEqual(err.message, "OH NO!") self.assertEqual(err.lineno, 1) self.assertEqual(err.value, _format_error_message(msg="OH NO!", lineno=1)) self.assertEqual(str(err), _format_error_message(msg="OH NO!", lineno=1))
def parseKickstart(f, strict_mode=False, pass_to_boss=False): # preprocessing the kickstart file has already been handled in initramfs. addon_paths = collect_addon_paths(ADDON_PATHS) handler = AnacondaKSHandler(addon_paths["ks"]) ksparser = AnacondaKSParser(handler) kswarnings = [] ksmodule = "pykickstart" kscategories = (UserWarning, SyntaxWarning, DeprecationWarning) showwarning = warnings.showwarning def ksshowwarning(message, category, filename, lineno, file=None, line=None): # Print the warning with default function. showwarning(message, category, filename, lineno, file, line) # Collect pykickstart warnings. if ksmodule in filename and issubclass(category, kscategories): kswarnings.append(message) try: # Process warnings differently in this part. with warnings.catch_warnings(): # Set up the warnings module. warnings.showwarning = ksshowwarning for category in kscategories: warnings.filterwarnings(action="always", module=ksmodule, category=category) # Parse the kickstart file in DBus modules. if pass_to_boss: boss = BOSS.get_proxy() boss.SplitKickstart(f) errors = boss.DistributeKickstart() if errors: message = "\n\n".join("{error_message}".format_map(e) for e in errors) raise KickstartError(message) # Parse the kickstart file in anaconda. ksparser.readKickstart(f) # Process pykickstart warnings in the strict mode: if strict_mode and kswarnings: raise KickstartError( "Please modify your kickstart file to fix the warnings " "or remove the `ksstrict` option.") except (KickstartError, SplitKickstartError) as e: # We do not have an interface here yet, so we cannot use our error # handling callback. parsing_log.error(e) # Print kickstart warnings in the strict mode. if strict_mode and kswarnings: print( _("\nSome warnings occurred during reading the kickstart file:" )) for w in kswarnings: print(str(w).strip()) # Print an error and terminate. print( _("\nAn error occurred during reading the kickstart file:" "\n%s\n\nThe installer will now terminate.") % str(e).strip()) util.ipmi_report(IPMI_ABORTED) time.sleep(10) sys.exit(1) return handler