Projects
Eulaceura:Mainline
dnf-plugin-ovl
_service:obs_scm:dnf-plugin-ovl-1698672320.455c...
Sign Up
Log In
Username
Password
Overview
Repositories
Revisions
Requests
Users
Attributes
Meta
File _service:obs_scm:dnf-plugin-ovl-1698672320.455ce02.obscpio of Package dnf-plugin-ovl
07070100000000000081A4000000000000000000000001653FAEC000000370000000000000000000000000000000000000002F00000000dnf-plugin-ovl-1698672320.455ce02/README.en.md# dnf-plugin-ovl #### Description Workaround to run dnf on overlayfs. A port of yum-plugin-ovl to dnf. #### Software Architecture Software architecture description #### Installation 1. xxxx 2. xxxx 3. xxxx #### Instructions 1. xxxx 2. xxxx 3. xxxx #### Contribution 1. Fork the repository 2. Create Feat_xxx branch 3. Commit your code 4. Create Pull Request #### Gitee Feature 1. You can use Readme\_XXX.md to support different languages, such as Readme\_en.md, Readme\_zh.md 2. Gitee blog [blog.gitee.com](https://blog.gitee.com) 3. Explore open source project [https://gitee.com/explore](https://gitee.com/explore) 4. The most valuable open source project [GVP](https://gitee.com/gvp) 5. The manual of Gitee [https://gitee.com/help](https://gitee.com/help) 6. The most popular members [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/) 07070100000001000081A4000000000000000000000001653FAEC0000003C9000000000000000000000000000000000000002C00000000dnf-plugin-ovl-1698672320.455ce02/README.md# dnf-plugin-ovl #### 介绍 Workaround to run dnf on overlayfs. A port of yum-plugin-ovl to dnf. #### 软件架构 软件架构说明 #### 安装教程 1. xxxx 2. xxxx 3. xxxx #### 使用说明 1. xxxx 2. xxxx 3. xxxx #### 参与贡献 1. Fork 本仓库 2. 新建 Feat_xxx 分支 3. 提交代码 4. 新建 Pull Request #### 特技 1. 使用 Readme\_XXX.md 来支持不同的语言,例如 Readme\_en.md, Readme\_zh.md 2. Gitee 官方博客 [blog.gitee.com](https://blog.gitee.com) 3. 你可以 [https://gitee.com/explore](https://gitee.com/explore) 这个地址来了解 Gitee 上的优秀开源项目 4. [GVP](https://gitee.com/gvp) 全称是 Gitee 最有价值开源项目,是综合评定出的优秀开源项目 5. Gitee 官方提供的使用手册 [https://gitee.com/help](https://gitee.com/help) 6. Gitee 封面人物是一档用来展示 Gitee 会员风采的栏目 [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/) 07070100000002000041ED000000000000000000000003653FAEC000000000000000000000000000000000000000000000002A00000000dnf-plugin-ovl-1698672320.455ce02/drv-img07070100000003000081A4000000000000000000000001653FAEC0000046AC000000000000000000000000000000000000003200000000dnf-plugin-ovl-1698672320.455ce02/drv-img/LICENSE GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. <signature of Ty Coon>, 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. 07070100000004000081A4000000000000000000000001653FAEC000000021000000000000000000000000000000000000003600000000dnf-plugin-ovl-1698672320.455ce02/drv-img/MANIFEST.ininclude LICENSE include README.md07070100000005000081A4000000000000000000000001653FAEC000000A82000000000000000000000000000000000000003400000000dnf-plugin-ovl-1698672320.455ce02/drv-img/README.md# drv-img ## Description A simple program to inject a driver and package into a Linux iso image. drv-img is a utility program that enables users to inject a driver and package into a Linux ISO image. It may be used in several contexts, such as when building custom Linux distros, provisioning new diver which is not provided in published iso, or injecting patch updates into a previously built image. ## Usage The primary use case of drv-img is to inject a driver into a Linux ISO file. You can do this using the command line interface. ``` usage: drv-img [-h] --iso ISO [--rpm-path RPM_PATH] [--ko-path KO_PATH] --work-dir WORK_DIR --output OUTPUT [-v] Inject driver to Linux ISO optional arguments: -h, --help show this help message and exit --iso ISO ISO file used to rebuild --rpm-path RPM_PATH Directory for RPM path --ko-path KO_PATH Directory for kernel module path --work-dir WORK_DIR Directory for ISO rebuild. It must have enough space to uncompress the whole ISO file --output OUTPUT Directory for rebuilt ISO. It must have enough space to store the whole ISO file -v, --version show program's version number and exit ``` ## Options Details - -h, --help: Shows the help message and exit - --iso ISO (Must): The ISO file on which the operations will be performed. This involves specifying the path to the ISO file which the user wants to modify. - --rpm-path RPM_PATH: The path to the directory where the RPM (RPM Package Manager) files are stored. These files are typically used for installing, upgrading, and removing software on Linux. - --ko-path KO_PATH: The path to the directory containing the Linux kernel module (*.ko) files. These modules are code that can be loaded and unloaded into the kernel upon demand. They extend the functionality of the kernel without needing to reboot the system. - --work-dir WORK_DIR (Must): Specify the working directory where the ISO file will be rebuilt. It's important to note that this directory should have enough space to uncompress the entire ISO file. - --output OUTPUT (Must): The location where the rebuilt ISO will be saved. This directory must have sufficient space to store the whole ISO file after it's rebuilt. ## Example To inject a driver into an ISO file, you might use a command like this: ``` drv-img --iso /path/to/your.iso --rpm-path /path/to/rpms --ko-path /path/to/modules --work-dir /path/to/workdir --output /path/to/output ``` ## Authors * [**BINSHUO ZU**](binshuozu@gmail.com) ## License This project is licensed under the GPL License - see the [LICENSE](LICENSE) file for details 07070100000006000041ED000000000000000000000007653FAEC000000000000000000000000000000000000000000000003200000000dnf-plugin-ovl-1698672320.455ce02/drv-img/drv_img07070100000007000081A4000000000000000000000001653FAEC0000000B5000000000000000000000000000000000000003E00000000dnf-plugin-ovl-1698672320.455ce02/drv-img/drv_img/__init__.py"""drv-img: a tool to add package and driver to iso image""" __cli_name__ = 'drv-img' __version__ = '0.1.0' __date__ = '2023-09-07' __author__ = 'BINSHUO ZU' __license__ = 'GPLv2' 07070100000008000041ED000000000000000000000002653FAEC000000000000000000000000000000000000000000000003700000000dnf-plugin-ovl-1698672320.455ce02/drv-img/drv_img/core07070100000009000081A4000000000000000000000001653FAEC000000000000000000000000000000000000000000000004300000000dnf-plugin-ovl-1698672320.455ce02/drv-img/drv_img/core/__init__.py0707010000000A000081A4000000000000000000000001653FAEC000000452000000000000000000000000000000000000004800000000dnf-plugin-ovl-1698672320.455ce02/drv-img/drv_img/core/global_config.py"""This is file is used to store global settings for the application.""" from drv_img.core.oetype import ArchType class GlobalConfig(object): """ Storage container for global settings for the application. Fields: ARCH: A constant indicating the architecture type. PRODUCT_NAME: The name of the product. VERSION_INFO: Version information about the product. VERSION_ID: The ID of the version. BASE_ISO_VERSION: The base ISO version for the product. CACHED_PATH: The path for cached files. WORK_DIR: The directory for performing assembly operations. OUTPUT: The final output directory. ISO: The ISO file to be used. RPM_PATH: The path to the RPM files. KERNEL_MODULES_PATH: The path to the kernel modules. """ ARCH = ArchType.X86_64 PRODUCT_NAME = "openEuler" VERSION_INFO = "20.03-LTS" VERSION_ID = "20.03" BASE_ISO_VERSION = "20.03-LTS-SP1" CACHED_PATH = "/root/cache" WORK_DIR = "/root/isotemp" OUTPUT = "/root/res/xxx.iso" # ediso ISO = "/root/xxx.iso" RPM_PATH = "" KERNEL_MODULES_PATH = "" 0707010000000B000081A4000000000000000000000001653FAEC000000128000000000000000000000000000000000000004100000000dnf-plugin-ovl-1698672320.455ce02/drv-img/drv_img/core/oetype.py"""This module contains definitions related to architecture types.""" from enum import Enum class ArchType(Enum): """ Enumeration of architecture types. This class represents different architecture types like x86_64 and ARM64. """ X86_64 = 'x86_64' ARM64 = 'aarch64' 0707010000000C000041ED000000000000000000000002653FAEC000000000000000000000000000000000000000000000003C00000000dnf-plugin-ovl-1698672320.455ce02/drv-img/drv_img/kickstart0707010000000D000081A4000000000000000000000001653FAEC000000000000000000000000000000000000000000000004800000000dnf-plugin-ovl-1698672320.455ce02/drv-img/drv_img/kickstart/__init__.py0707010000000E000081A4000000000000000000000001653FAEC00000173F000000000000000000000000000000000000005100000000dnf-plugin-ovl-1698672320.455ce02/drv-img/drv_img/kickstart/kickstart_manager.py"""This module is used to modify kickstart file""" import os from pykickstart.version import makeVersion from pykickstart.parser import KickstartParser, Script from pykickstart.constants import KS_SCRIPT_POST, KS_SCRIPT_PRE from drv_img.utils import run_cmd from drv_img.core.global_config import GlobalConfig KS_PATH = "/usr/share/anaconda/interactive-defaults.ks" MOVE_PATH = "/_tmp" INS_SHELL_SCRIPT = """\ # The content of this script is generated by drv-img #!/bin/bash set -x RPM_PATH={} for i in $(find $RPM_PATH -name "*.rpm"); do if command -v rpm >/dev/null 2>&1; then rpm -i $i --nodeps --force else dnf install $i --releasever {} -y fi done KO_PATH={} for i in $(find $KO_PATH -name "*.ko"); do if command -v rpm >/dev/null 2>&1; then mv $i /lib/modules/`uname -r`/updates/ fi modprobe -a /lib/modules/`uname -r`/updates/$(basename $i .ko) -f done depmod -a """ class KickManager: """ The KickManager class is responsible for managing the kickstart process. Attributes: _install_path (str): The path to the installation image. _rpm_list (list): A list of RPMs to be installed. _ko_list (list): A list of kernel objects to be installed. Methods: modify_kickstart(kck_file, output_file): Modifies the kickstart file. move_driver(): Moves the driver files to a temporary directory for future use. """ def __init__(self, install_img_path, rpm_list, ko_list): self._install_path = install_img_path self._rpm_list = rpm_list self._ko_list = ko_list def modify_kickstart(self, kck_file, output_file): """ Modifies the kickstart file. This method reads a kickstart file, processes its sections, and writes the modified content to an output file. Args: kck_file (str): The path to the kickstart file to be modified. output_file (str): The path to the output file where the modified kickstart content will be written. Returns: None """ ks_content = self._read_kickstart_file(kck_file) ks_parser = KickstartParser(makeVersion()) ks_parser.readKickstartFromString(ks_content) self._process_file_sections(ks_parser) self._write_to_output_file(output_file, ks_parser.handler) def _process_file_sections(self, ks_parser): self._add_pre_section(ks_parser) self._add_post_section(ks_parser) def _add_pre_section(self, ks_parser): content = INS_SHELL_SCRIPT.format(MOVE_PATH, GlobalConfig.VERSION_ID, MOVE_PATH) self._add_script_to_section(ks_parser, content, in_chroot=False, script_type=KS_SCRIPT_PRE) def _add_post_section(self, ks_parser): content = f"# The content of this script is generated by drv-img\n"\ f"mv {MOVE_PATH} /mnt/sysimage{MOVE_PATH}" self._add_script_to_section(ks_parser, content, in_chroot=False, script_type=KS_SCRIPT_POST) chroot_content = INS_SHELL_SCRIPT.format(MOVE_PATH, GlobalConfig.VERSION_ID, MOVE_PATH) chroot_content += f"rm -rf {MOVE_PATH}" self._add_script_to_section(ks_parser, chroot_content, in_chroot=True, script_type=KS_SCRIPT_POST) def move_driver(self): """ Moves the driver files to a temporary directory for future use. This method creates a temporary directory in the installation path and copies the kernel objects and RPMs to this directory. """ # copy kernel_module and rpm to tmp dir for future ks usage tmp_path = self._install_path + MOVE_PATH run_cmd.mkdir_chain(tmp_path) for kernel_module in self._ko_list: run_cmd.cp_file(kernel_module, tmp_path) for rpm in self._rpm_list: run_cmd.cp_file(rpm, tmp_path) def _add_script_to_section(self, ks_parser, content, in_chroot, lineno=0, interpreter='/bin/bash', script_type=KS_SCRIPT_POST): """Adds a script to kickstart parser""" new_script = Script(content, interp=interpreter, inChroot=in_chroot, lineno=lineno, type=script_type) ks_parser.handler.scripts.append(new_script) def _read_kickstart_file(self, kck_file): """Reads and returns content of a kickstart file""" if not os.path.exists(kck_file): print(f"Kickstart file not found: {kck_file} try to create it") os.mknod(kck_file) with open(kck_file, 'r', encoding='utf-8') as kickstart_file: return kickstart_file.read() def _write_to_output_file(self, output_file, handler): """Writes to output file""" try: with open(output_file, 'w', encoding='utf-8') as file: file.write(str(handler)) except IOError: print(f"Error writing to output file: {output_file}") with open(output_file, 'r+', encoding='utf-8') as file: contents = file.readlines() file.seek(0) for line in contents: if not line.startswith('bootloader'): file.write(line) file.truncate() 0707010000000F000041ED000000000000000000000002653FAEC000000000000000000000000000000000000000000000003500000000dnf-plugin-ovl-1698672320.455ce02/drv-img/drv_img/ko07070100000010000081A4000000000000000000000001653FAEC000000000000000000000000000000000000000000000004100000000dnf-plugin-ovl-1698672320.455ce02/drv-img/drv_img/ko/__init__.py07070100000011000081A4000000000000000000000001653FAEC000000F04000000000000000000000000000000000000004300000000dnf-plugin-ovl-1698672320.455ce02/drv-img/drv_img/ko/ko_manager.py"""This module provides the class to manage and handle kernel objects (ko).""" import os from drv_img.utils.logger import logger from drv_img.utils import run_cmd class KOManager: """ Class to manage and handle kernel objects (ko). The class can check the compatibility of the kernel objects with current kernel version and manage their installation. """ def __init__(self, work_dir, ko_list): """Initialize with working directory and list of kernel objects.""" self._work_dir = work_dir self._ko_list = ko_list self._kernel_version = self.get_kernel_version(work_dir) def _process_version_string(self, raw_version): """Process kernel version string to get the necessary version.""" if raw_version is None: return None return '.'.join(raw_version.strip().split(' ')[0].split('.')) def get_kernel_version(self, root_dir): """Get the version of the kernel from the given root directory.""" current_kernel_raw = run_cmd.get_kernel_version_with_chroot(root_dir) print("current_kernel_raw: ", current_kernel_raw) return self._process_version_string(current_kernel_raw) def get_module_vermagic(self, module_path): """ Get the version magic of the module. Version magic is a string associated with each module that contains information about the kernel version and configuration for which the module is valid. """ module_compatibility_raw = run_cmd.get_module_vermagic(module_path) print( f"module_path: {module_path}, module_compatibility_raw: {module_compatibility_raw}" ) return self._process_version_string(module_compatibility_raw) def check_compatibility(self, module_path): """Check if the kernel module is compatible with the current kernel version.""" module_compatibility = self.get_module_vermagic(module_path) if module_compatibility is None: return False if module_compatibility == self._kernel_version: return True logger.warning("module %s is not exactly compatible with kernel %s", module_path, self._kernel_version) print( f"module {module_path} is not exactly compatible with kernel {self._kernel_version}" ) return module_compatibility.split( '.')[:2] == self._kernel_version.split('.')[:2] def check_can_install(self): """Check which kernel objects in the list can be installed.""" return [ ko for ko in self._ko_list if self.check_compatibility(ko) is True ] def install_ko(self, kernel_module): """Install the kernel module to target directory if it's compatible.""" if not self.check_compatibility(kernel_module): return False destination = f"{self._work_dir}/lib/modules/{self._kernel_version}/updates/" run_cmd.cp_file(kernel_module, destination) run_cmd.depmod(self._work_dir, self._kernel_version) ko_base = os.path.basename(kernel_module).split('.')[0] run_cmd.modprobe(self._kernel_version, self._work_dir, ko_base) return True def install_all_ko(self): """Install all compatible kernel objects in the list.""" to_install = self.check_can_install() for kernel_module in to_install: print(f"Installing {kernel_module} to {self._work_dir}") if not self.install_ko(kernel_module): logger.error("Install ko package %s to %s failed!", kernel_module, self._work_dir) raise ValueError( f"Install ko package {kernel_module} to {self._work_dir} failed!" ) return True 07070100000012000081A4000000000000000000000001653FAEC000003287000000000000000000000000000000000000004100000000dnf-plugin-ovl-1698672320.455ce02/drv-img/drv_img/rebuild_iso.py"""This module is used to rebuild iso with driver.""" import os import sys from tempfile import TemporaryDirectory from drv_img.kickstart.kickstart_manager import KickManager, KS_PATH from drv_img.ko.ko_manager import KOManager from drv_img.rpm.rpm_manager import RpmManager from drv_img.utils.logger import logger from drv_img.utils import run_cmd from drv_img.core.oetype import ArchType from drv_img.core.global_config import GlobalConfig class RebuildISOWithDriver: """Replace the packages/kernel modules in the given ISO and rebuild the ISO.""" def __init__(self, iso: str, rpm_path: str, ko_path: str, work_dir: str, output: str, arch: ArchType, mount_point="/root/tmp"): self._iso = iso self._rpm_path = rpm_path self._ko_path = ko_path self._work_dir = work_dir self._output = output self._arch = arch self._mount_point = mount_point self._to_install_rpm = [] self._to_install_ko = [] self._product_name = "" def do_iso_rebuild(self): """ Main function to do ISO rebuild. :return: None """ self.mount_and_cp() self.read_product_name() self.inject_driver() self.create_repo_group() self.make_iso() self.implant_iso_md5() def mount_and_cp(self): """ This method mounts an ISO file and copies all its contents to a specified directory. If any of the steps fail, an error message is logged and printed, and the program exits. :raises OSError: If there is an error during the execution of any of the steps. """ print("We are mounting iso, and copy all files, please wait...", ) logger.info("begin mount iso and copy files") iso_mount_path = os.path.join(self._mount_point, "iso_") try: with TemporaryDirectory(prefix=iso_mount_path, dir=self._mount_point) as iso_dir: if run_cmd.mount(self._iso, iso_dir, "iso9660", "loop"): error_message = f"Failed to mount {self._iso} to {iso_dir}" logger.error(error_message) print(error_message) sys.exit(0) logger.info("ISO mounted on dir: %s", iso_dir) if run_cmd.cp_iso_file(iso_dir, self._work_dir): error_message = "Failed to cp iso file from {iso_dir} to {self._work_dir}" logger.error(error_message) print(error_message) sys.exit(0) logger.info("CP all iso files successfully!") if run_cmd.umount(iso_dir): error_message = f"Failed to umount dir {iso_dir}" logger.error(error_message) print(error_message) sys.exit(0) logger.info("umount iso successfully") logger.info("Mount iso and copy file successfully!") except OSError as err: logger.error(err) print(err) sys.exit(0) def replace_install_img(self): """ This method replaces the install image in a specified directory with a new one. If any of the steps fail, an error message is logged and printed, and the program exits. :raises OSError: If there is an error during the execution of any of the steps. """ # unsquashfs install_img_path = self._work_dir + "/images/install.img" install_mount_path = os.path.join(self._mount_point, "install_") squashfs_path = self._work_dir + "/images/squashfs-root" rootfs_path = squashfs_path + "/LiveOS/rootfs.img" if run_cmd.unsquashfs(install_img_path, squashfs_path) != 0: error_message = f"Unsquashfs image Failed! image path: {install_img_path}" logger.error(error_message) print(error_message) sys.exit(0) logger.info("Unsquashfs successfully!") # mount with TemporaryDirectory(prefix=install_mount_path, dir=self._mount_point) as install_dir: if run_cmd.mount(rootfs_path, install_dir, "ext4", "rw") != 0: logger.error("Failed to mount %s to %s", rootfs_path, install_dir) sys.exit(0) logger.info("install.img mounted on dir %s", install_dir) # install rpm package if self._rpm_path: print("We are installing rpm package, please wait...") self.check_rpm_dependence(install_dir) for rpm_pkgs in self._to_install_rpm: if run_cmd.rpm_setup(rpm_pkgs, install_dir) != 0: logger.error("Set up rpm package %s to %s failed!", rpm_pkgs, install_dir) sys.exit(0) print(f"Set up rpm package {rpm_pkgs} successfully!") logger.info("Set up rpm package %s successfully!", rpm_pkgs) # install kernel module if self._ko_path: print("We are installing ko package, please wait...") self._to_install_ko = self.load_ko_list() ko_manager = KOManager(install_dir, self._to_install_ko) if ko_manager.install_all_ko(): logger.info("Install ko package successfully!") else: logger.error("Install ko package failed!") sys.exit(0) print("Modify kickstart file, please wait...") kickstart_manager = KickManager(install_dir, self._to_install_rpm, self._to_install_ko) kickstart_manager.move_driver() kickstart_manager.modify_kickstart(install_dir + KS_PATH, install_dir + KS_PATH) # umount + squashfs if run_cmd.umount(install_dir) != 0: logger.error("Umount %s Failed!", install_dir) sys.exit(0) if run_cmd.mksquashfs(squashfs_path, install_img_path) != 0: logger.error("mksquashfs %s Failed!", squashfs_path) sys.exit(0) # delete if run_cmd.remove_file(squashfs_path) != 0: logger.error("Remove file %s failed!", squashfs_path) sys.exit(0) def read_product_name(self): """ This method reads the product name and version from a .treeinfo file. :raises IOError: If there is an error opening or reading the .treeinfo file. """ tree_info_file = os.path.join(self._work_dir, ".treeinfo") with open(tree_info_file, encoding='utf-8') as tree_info: for content in tree_info: if content.startswith("name"): self._product_name = content.split("=")[1].strip() logger.info("product name is %s", self._product_name) if content.startswith("version"): GlobalConfig.VERSION_ID = content.split("=")[1].strip() def create_repo_group(self): """ This method creates a repository group in the working directory. :raises SystemExit: If there is an error during the execution of the `createrepo_group` function. """ if run_cmd.createrepo_group(self._work_dir) != 0: logger.error("Failed to createrepo for dir: %s", self._work_dir) sys.exit(0) logger.info("createrepo for new iso successfully!") def make_iso(self): """ This method creates an ISO file from the contents of the working directory. :raises SystemExit: If there is an error during the execution of the `mkisofs` function or if the product name is not available. """ if self._product_name == "": logger.error("failed to get product name!") print("failed to get product name! has .treeinfo in iso?") sys.exit(0) vid = self._product_name + "-" + self._arch.value if run_cmd.mkisofs(self._work_dir, self._output, self._arch, vid) != 0: logger.error("Failed to rebuild iso") sys.exit(0) logger.info("ISO rebuild successfully, please check: %s", self._output) def replace_repo(self): """ This method replaces the repository in the working directory with a new one. :raises SystemExit: If there is an error during the execution of the `cp_file` function. """ new_repo_path = self._work_dir + "/Packages" for root, _, files in os.walk(self._rpm_path): for file in files: src_file = os.path.join(root, file) if src_file.endswith(".rpm") is False: continue dest_file = os.path.join(new_repo_path, file) if run_cmd.cp_file(src_file, dest_file) != 0: logger.error("Copy file %s to %s Failed", src_file, dest_file) sys.exit(0) def inject_driver(self): """ This method injects drivers into the working directory. The method performs the following steps: 1. Logs and prints a message indicating the start of the driver injection process. 2. Calls the `replace_install_img` method to replace the install image in the working directory. 3. Calls the `replace_repo` method to replace the repository in the working directory. 4. Logs a success message indicating the successful completion of driver injection. :raises SystemExit: If there is an error during the execution of the `replace_install_img` or `replace_repo` methods. """ logger.info("begin inject drivers") print("begin inject drivers, please wait...") self.replace_install_img() self.replace_repo() logger.info("Replace drivers for new iso successfully!") def implant_iso_md5(self): """ This method implants the ISO MD5 hash into the output. It first calls the `implant_iso_md5` method from the `run_cmd` module on the instance's output attribute. If the method call is unsuccessful, it logs an error message and exits the program. If the method call is successful, it logs a success message. Raises: SystemExit: If the `implant_iso_md5` method from the `run_cmd` module fails. """ if run_cmd.implant_iso_md5(self._output) != 0: logger.error("Implant iso md5 Failed!") sys.exit(0) logger.info("implant iso md5 successfully!") def check_rpm_dependence(self, install_dir): """ This method checks the RPM dependencies for a given installation directory. It first creates an instance of the `RpmManager` with the provided installation directory. Then it checks if the RPM packages can be installed by calling the `can_install` method on the `RpmManager` instance with the loaded RPM list. The method also logs information about each RPM package that will be installed. Args: install_dir (str): The directory where the RPM packages are to be installed. Returns: bool: True if the RPM packages can be installed, False otherwise. """ rpm_manager = RpmManager(install_dir) installable, _ = rpm_manager.can_install(self.load_rpm_list()) self._to_install_rpm = [rpm[0] for rpm in installable] for rpm_pkg in installable: logger.info("rpm package %s will be installed", rpm_pkg) return installable is not None def load_rpm_list(self): """ This method loads the list of RPM files from the RPM path. Returns: list: A list of paths to all the RPM files in the RPM path. """ rpm_list = [] for filename in os.listdir(self._rpm_path): if filename.endswith(".rpm"): rpm_list.append(os.path.join(self._rpm_path, filename)) return rpm_list def load_ko_list(self): """ This method loads the list of KO files from the KO path. Returns: list: A list of paths to all the KO files in the KO path. """ ko_list = [] for filename in os.listdir(self._ko_path): if filename.endswith(".ko"): ko_list.append(os.path.join(self._ko_path, filename)) return ko_list 07070100000013000041ED000000000000000000000002653FAEC000000000000000000000000000000000000000000000003600000000dnf-plugin-ovl-1698672320.455ce02/drv-img/drv_img/rpm07070100000014000081A4000000000000000000000001653FAEC000000000000000000000000000000000000000000000004200000000dnf-plugin-ovl-1698672320.455ce02/drv-img/drv_img/rpm/__init__.py07070100000015000081A4000000000000000000000001653FAEC000003200000000000000000000000000000000000000004500000000dnf-plugin-ovl-1698672320.455ce02/drv-img/drv_img/rpm/rpm_manager.py""" This module is designed to handle RPM (Red Hat Package Manager) file operations mainly to manage dependencies, comparing versions and checking for installation requirements. """ import re import collections from packaging import version import rpm as lib_rpm from drv_img.utils import run_cmd from drv_img.utils.logger import logger class RpmManager: """ The class is designed to handle RPM (Red Hat Package Manager) file operations mainly to manage dependencies, comparing versions and checking for installation requirements. Attributes: ----------- installed_packages {list } -- A list of packages already installed. operators {list} -- Operators used in version comparison operations. Methods: ----------- get_installed_packages_from_file(file_path) Returns the installed packages retrieving from the file path. get_rpm_package(provides_input) Returns the rpm package by querying against the provided input. get_rpm_dependencies(rpm_package) Returns dependencies of the given rpm package. compare_versions(installed_version, operator, requirement_version) Compares installed version against the requirement version using the provided operator. is_satisfied(name, operator, _version) Checks if the given package name can be installed with the specified version. can_install(rpm_list) Returns a tuple with list of packages that can be installed and cannot be installed. """ def __init__(self, work_dir, file_path="/root/lorax-packages.log"): self.installed_packages = self.get_installed_packages_from_file( work_dir + file_path) self.operators = ['>=', '<=', '>', '<', '==', '='] def _parse_package_info_from_line(self, line): match = re.match(r'(.+)-([^-]+)-(.+)\.((x86_64)|(noarch)|(aarch64))', line.strip()) if match: name, rpm_version, release, arch, _, _, _ = match.groups() return { 'name': name, 'version': rpm_version, "release": release, 'arch': arch, } return None def _parse_packages(self, lines): """ Extract package information from a list of lines. Parameters: lines (list): A list of string lines from which package information is to be extracted. Returns: list: A list of dictionaries each containing the package name, version, release, and arch. """ packages = [] for line in lines: pkg_info = self._parse_package_info_from_line(line) if pkg_info is not None: packages.append(pkg_info) return packages def get_installed_packages_from_file(self, file_path): """ Retrieve installed packages information from a given file. Parameters: file_path (str): Path to the file from which installed packages information is to be read. Returns: list: A list of dictionaries each containing the installed package name, version, release, and architecture information. """ with open(file_path, 'r', encoding='utf-8') as file: lines = file.readlines() return self._parse_packages(lines) def get_rpm_package(self, provides_input): """ Retrieves rpm package information for a provided input. Parameters: provides_input (str): The input provided to query rpm. Returns: list or None: A list of dictionaries each containing rpm package information if found; Otherwise, None. """ output = run_cmd.rpm_query_provides(provides_input) if output is None: return None lines = output.strip().split('\n') return self._parse_packages(lines) def _search_operator_version(self, line): """ Searches for an operator and version from a given line string. Parameters: line (str): The line string from which operator and version is to be identified. Returns: tuple: A tuple containing three elements (name, operator, version) where 'name' is the string before the operator, 'operator' is the operator found, and 'version' is the string after the operator. If no operator is found, the operator and version will be None. """ for operator_symbol in self.operators: if operator_symbol in line: splitted = line.split(operator_symbol) return splitted[0].strip(), operator_symbol, splitted[1].strip( ) return line.strip(), None, None def _is_special_dependency(self, dependency_name): """ Checks if a given dependency name is a special dependency. Parameters: dependency_name (str): The name of the dependency to check. Returns: bool: True if the dependency name is a special dependency; Otherwise, False. """ return dependency_name.startswith( "rpmlib(") or dependency_name.startswith("config(") def get_rpm_dependencies(self, rpm_package): """ Retrieve rpm dependencies for a given rpm package. Parameters: rpm_package (str): The name of the rpm package for which dependencies are to be retrieved. Returns: dict or None: A dictionary containing the dependencies of the package, if found; Otherwise, None. """ dependencies_result = collections.defaultdict(list) # TODO: change it to a better way as it depends on host machine's database output = run_cmd.rpm_check_dependency(rpm_package) if output is None: return None dependency_lines = output.split('\n') for line in dependency_lines: if line: # ignore empty lines if line.startswith('/'): # ignore lines starting with a '/' continue dependency_name, operator, dependency_version = self._search_operator_version( line) # ignore special dependencies if self._is_special_dependency(dependency_name): continue packages = self.get_rpm_package(dependency_name) if packages is None: # if there is an error in getting the package return None for package in packages: dependencies_result[package["name"]].append({ "dependency_name": package["name"], "operator": operator, "version": dependency_version }) logger.info("Package %s has dependencies: %s", rpm_package, dependencies_result) return dependencies_result def compare_versions(self, installed_version, operator, requirement_version): """ Compare the installed_version against the requirement_version using operator. :param installed_version: the version string of the installed package :param operator: a string, one of "==", ">=", "<=", "<", ">" :param requirement_version: the version string of the required package :return: True if the requirement is satisfied, False otherwise """ installed_version = version.parse(installed_version) requirement_version = version.parse(requirement_version) if operator == '>=': return installed_version >= requirement_version elif operator == '<=': return installed_version <= requirement_version elif operator == '==': return installed_version == requirement_version elif operator == '>': return installed_version > requirement_version elif operator == '<': return installed_version < requirement_version else: raise ValueError("Unsupported operator: " + operator) def is_satisfied(self, name, operator, _version): """ Checks if the given package name can meet the version requirement. If there is no version requirement (operator is None), returns True. Otherwise, checks if any installed package with the given name can satisfy the version requirement. Parameters: name {str} -- Name of the package. operator {str} -- Operator used for version comparison. It can be '>=', '<=', '>', '<', '==' or None. _version {str} -- Version requirement for the package. Returns: {bool} -- Returns True if there is no version requirement or if any installed package with the given name can meet the version requirement. Otherwise, returns False. """ if operator is None: # if there is no version requirement, return True return True for installed_pack in self.installed_packages: if installed_pack['name'] == name: result = self.compare_versions(installed_pack['version'], operator, _version) if result: return True return False def can_install(self, rpm_list): """ Function checks if provided RPM files can be installed. It trying to resolve unsatisfied dependencies. Returns tuple with list of installable RPMs and list of RPMs that cannot be installed with their unsatisfied dependencies. """ def get_rpm_info(rpm_path): """Helper function to extract information from a RPM file""" ts = lib_rpm.TransactionSet() with open(rpm_path, 'rb') as rpm_file: try: hdr = ts.hdrFromFdno(rpm_file) return { 'name': hdr[lib_rpm.RPMTAG_NAME], 'version': hdr[lib_rpm.RPMTAG_VERSION], 'release': hdr[lib_rpm.RPMTAG_RELEASE], 'arch': hdr[lib_rpm.RPMTAG_ARCH], } except lib_rpm.error as e: print(f"Error reading RPM header: {e}") def is_dependency_satisfied(dependency, installed_rpms): """Helper function to check if dependency condition is satisfied with currently installed RPMs""" dep_name, operator, version = dependency.split() return any( self.compare_versions(rpm['version'], operator, version ) if dep_name == rpm['name'] else False for rpm in installed_rpms) def check_unsatisfied_dependencies(rpm_dependencies): """Helper function to check for unsatisfied dependencies in a given dictionary of RPM dependencies""" unsatisfied_deps = [] for pkg, dependencies in rpm_dependencies.items(): for dependency in dependencies: if not self.is_satisfied(pkg, dependency['operator'], dependency['version']): unsatisfied_deps.append(dependency) return unsatisfied_deps to_install = [] cannot_install = [] # Loop through all provided RPMs in the RPM list for rpm in rpm_list: rpm_dependencies = self.get_rpm_dependencies(rpm) if rpm_dependencies is None: cannot_install.append((rpm, ['Error in getting dependencies'])) continue # Check for unsatisfied dependencies unsatisfied_deps = check_unsatisfied_dependencies(rpm_dependencies) (cannot_install if unsatisfied_deps else to_install).append( (rpm, unsatisfied_deps)) # Get information for all installable RPMs installed_rpms = [get_rpm_info(rpm) for rpm, _ in to_install] for rpm, dependencies in cannot_install.copy(): if dependencies == ['Error in getting dependencies']: continue for dependency in dependencies.copy(): if is_dependency_satisfied(dependency, installed_rpms): dependencies.remove(dependency) if not dependencies: cannot_install.remove((rpm, dependencies)) to_install.append((rpm, dependencies)) # Final return with RPMs that can be installed and those that cannot return to_install, cannot_install 07070100000016000081ED000000000000000000000001653FAEC00000211D000000000000000000000000000000000000003900000000dnf-plugin-ovl-1698672320.455ce02/drv-img/drv_img/run.py"""The main entry point for the drv-img tool.""" #!/bin/python import argparse import pathlib import sys import os import shutil import time from argparse import RawTextHelpFormatter from drv_img.utils.run_cmd import get_os_arch from drv_img.core.global_config import GlobalConfig from drv_img.utils.logger import logger from drv_img.rebuild_iso import RebuildISOWithDriver import drv_img def init_config(parser: argparse.ArgumentParser): """ Initialize the global configuration. Parameters: parser (argparse.ArgumentParser): The parser containing configuration data. """ arch = get_os_arch() if not arch: sys.exit(1) GlobalConfig.ARCH = arch get_config_parser(parser) def check_exist_outdir(): """ Check if the output directory exists. Asserts the location ends in '.iso' and that the directory it would be placed in exists, creating it if not. """ if not GlobalConfig.OUTPUT.endswith("iso"): logger.error("Please define the --output like /xxx/xxx/xxx.iso") sys.exit(0) dirname = os.path.dirname(os.path.abspath(GlobalConfig.OUTPUT)) if not os.path.exists(dirname): os.makedirs(dirname) def check_exist_workdir(): """ Check if the work directory exists. Asserts the existence of the work directory, and if it doesn't exist, creates it. If the path exists but is not a directory, it logs an error and exits the program. """ work_dir = os.path.abspath(GlobalConfig.WORK_DIR) if not os.path.exists(work_dir): os.makedirs(work_dir) if not os.path.isdir(work_dir): logger.error("Work path is not a directory. Path: %s", work_dir) sys.exit(0) def check_exist_ko(): """ Check if the kernel modules exist. Asserts the existence of the directory for kernel module files (.ko files). Creates it if it doesn't exist. If the path exists but is not a directory, or if no .ko files are found in the directory, logs an error and exits the program. """ ko_path = os.path.abspath(GlobalConfig.KERNEL_MODULES_PATH) if not os.path.exists(ko_path): os.makedirs(ko_path) if not os.path.isdir(ko_path): logger.error( "Kernel modules path exists, but is not a directory! Path: %s", GlobalConfig.KERNEL_MODULES_PATH) sys.exit(0) # check if there is any .ko file in the directory if not any(fname.endswith('.ko') for fname in os.listdir(ko_path)): logger.error("Cannot find any .ko file in the directory: %s", ko_path) sys.exit(0) def check_exist_rpm(): """ Check if the RPMs exist. Asserts the existence of the directory for RPM files. If it doesn't exist, creates it. If the path exists but is not a directory, or if no .rpm files are found in the directory, logs an error and exits the program. """ rpm_path = os.path.abspath(GlobalConfig.RPM_PATH) if not os.path.exists(rpm_path): os.makedirs(rpm_path) if not os.path.isdir(rpm_path): logger.error("RPMS path exists, but is not a directory! Path: %s", GlobalConfig.RPM_PATH) sys.exit(0) # check if there is any .rpm file in the directory if not any(fname.endswith('.rpm') for fname in os.listdir(rpm_path)): logger.error("Cannot find any RPM file in the directory: %s", rpm_path) sys.exit(0) def check_exist_iso(): """ Check if the ISO file exists. Asserts the existence of the ISO file. If it doesn't exist, logs an error and exits the program. """ if not os.path.exists(os.path.abspath(GlobalConfig.ISO)): logger.error("Cannot find the ISO file. Path: %s", GlobalConfig.ISO) sys.exit(0) def get_config_parser(parser): """ Extract configuration from the parser and check paths exist. Parameters: parser (argparse.ArgumentParser): The parser containing configuration data. """ GlobalConfig.ISO = parser.iso[0] GlobalConfig.WORK_DIR = parser.work_dir[0] GlobalConfig.OUTPUT = parser.output[0] if parser.rpm_path is not None and len(parser.rpm_path) > 0: GlobalConfig.RPM_PATH = parser.rpm_path[0] if parser.ko_path is not None and len(parser.ko_path) > 0: GlobalConfig.KERNEL_MODULES_PATH = parser.ko_path[0] check_exist_iso() if GlobalConfig.RPM_PATH != "": check_exist_rpm() if GlobalConfig.KERNEL_MODULES_PATH != "": check_exist_ko() check_exist_workdir() check_exist_outdir() def parse_cli(): """ Parse the command-line arguments. Returns: argparse.Namespace: The parsed arguments. """ parser = argparse.ArgumentParser(description="Inject driver to Linux ISO", formatter_class=RawTextHelpFormatter) # Common arguments parser_argument(parser) config = parser.parse_args() if config.rpm_path is None and config.ko_path is None: print("No rpm and ko driver are specified do nothing") sys.exit(0) if config.rpm_path is None: print("No rpm driver are specified do with ko driver") if config.ko_path is None: print("No ko driver are specified do with rpm driver") if not hasattr(config, 'func'): parser.print_help() sys.exit(0) return config def parser_argument(parser: argparse.ArgumentParser): """ Define the command-line arguments to the parser. Parameters: parser (argparse.ArgumentParser): The parser to define arguments for. """ parser.add_argument("--iso", required=True, nargs=1, dest="iso", help="ISO file used to rebuild") parser.add_argument("--rpm-path", required=False, nargs=1, dest="rpm_path", help="Directory for RPM path") parser.add_argument("--ko-path", required=False, nargs=1, dest="ko_path", help="Directory for kernel module path") parser.add_argument( "--work-dir", required=True, nargs=1, dest="work_dir", help="Directory for ISO rebuild. It must have enough space " "to uncompress the whole ISO file") parser.add_argument( "--output", required=True, nargs=1, dest="output", help="Directory for rebuilt ISO. It must have enough space " "to store the whole ISO file") parser.add_argument('-v', '--version', action='version', version="drv-img version: {}\n" "Python version: {}\n" "Execution path: {}\n" "Timestamp: {}".format(drv_img.__version__, sys.version, pathlib.Path().absolute(), time.ctime())) parser.set_defaults(func=process_with_replace_driver) def process_with_replace_driver(parser: argparse.ArgumentParser): """ Replace the packages/kernel modules in the given ISO and rebuild the ISO. Parameters: parser (argparse.ArgumentParser): The parser containing configuration data. """ init_config(parser) iso_rebuilder = RebuildISOWithDriver(GlobalConfig.ISO, GlobalConfig.RPM_PATH, GlobalConfig.KERNEL_MODULES_PATH, GlobalConfig.WORK_DIR, GlobalConfig.OUTPUT, GlobalConfig.ARCH) iso_rebuilder.do_iso_rebuild() def clean_work_dir(): """ Clean the work directory. Removes the global work directory if it exists. """ if os.path.exists(GlobalConfig.WORK_DIR): shutil.rmtree(GlobalConfig.WORK_DIR) def main(): """ The main function of the script. It parses the command line arguments, executes the function associated with the parsed arguments, and finally cleans up the working directory. """ parser = parse_cli() parser.func(parser) clean_work_dir() if __name__ == "__main__": main() 07070100000017000041ED000000000000000000000002653FAEC000000000000000000000000000000000000000000000003800000000dnf-plugin-ovl-1698672320.455ce02/drv-img/drv_img/utils07070100000018000081A4000000000000000000000001653FAEC000000000000000000000000000000000000000000000004400000000dnf-plugin-ovl-1698672320.455ce02/drv-img/drv_img/utils/__init__.py07070100000019000081A4000000000000000000000001653FAEC000000084000000000000000000000000000000000000004200000000dnf-plugin-ovl-1698672320.455ce02/drv-img/drv_img/utils/logger.py"""This module contains the logger for the project.""" import logging logger = logging.getLogger() logger.setLevel(logging.DEBUG) 0707010000001A000081A4000000000000000000000001653FAEC000004DDD000000000000000000000000000000000000004300000000dnf-plugin-ovl-1698672320.455ce02/drv-img/drv_img/utils/run_cmd.py# -*- coding:utf-8 -*- # # util.py - generic install utility functions # # Copyright (C) 1999-2014 # Red Hat, Inc. All rights reserved. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import os import os.path import subprocess from drv_img.core.oetype import ArchType from drv_img.core.global_config import GlobalConfig from drv_img.utils.logger import logger NO_SUCH_PROGRAM = 127 def start_program(argv, root='/', stdin=None, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **kwargs): logger.warning("Running... %s", argv) if os.path.isdir(root): os.chdir(root) return subprocess.Popen(argv, stdin=stdin, stdout=stdout, stderr=stderr, close_fds=True, cwd=root, **kwargs) def _run_program(argv, root='/', stdin=None, stdout=None, log_output=True, binary_output=False, filter_stderr=False): try: if filter_stderr: stderr = subprocess.PIPE else: stderr = subprocess.STDOUT proc = start_program(argv, root=root, stdin=stdin, stdout=subprocess.PIPE, stderr=stderr) (output_string, err_string) = proc.communicate() if not binary_output: output_string = output_string.decode("utf-8") if output_string and output_string[-1] != "\n": output_string = output_string + "\n" if log_output: if binary_output: # try to decode as utf-8 and replace all undecodable data by # "safe" printable representations when logger binary output decoded_output_lines = output_string.decode("utf-8", "replace") else: # output_string should already be a Unicode string decoded_output_lines = output_string.splitlines(True) for line in decoded_output_lines: logger.info(line.strip()) if stdout: stdout.write(output_string) # If stderr was filtered, log it separately if filter_stderr and err_string and log_output: # try to decode as utf-8 and replace all undecodable data by # "safe" printable representations when logger binary output decoded_err_string = err_string.decode("utf-8", "replace") err_lines = decoded_err_string.splitlines(True) for line in err_lines: logger.warning(line.strip()) except OSError as e: logger.error("Error running %s: %s", argv[0], e.strerror) raise logger.debug("Return code: %d", proc.returncode) return proc.returncode, output_string def exec_readlines(command, argv, stdin=None, root='/', env_prune=None, filter_stderr=False): class ExecLineReader(object): """Iterator class for returning lines from a process and cleaning up the process when the output is no longer needed. """ def __init__(self, proc, argv): self._proc = proc self._argv = argv def __iter__(self): return self def __del__(self): # See if the process is still running if self._proc.poll() is None: # Stop the process and ignore any problems that might arise try: self._proc.terminate() except OSError: pass def __next__(self): # Read the next line, blocking if a line is not yet available line = self._proc.stdout.readline().decode("utf-8") if line == '': # Output finished, wait for the process to end self._proc.communicate() # Check for successful exit if self._proc.returncode < 0: raise OSError("process '%s' was killed by signal %s" % (self._argv, -self._proc.returncode)) elif self._proc.returncode > 0: raise OSError("process '%s' exited with status %s" % (self._argv, self._proc.returncode)) raise StopIteration return line.strip() argv = [command] + argv if filter_stderr: stderr = subprocess.DEVNULL else: stderr = subprocess.STDOUT try: proc = start_program(argv, root=root, stdin=stdin, stderr=stderr) except OSError as e: logger.error("Error running %s: %s", argv[0], e.strerror) raise return ExecLineReader(proc, argv) def exec_with_redirect(command, argv, stdin=None, stdout=None, root='/', log_output=True, binary_output=False): argv = [command] + argv return _run_program(argv, stdin=stdin, stdout=stdout, root=root, log_output=log_output, binary_output=binary_output) def exec_with_capture(command, argv, stdin=None, root='/', log_output=True, filter_stderr=False): argv = [command] + argv return _run_program(argv, stdin=stdin, root=root, log_output=log_output, filter_stderr=filter_stderr)[1] def mkdir_chain(directory): """ Make a directory and all of its parents. Don't fail if part or of it already exists. :param str directory: The directory path to create """ os.makedirs(directory, 0o755, exist_ok=True) def _run_systemctl(command, service, root="/"): """ Runs 'systemctl command service.service' :return: exit status of the systemctl """ args = [command, service] if root != "/": args += ["--root", root] ret = exec_with_redirect("systemctl", args) if ret[0] != 0: logger.error(ret[1]) return ret[0] def start_service(service): return _run_systemctl("start", service) def stop_service(service): return _run_systemctl("stop", service) def restart_service(service): return _run_systemctl("restart", service) def service_running(service): ret = _run_systemctl("status", service) return ret == 0 def is_service_installed(service, root='/'): """Is a systemd service installed in the sysroot? :param str service: name of the service to check :param str root: path to the sysroot or None to use default sysroot path """ if not service.endswith(".service"): service += ".service" args = ["list-unit-files", service, "--no-legend"] if root != "/": args += ["--root", root] unit_file = exec_with_capture("systemctl", args) return bool(unit_file) def enable_service(service, root='/'): ret = _run_systemctl("enable", service, root=root) if ret != 0: raise ValueError("Error enabling service %s: %s" % (service, ret)) def disable_service(service, root='/'): ret = _run_systemctl("disable", service, root=root) if ret != 0: logger.warning("Disabling %s failed. It probably doesn't exist", service) def get_mount_paths(devnode): '''given a device node, return a list of all active mountpoints.''' devno = os.stat(devnode).st_rdev majmin = "%d:%d" % (os.major(devno), os.minor(devno)) mountinfo = (line.split() for line in open("/proc/self/mountinfo")) return [info[4] for info in mountinfo if info[2] == majmin] def decode_bytes(data): """Decode the given bytes. Return the given string or a string decoded from the given bytes. :param data: bytes or a string :return: a string """ if isinstance(data, str): return data if isinstance(data, bytes): return data.decode('utf-8') raise ValueError("Unsupported type '{}'.".format(type(data).__name__)) def join_paths(path, *paths): if len(paths) == 0: return path new_paths = [] for p in paths: new_paths.append(p.lstrip(os.path.sep)) return os.path.join(path, *new_paths) def get_os_arch(): try: arch = exec_with_capture("uname", ["-m"]).strip() except Exception as err: logger.error(err) return "" if arch == ArchType.ARM64.value: return ArchType.ARM64 elif arch == ArchType.X86_64.value: return ArchType.X86_64 else: logger.error("platform: %s is not supported", arch) return "" def rpm_src_setup(src_path): try: ret = exec_with_redirect("rpm", ["-i", src_path]) if ret[0] != 0: logger.error(ret[1]) except Exception as err: logger.error(err) return ret[0] def rpm_src_build_pre(spec_path): try: ret = exec_with_redirect("rpmbuild", ["-bp", spec_path]) if ret[0] != 0: logger.error(ret[1]) except Exception as err: logger.error(err) return ret[0] def rpm_build(spec_file): ret = 0 try: _vendor_args = "_vendor {}".format(GlobalConfig.PRODUCT_NAME) ret = exec_with_redirect("rpmbuild", ["-ba", spec_file, "--define", _vendor_args]) if ret[0] != 0: logger.error(ret[1]) except Exception as err: logger.error(err) return ret[0] def yum_download_install(package): ret = 0 try: ret = exec_with_redirect("yumdownloader", [ "--resolve", "--installroot={}".format(GlobalConfig.CACHED_PATH), "--destdir={}".format(GlobalConfig.WORK_DIR + "/Packages"), package ]) if ret[0] != 0: logger.error(ret[1]) except Exception as err: logger.error(err) return ret[0] def yum_loacl_install(rpm_path, package_path, install_path): ret = 0 try: ret = exec_with_redirect("yum", [ "localinstall", "--installroot={}".format(install_path), "--destdir={}".format(package_path), rpm_path ]) if ret[0] != 0: logger.error(ret[1]) except Exception as err: logger.error(err) return ret[0] def unsquashfs(efibootimg, uncompress_path): ret = 0 try: ret = exec_with_redirect("unsquashfs", ["-d", uncompress_path, efibootimg]) if ret[0] != 0: logger.error(ret[1]) except Exception as err: logger.error(err) return ret[0] def mksquashfs(liveos, installimg): ret = 0 try: ret = exec_with_redirect( "mksquashfs", [liveos, installimg, "-noappend", "-comp", "xz"]) if ret[0] != 0: logger.error(ret[1]) except Exception as err: logger.error(err) return ret[0] def replace_vendor_in_boot(): pass def replace_rpms_in_minios(work_dir, rpm_path): pass def replace_rpms_in_repo(work_dir, rpm_path): os.chdir(work_dir) if not os.path.isdir(rpm_path): logger.error("%s is not a valid direcotry!", rpm_path) return 1 else: if not rpm_path.endswith('/'): rpm_path += "/." else: rpm_path += "." ret = 0 try: ret = exec_with_redirect("cp", ["-f", rpm_path, "Packages/"]) if ret[0] != 0: logger.error(ret[1]) except Exception as err: logger.error(err) return ret[0] def createrepo_group(work_dir): ret = 0 try: for line in exec_readlines("createrepo", ["-g", "repodata/normal.xml", "./"], root=work_dir): logger.warning(line) except Exception as err: logger.error(err) ret = 1 return ret def cp_iso_file(src_dir, dst_dir): ret = 0 if not os.path.isdir(src_dir): logger.error("%s is not a valid direcotry!", src_dir) return 1 elif not os.path.isdir(dst_dir): logger.error("%s is not a valid direcotry!", dst_dir) return 1 else: if not src_dir.endswith('/'): src_dir += "/." else: src_dir += "." try: ret = exec_with_redirect("cp", ["-ar", src_dir, dst_dir]) if ret[0] != 0: logger.error(ret[1]) except Exception as err: logger.error(err) return ret[0] def mount(device, mntpoint, ftype, options=None): if not options: options = "defaults" mntpoint = os.path.normpath(mntpoint) if not os.path.isdir(mntpoint): os.makedirs(dir, 0o755) ret = 0 try: ret = exec_with_redirect( "mount", ["-t", ftype, "-o", options, device, mntpoint]) if ret[0] != 0: logger.error(ret[1]) except Exception as err: logger.error(err) return ret[0] def umount(mntpoint): ret = 0 try: ret = exec_with_redirect("umount", [mntpoint]) if ret[0] != 0: logger.error(ret[1]) except Exception as err: logger.error(err) return ret[0] def mkisofs(work_dir, output, arch, vid): cmd = "mkisofs -R -J -T -r -l -d -joliet-long" \ " -allow-multidot -allow-leading-dots -no-bak" \ " -no-emul-boot -e images/efiboot.img" x86_options = " -b isolinux/isolinux.bin -c isolinux/boot.cat" \ " -boot-load-size 4 -boot-info-table -eltorito-alt-boot" if arch == ArchType.X86_64: cmd += x86_options options = " -V {} -o {} {} ".format(vid, output, work_dir) cmd += options ret = 0 try: logger.warning(cmd) ret = subprocess.check_call(cmd, shell=True) except Exception as err: logger.error("Failed to mkisofs for %s", vid) ret = 1 return ret def implant_iso_md5(iso_path): try: ret = exec_with_redirect("implantisomd5", [iso_path]) if ret[0] != 0: logger.error(ret[1]) except Exception as err: logger.error(err) return ret[0] def get_os_release_value(name, sysroot="/"): """Read os-release files and return a value of the specified parameter. :param name: a name of the parameter (for example, "VERSION_ID") :param sysroot: a path to the system root :return: a string with the value of None if nothing found """ # Match the variable assignment (for example, "VERSION_ID="). name += "=" # Search all os-release files in the system root. paths = ("/etc/os-release", "/usr/lib/os-release") for path in paths: try: with open(join_paths(sysroot, path), "r") as f: for line in f: # Match the current line. if not line.startswith(name): continue # Get the value. value = line[len(name):] # Strip spaces and then quotes. value = value.strip().strip("\"'") return value except FileNotFoundError: pass # No value found. logger.debug("%s not found in os-release files", name[:-1]) return None def replace(file, old_content, new_content, num=None): content = read_file(file) if num is None: content = content.replace(old_content, new_content) else: content = content.replace(old_content, new_content, num) rewrite_file(file, content) def read_file(file): with open(file, encoding='UTF-8') as f: read_all = f.read() f.close() return read_all def rewrite_file(file, data): with open(file, 'w', encoding='UTF-8') as f: f.write(data) f.close() def cp_catalog(src_dir, dst_dir): if os.path.exists(dst_dir) is False: os.makedirs(dst_dir) try: ret = exec_with_redirect("cp", ["-rf", src_dir, dst_dir]) if ret[0] != 0: logger.error(ret[1]) except Exception as err: logger.error(err) return ret[0] def cp_file(src_file, dst_file): try: ret = exec_with_redirect("cp", ["-rf", src_file, dst_file]) if ret[0] != 0: logger.error(ret[1]) except Exception as err: logger.error(err) return ret[0] def depmod(work_dir, kernel_version): try: ret = exec_with_redirect("depmod", ['-a', '-b', work_dir, kernel_version]) if ret[0] != 0: logger.error(ret[1]) except Exception as err: logger.error(err) return ret[0] def modprobe(kernel_version, work_dir, ko_base): try: ret = exec_with_redirect( "modprobe", ['-S', kernel_version, '-d', work_dir, ko_base]) if ret[0] != 0: logger.error(ret[1]) except Exception as err: logger.error(err) return ret[0] def get_module_vermagic(module_path): try: module_comp = exec_with_capture( "modinfo", ["-F", "vermagic", module_path]).strip() return module_comp except Exception as err: logger.error(err) return "" def get_kernel_version_with_chroot(root_dir): try: current_kernel = exec_with_capture("chroot", [root_dir, 'uname', '-r']).strip() return current_kernel except Exception as err: logger.error(err) return "" def rpm_setup(rpm_path, dst_path='/'): try: root_path = "--root={}".format(dst_path) ret = exec_with_redirect( "rpm", ["-ivh", rpm_path, root_path, "--force", "--nodeps"]) if ret[0] != 0: logger.error(ret[1]) except Exception as err: logger.error("rpm set up failed! package path:%s, dst_path: %s, %s", rpm_path, dst_path, err) return ret[0] def rpm_check_dependency(rpm_path): try: output = exec_with_capture("rpm", ["-qR", rpm_path]) return output except Exception as err: logger.error(err) return "" def rpm_query_provides(rpm_path): try: output = exec_with_capture("rpm", ["-q", "--whatprovides", rpm_path]) return output except Exception as err: logger.error(err) return "" def remove_file(target_path): try: ret = exec_with_redirect("rm", ["-rf", target_path]) if ret[0] != 0: logger.error(ret[1]) except Exception as err: logger.error("rm %s failed! %s", target_path, err) return ret[0] def exist_command(cmd): try: ret = _run_program([cmd, "--help"]) if ret[0] == NO_SUCH_PROGRAM: return False else: return True except FileNotFoundError as err: return False 0707010000001B000081A4000000000000000000000001653FAEC000000019000000000000000000000000000000000000003B00000000dnf-plugin-ovl-1698672320.455ce02/drv-img/requirements.txtpackaging rpm pykickstart0707010000001C000081A4000000000000000000000001653FAEC000000378000000000000000000000000000000000000003300000000dnf-plugin-ovl-1698672320.455ce02/drv-img/setup.py"""Package setup script for drv-img.""" from setuptools import setup, find_packages import drv_img def long_description(): """ Return the contents of the 'README.md' file as a string. :return: the contents of 'README.md' file :rtype: str """ with open('README.md', encoding='utf-8') as file: return file.read() setup( name=drv_img.__cli_name__, version=drv_img.__version__, description=drv_img.__doc__.strip(), long_description=long_description(), long_description_content_type='text/markdown', author=drv_img.__author__, author_email='binshuozu@gmail.com', license=drv_img.__license__, packages=find_packages(include=['drv_img', 'drv_img.*']), entry_points={ 'console_scripts': [ 'drv-img = drv_img.run:main', ], }, python_requires='>=3.7', install_requires=["rpm"], ) 07070100000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000B00000000TRAILER!!!185 blocks
Locations
Projects
Search
Status Monitor
Help
Open Build Service
OBS Manuals
API Documentation
OBS Portal
Reporting a Bug
Contact
Mailing List
Forums
Chat (IRC)
Twitter
Open Build Service (OBS)
is an
openSUSE project
.
浙ICP备2022010568号-2