Repository: kxr/o-must-gather Branch: master Commit: 672d69ae5471 Files: 117 Total size: 226.2 KB Directory structure: gitextract_b8u0jcle/ ├── .gitignore ├── LICENSE ├── README.md ├── omg/ │ ├── __init__.py │ ├── cli.py │ ├── completion/ │ │ └── __init__.py │ ├── components/ │ │ ├── __init__.py │ │ ├── ceph/ │ │ │ ├── __init__.py │ │ │ └── ceph.py │ │ └── etcdctl/ │ │ ├── __init__.py │ │ ├── etcdctl.py │ │ └── output/ │ │ ├── __init__.py │ │ ├── alarm_list.py │ │ ├── endpoint_health.py │ │ ├── endpoint_status.py │ │ └── member_list.py │ ├── config/ │ │ ├── __init__.py │ │ ├── config.py │ │ └── logging.py │ ├── get/ │ │ ├── __init__.py │ │ ├── complete.py │ │ ├── get.py │ │ ├── get_resources.py │ │ ├── output/ │ │ │ ├── __init__.py │ │ │ ├── build_table.py │ │ │ ├── o_raw.py │ │ │ ├── o_table.py │ │ │ └── table_modules/ │ │ │ ├── Build.py │ │ │ ├── BuildConfig.py │ │ │ ├── CSIDriver.py │ │ │ ├── CSINode.py │ │ │ ├── CatalogSource.py │ │ │ ├── CephCluster.py │ │ │ ├── CephFilesystem.py │ │ │ ├── CertificateSigningRequest.py │ │ │ ├── ClusterOperator.py │ │ │ ├── ClusterServiceVersion.py │ │ │ ├── ClusterVersion.py │ │ │ ├── ConfigMap.py │ │ │ ├── CronJob.py │ │ │ ├── CustomResourceDefinition.py │ │ │ ├── DaemonSet.py │ │ │ ├── Deployment.py │ │ │ ├── DeploymentConfig.py │ │ │ ├── EndpointSlice.py │ │ │ ├── Endpoints.py │ │ │ ├── Event.py │ │ │ ├── HorizontalPodAutoscaler.py │ │ │ ├── HostSubnet.py │ │ │ ├── ImageStream.py │ │ │ ├── InstallPlan.py │ │ │ ├── Job.py │ │ │ ├── Machine.py │ │ │ ├── MachineConfig.py │ │ │ ├── MachineConfigPool.py │ │ │ ├── MachineSet.py │ │ │ ├── MutatingWebhookConfiguration.py │ │ │ ├── Namespace.py │ │ │ ├── NetNamespace.py │ │ │ ├── NetworkPolicy.py │ │ │ ├── Node.py │ │ │ ├── PersistentVolume.py │ │ │ ├── PersistentVolumeClaim.py │ │ │ ├── Pod.py │ │ │ ├── ReplicaSet.py │ │ │ ├── ReplicationController.py │ │ │ ├── Route.py │ │ │ ├── Secret.py │ │ │ ├── Service.py │ │ │ ├── StatefulSet.py │ │ │ ├── StorageClass.py │ │ │ ├── Subscription.py │ │ │ ├── ValidatingWebhookConfiguration.py │ │ │ ├── VirtualMachine.py │ │ │ └── VirtualMachineInstance.py │ │ └── parse.py │ ├── log/ │ │ ├── __init__.py │ │ ├── complete.py │ │ └── log.py │ ├── machine_config/ │ │ ├── __init__.py │ │ ├── compare.py │ │ ├── decode_content.py │ │ └── extract.py │ ├── must_gather/ │ │ ├── RDEFS.py │ │ ├── __init__.py │ │ ├── exceptions.py │ │ ├── generate_rdefs.py │ │ ├── get_rdef.py │ │ ├── load_resources.py │ │ ├── locate_yamls.py │ │ └── scan_mg.py │ ├── project/ │ │ ├── __init__.py │ │ ├── complete.py │ │ ├── project.py │ │ └── projects.py │ ├── show/ │ │ └── __init__.py │ ├── use/ │ │ ├── __init__.py │ │ ├── show_mg_info.py │ │ └── use.py │ ├── utils/ │ │ ├── __init__.py │ │ ├── age.py │ │ ├── dget.py │ │ ├── extract_labels.py │ │ ├── load_json.py │ │ ├── load_yaml.py │ │ └── size.py │ └── whoami/ │ ├── __init__.py │ └── whoami.py ├── samples/ │ └── must-gather.46i.tgz ├── setup.cfg ├── setup.py └── tests/ ├── __init__.py ├── conftest.py ├── dev_testing.py ├── test_config.py ├── test_mg_ops.py └── test_use.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ *.pyc **/__pycache__ dist/ build/ *.egg-info/ .pytest_cache/ .tox/ .coverage .vscode venv/ ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. 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 them 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 prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. 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. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey 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; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If 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 convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU 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 that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. 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. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 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. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. 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 state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 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 3 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 . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program 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, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU 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. But first, please read . ================================================ FILE: README.md ================================================ # O Must Gather (omg) v2 (WORK IN PROGRESS) With the previous (v1) implementation of omg, there were some major limitations. A major restructuring is being done to implement some advance features that are necessary, for example: - **Multi directory support**: Often times a single must-gather is not enough to capture all the components that are being investigated hence multiple must-gathers (or combination of must-gathes and oc-adm-inspect) are collected. omg needs to be able to look at them at once (using v1 omg we have to switch to these directories individually, which is very inconvenient). - **Dynamic CRDs**: The CRDs in OpenShift are huge in number and growing. In the current implementation of omg, every CRD needs to be "handled" manually for omg to recoginze it. A [resource map](https://github.com/kxr/o-must-gather/blob/172f84afc2b81ab523edf78eb6d4a0e64d34cd32/omg/common/resource_map.py#L62-L625) to handle each CRD is hard to scale and fails to pick any new/undefined CRDs. In the newer implementation, CRDs will be automatically detected and recognized. This idea was orignally pitched by Robert Bost [here](https://github.com/kxr/o-must-gather/issues/34). - **API Groups**: Handling API Groups for each CRD is important. For example to differentiate between `oc get config.operator` and `oc get config.imageregistry`. - **Components Output**: Provide an easy way to see outputs of other components like elasticsearch and ceph when component specific must-gathers are collected (ODF, Logging, CNV, etc.) - **High Level Summary**: A high level summary of a must-gather would be very useful. For exmaple `omg show summary` and `omg show issues`. - **Console Logging**: A proper console logging library [loguru](https://github.com/Delgan/loguru) is being used that supports standard/debug output and can separate standard and error outputs. ================================================ FILE: omg/__init__.py ================================================ version_info = (2, 0, 0) version = '.'.join(str(c) for c in version_info) ================================================ FILE: omg/cli.py ================================================ import click import os import subprocess from omg import version from omg.config import logging, config from omg.use import use from omg.project import project, projects from omg.project.complete import complete_projects from omg.get import get from omg.get.complete import complete_get from omg.log.complete import complete_pods, complete_containers from omg.log import log from omg.whoami import whoami from omg.components.ceph import ceph from omg.components.etcdctl import etcdctl from omg.machine_config.compare import mc_compare from omg.machine_config.extract import mc_extract # Common Options used by multiple subcommands o_filtered_path = click.option( "-P", "--path", type=int, default=0) o_log_level = click.option( "-l", "--loglevel", type=click.Choice(["normal", "info", "debug", "trace"])) o_namespace = click.option( "--namespace", "-n", required=False, shell_complete=complete_projects) o_all_namespaces = click.option( "--all-namespaces", "-A", required=False, is_flag=True) # Main click group @click.group() @o_log_level @o_filtered_path @o_namespace @o_all_namespaces def cli(loglevel, path, namespace, all_namespaces): logging.setup_logging(loglevel) if path: config.filtered_path = path if namespace: config.namespace = namespace if all_namespaces: config.all_namespaces = all_namespaces # omg *use* @cli.command("use") @click.argument("mg_paths", nargs=-1, required=False, type=click.Path( exists=True, file_okay=False, resolve_path=True, allow_dash=False)) @click.option("--cwd", is_flag=True) @o_log_level @o_filtered_path def use_cmd(mg_paths, cwd, loglevel, path): """ Select one or more must-gather(s) to use """ if loglevel: logging.setup_logging(loglevel) if path: config.filtered_path = path use.cmd(mg_paths, cwd) # omg *project* @cli.command("project") @click.argument("name", required=False, shell_complete=complete_projects) @o_log_level @o_filtered_path def project_cmd(name, loglevel, path): """ Switch to another project """ if loglevel: logging.setup_logging(loglevel) if path: config.filtered_path = path project.cmd(name) # omg *projects* @cli.command("projects") @o_log_level @o_filtered_path def projects_cmd(path, loglevel): """ Display existing projects """ if loglevel: logging.setup_logging(loglevel) if path: config.filtered_path = path projects.cmd() # omg *get* @cli.command("get") @click.argument("objects", nargs=-1, shell_complete=complete_get) @click.option("--output", "-o", type=click.Choice(["yaml", "json", "wide", "name"])) @click.option("--show-labels", is_flag=True, type=bool) @o_log_level @o_namespace @o_all_namespaces @o_filtered_path def get_cmd(objects, output, show_labels, loglevel, namespace, all_namespaces, path): """ Display one or many resources """ if loglevel: logging.setup_logging(loglevel) if path: config.filtered_path = path if namespace: config.namespace = namespace if all_namespaces: config.all_namespaces = all_namespaces get.cmd(objects, output, show_labels) # omg *log* @cli.command("logs") @click.argument("resource", shell_complete=complete_pods) @click.option("--container", "-c", shell_complete=complete_containers) @click.option("--previous", "-p", is_flag=True) @o_log_level @o_filtered_path @o_namespace def logs_cmd(resource, container, previous, namespace, loglevel, path): """ Print the logs for a container in a pod """ if loglevel: logging.setup_logging(loglevel) if path: config.filtered_path = path if namespace: config.namespace = namespace log.cmd(resource, container, previous) # omg *whoami* @cli.command("whoami") def whoami_cmd(): """ Tell you who you are """ whoami.cmd() # omg *version* @cli.command("version") def version_cmd(): """ Prints the version of o-must-gather """ print() print("omg version " + str(version) + " (https://github.com/kxr/o-must-gather)") print() @cli.command("completion") @click.argument("shell", nargs=1, type=click.Choice(["bash", "zsh", "fish"])) def completion(shell): """ Output shell completion code for the specified shell (bash or zsh) """ newenv = os.environ.copy() newenv["_OMG_COMPLETE"] = "{}_source".format(shell) subprocess.run("omg", env=newenv) # omg *ceph* @cli.command("ceph", context_settings={"ignore_unknown_options": True}) @click.argument("ceph_args", nargs=-1) @click.option("--output", "--format", "-o", type=click.Choice(["json", "json-pretty"])) @o_log_level @o_filtered_path def ceph_cmd(ceph_args, output, loglevel, path): if loglevel: logging.setup_logging(loglevel) if path: config.filtered_path = path ceph.cmd(ceph_args, output, com="ceph") # omg *rados* @cli.command("rados", context_settings={"ignore_unknown_options": True}) @click.argument("ceph_args", nargs=-1) @o_log_level @o_filtered_path def rados_cmd(ceph_args, loglevel, path): if loglevel: logging.setup_logging(loglevel) if path: config.filtered_path = path ceph.cmd(ceph_args, None, com="rados") # omg *rbd* @cli.command("rbd", context_settings={"ignore_unknown_options": True}) @click.argument("ceph_args", nargs=-1) @o_log_level @o_filtered_path def rbd_cmd(ceph_args, loglevel, path): if loglevel: logging.setup_logging(loglevel) if path: config.filtered_path = path ceph.cmd(ceph_args, None, com="rbd") # omg *etcdctl* @cli.command("etcdctl", context_settings={"ignore_unknown_options": True}) @click.option("--output", "--write-out", "-o", type=click.Choice(["json", "table", "simple"])) @click.argument("etcdctl_args", nargs=-1) @o_log_level @o_filtered_path def etcdctl_cmd(etcdctl_args, output, loglevel, path): if loglevel: logging.setup_logging(loglevel) if path: config.filtered_path = path etcdctl.cmd(etcdctl_args, output) # Click group for machine-config @cli.group("machine-config") def mc_cmd(): """ Explore Machine Configs """ pass # omg machine-config *extract* @mc_cmd.command("extract") @click.argument("mc_names", nargs=-1) @o_log_level @o_filtered_path def extract_mc_cmd(mc_names, loglevel, path): """ Extract Machine Configs """ if loglevel: logging.setup_logging(loglevel) if path: config.filtered_path = path mc_extract(mc_names) # omg machine-config *compare* @mc_cmd.command("compare") @click.argument("mc_names", nargs=2) @click.option("--show-contents", is_flag=True) @o_log_level @o_filtered_path def compare_mc_cmd(mc_names, show_contents, loglevel, path): """ Compare Machine Configs """ if loglevel: logging.setup_logging(loglevel) if path: config.filtered_path = path mc_compare(mc_names, show_contents) ================================================ FILE: omg/completion/__init__.py ================================================ ================================================ FILE: omg/components/__init__.py ================================================ ================================================ FILE: omg/components/ceph/__init__.py ================================================ ================================================ FILE: omg/components/ceph/ceph.py ================================================ import os from loguru import logger as lg from omg.config import config def cmd(ceph_args, output, com): cfg = config.get() mg_paths = cfg["paths"] if output in ["json", "json-pretty"]: commands_dir = "must_gather_commands_json_output" json_add = "_--format_json-pretty" else: commands_dir = "must_gather_commands" json_add = "" file_name = "{}_{}{}".format(com, "_".join(ceph_args), json_add) if file_name.startswith("ceph_config_show_"): file_name = file_name.replace("ceph_config_show_", "config_") ceph_file = os.path.join("ceph", commands_dir, file_name) lg.debug("ceph_file: {}".format(ceph_file)) ceph_cmd_paths = {} i = 1 for p in mg_paths: ceph_cmd_path = os.path.join(p, ceph_file) if os.path.isfile(ceph_cmd_path): lg.info("Command output file found: {}".format(ceph_cmd_path)) ceph_cmd_paths[i] = ceph_cmd_path i += 1 if ceph_cmd_paths: for i, cp in ceph_cmd_paths.items(): with open(cp, "r") as lf: print(lf.read()) if len(mg_paths) > 1: lg.opt(colors=True).success("^^^[{}]^^^\n".format(i)) else: suggestions = {} i = 1 for p in mg_paths: try: files = os.listdir(os.path.join(p, "ceph", "must_gather_commands")) file_match = "{}_{}".format(com, "_".join(ceph_args)) sugg = [] sugg.extend([ "omg " + f.replace("_", " ") for f in files if f.startswith(file_match)]) sugg.extend([ "omg ceph config show {}".format(f.replace("config_", "")) for f in files if f.startswith("config_") ]) if sugg: suggestions[i] = sugg except Exception as e: lg.debug(e) pass i += 1 if suggestions: lg.success("\nNote: Output of following commands are available:\n") for i, sugg in suggestions.items(): lg.success("\n".join(sugg)) lg.opt(colors=True).success("^^^[{}]^^^\n".format(i)) else: lg.error( "Command output not found in any of the" " {} must-gather paths".format(len(mg_paths)) ) ================================================ FILE: omg/components/etcdctl/__init__.py ================================================ ================================================ FILE: omg/components/etcdctl/etcdctl.py ================================================ import os from importlib import import_module from loguru import logger as lg from omg.utils.load_json import load_json from omg.config import config def cmd(etcdctl_args, output): cfg = config.get() mg_paths = cfg["paths"] if output is None: output = "table" command = "_".join(etcdctl_args) etcd_file = os.path.join( "etcd_info", "{}.json".format(command)) lg.debug("etcd_file: {}".format(etcd_file)) etcd_cmd_paths = {} i = 1 for p in mg_paths: ceph_cmd_path = os.path.join(p, etcd_file) if os.path.isfile(ceph_cmd_path): lg.info("Command output file found: {}".format(ceph_cmd_path)) etcd_cmd_paths[i] = ceph_cmd_path i += 1 if etcd_cmd_paths: for i, cp in etcd_cmd_paths.items(): try: j_data = load_json(cp) table_mod = import_module( "omg.components.etcdctl.output.{}".format(command)) table_mod.etcdctl_out(j_data, output) except Exception as e: lg.warning("Error generating output for {}: {}".format(command, e)) lg.success("\nHere is the raw file ({}):".format(cp)) with open(cp, "r") as cf: print(cf.read()) if len(mg_paths) > 1: lg.opt(colors=True).success("^^^[{}]^^^\n".format(i)) else: suggestions = {} i = 1 for p in mg_paths: try: files = os.listdir(os.path.join(p, "etcd_info")) file_match = "_".join(etcdctl_args) sugg = [] sugg.extend([ "omg etcdctl " + f.replace("_", " ").replace(".json", "") for f in files if f.startswith(file_match)]) if sugg: suggestions[i] = sugg except Exception: pass i += 1 if suggestions: lg.success("\nNote: Output of following commands are available:\n") for i, sugg in suggestions.items(): lg.success("\n".join(sugg)) lg.opt(colors=True).success("^^^[{}]^^^\n".format(i)) else: lg.error( "Command output not found in any of the" " {} must-gather paths".format(len(mg_paths)) ) ================================================ FILE: omg/components/etcdctl/output/__init__.py ================================================ ================================================ FILE: omg/components/etcdctl/output/alarm_list.py ================================================ import json def etcdctl_out(j_data, output): print(json.dumps(j_data, indent=2)) ================================================ FILE: omg/components/etcdctl/output/endpoint_health.py ================================================ import json from tabulate import tabulate from omg.utils.dget import dget def etcdctl_out(j_data, output): if output == "json": print(json.dumps(j_data, indent=2)) else: head = ["ENDPOINT", "HEALTH", "TOOK", "ERROR"] body = [] for jd in j_data: body.append([ dget(jd, ["endpoint"], "?"), dget(jd, ["health"], "?"), dget(jd, ["took"], "?"), dget(jd, ["error"], ""), ]) if output == "table": print(tabulate(body, head, tablefmt="psql")) elif output is None or output == "simple": for row in body: if row[3] == "": print( "{} is healthy: " "successfully committed proposal: took = {}" .format(row[0], row[2]) ) else: print( "{} is unhealthy: " "failed to commit proposal: {}" .format(row[0], row[3]) ) ================================================ FILE: omg/components/etcdctl/output/endpoint_status.py ================================================ import json from tabulate import tabulate from omg.utils.dget import dget from omg.utils.size import num2human def etcdctl_out(j_data, output): if output == "json": print(json.dumps(j_data, indent=2)) else: head = [ "ENDPOINT", "ID", "VERSION", "DB SIZE/IN USE", "IS LEADER", "IS LEARNER", "RAFT TERM", "RAFT INDEX", "RAFT APPLIED INDEX", "ERRORS" ] body = [] for jd in j_data: member_id = dget(jd, ["Status", "header", "member_id"]) leader_id = dget(jd, ["Status", "leader"]) body.append([ dget(jd, ["Endpoint"], "?"), "{:x}".format(int(member_id)), dget(jd, ["Status", "version"], "?"), "{}/{}".format( num2human(dget(jd, ["Status", "dbSize"], "0")), num2human(dget(jd, ["Status", "dbSizeInUse"], "0")) ), "true" if member_id == leader_id else "false", dget(jd, ["isLearner"], "false"), dget(jd, ["Status", "raftTerm"], "?"), dget(jd, ["Status", "raftIndex"], "?"), dget(jd, ["Status", "raftAppliedIndex"], "?"), dget(jd, ["Status", "errors"], ""), ]) if output == "table": print(tabulate(body, head, tablefmt="psql")) elif output is None or output == "simple": for row in body: print(", ".join([str(r) for r in row])) ================================================ FILE: omg/components/etcdctl/output/member_list.py ================================================ import json from tabulate import tabulate from omg.utils.dget import dget def etcdctl_out(j_data, output): if output == "json": print(json.dumps(j_data, indent=2)) else: head = ["ID", "STATUS", "NAME", "PEER ADDRS", "CLIENT ADDRS", "IS LEARNER"] body = [] for jd in dget(j_data, ["members"]): name = dget(jd, ["name"], "") body.append([ "{:x}".format(int(dget(jd, ["ID"]))), "started" if len(name) > 0 else "unstarted", name, ",".join(dget(jd, ["peerURLs"], "?")), ",".join(dget(jd, ["clientURLs"], "?")), dget(jd, ["isLearner"], "false") ]) if output == "table": print(tabulate(body, head, tablefmt="psql")) elif output is None or output == "simple": for row in body: print(", ".join([str(r) for r in row])) ================================================ FILE: omg/config/__init__.py ================================================ ================================================ FILE: omg/config/config.py ================================================ """ config.py """ import yaml from os import path, getenv from loguru import logger as lg from omg.utils.dget import dget from omg.must_gather.scan_mg import scan_mg, NoValidMgFound _default_cfile = path.join(getenv("HOME") or "", ".omgconfig") # -p, --path filtered_path = 0 # -n, --namespace namespace = None # -A, --all-namespaces all_namespaces = False class NoMgSelected(Exception): """ Error raised when no must-gather is selected """ pass class InvalidConfig(Exception): """ Error raised when config is invalid """ pass def _load_config(cfile): """Load config from file. If file doesn't exist MgConfigNotFound is raised. Args: cfile (str): Config file Returns: dict: Config dict """ lg.debug("FUNC_INIT: {}".format(locals())) if not cfile: cfile = _default_cfile config = {"paths": None, "project": None} if path.isfile(cfile): try: with open(cfile, "r") as c_f: lg.debug("Loading config from: {}".format(cfile)) lconf = yaml.safe_load(c_f) lg.debug("Loaded config from file: {}".format(lconf)) config["paths"] = dget(lconf, ["paths"], None) config["project"] = dget(lconf, ["project"], None) except Exception as e: raise InvalidConfig(e) if not dget(config, ["paths"], None): raise NoMgSelected("Please select a must-gather (omg use )") return config def _dump_config(config, cfile): """Dump config to file Args: config (dict): Config dict cfile (str): Config file """ if not cfile: cfile = _default_cfile try: with open(cfile, "w") as c_f: yaml.dump(config, c_f, default_flow_style=False) lg.debug("Config dumped to {}".format(cfile)) except Exception as e: lg.error(e) raise SystemExit(1) def get(cfile=None): """Get config from file. Args: cfile (str, optional): Config file. Defaults to None. Raises: SystemExit: If paths is not found in config file Returns: dict: Config dict """ if not cfile: env_config = getenv("OMGCONFIG") if env_config: cfile = env_config else: cfile = _default_cfile try: config = _load_config(cfile) except NoMgSelected as e: lg.error(e) raise SystemExit(1) if config["paths"] == ["."]: try: v_mgs = scan_mg(["."]) config["paths"] = v_mgs config["cwd"] = True except NoValidMgFound as e: lg.error(e) raise SystemExit(1) if filtered_path: config["paths"] = [config["paths"][filtered_path - 1]] if namespace: config["project"] = namespace if all_namespaces: config["project"] = "_all" return config def save(paths=None, project=None, cfile=None): """Save config to file Args: paths (list[str], optional): Must-gather paths. Defaults to None. project ([type], optional): Project. Defaults to None. cfile ([type], optional): Config file. Defaults to None. """ try: config = _load_config(cfile) except (NoMgSelected, InvalidConfig): c_paths = None c_project = None else: c_paths = dget(config, ["paths"]) c_project = dget(config, ["project"]) if paths: save_paths = paths else: save_paths = c_paths if project: save_project = project else: save_project = c_project _dump_config( {"paths": save_paths, "project": save_project}, cfile) ================================================ FILE: omg/config/logging.py ================================================ import sys from os import getenv from loguru import logger def _is_debug_or_trace(record): return ( record["level"].name == "DEBUG" or record["level"].name == "TRACE" ) def _is_info(record): return record["level"].name == "INFO" def _is_success(record): return record["level"].name == "SUCCESS" def _is_warning_or_error(record): return ( record["level"].name == "WARNING" or record["level"].name == "ERROR" ) _debug_fmt = ( "{level} " "[{name}:{function}:{line}] " "{message}" ) _info_fmt = ( "{level} {message}" ) _success_fmt = ( "{message}" ) def setup_logging(loglevel): # If loglevel is not set, we check the env['OMG_LOG_LEVEL'] # else we set it to default "normal" if not loglevel: env_log_level = getenv("OMG_LOG_LEVEL") if (env_log_level and env_log_level in ['normal', 'info', 'debug', 'trace']): loglevel = env_log_level else: loglevel = "normal" # Map the loglevel to loguru's standard/default loglevel # normal -> SUCCESS(25) # info -> INFO(20) # debug -> DEBUG(10) # trace -> TRACE(5) if loglevel == 'normal': level = 25 elif loglevel == 'info': level = 20 elif loglevel == 'debug': level = 10 elif loglevel == 'trace': level = 5 else: raise ValueError('Invalid loglevel: ' + str(loglevel)) logger.remove() # debug or trace uses _debug_fmt format if level <= 10: logger.add(sys.stderr, colorize=True, level=level, filter=_is_debug_or_trace, format=_debug_fmt) # info uses _info_fmt format if level <= 20: logger.add(sys.stderr, colorize=True, level=level, filter=_is_info, format=_info_fmt) # normal/default uses _success_fmt for success logs # and _info_fmt for error and warning logs if level <= 25: logger.add(sys.stderr, colorize=True, level=level, filter=_is_success, format=_success_fmt) logger.add(sys.stderr, colorize=True, level=level, filter=_is_warning_or_error, format=_info_fmt) ================================================ FILE: omg/get/__init__.py ================================================ ================================================ FILE: omg/get/complete.py ================================================ from omg.must_gather.RDEFS import RDEFS from omg.must_gather.get_rdef import get_generated_rdefs from omg.get.get_resources import get_all_resource_names from omg.get.parse import parse_get_args, ParseError from omg.config import config from omg.utils.dget import dget from loguru import logger as lg def _suggest_type(incomplete_type): """ Match type based on incomplete string """ all_rdefs = [] all_rdefs.extend(RDEFS) all_rdefs.extend(get_generated_rdefs()) all_types = set() for rdef in all_rdefs: singular = dget(rdef, ["singular"]) plural = dget(rdef, ["plural"]) # shortNames = dget(rdef, ["shortNames"]) group = dget(rdef, ["group"]) if group != "core": all_types.add(plural + "." + group) else: all_types.add(singular) all_types.add(plural) # if shortNames: # all_types.update(shortNames) match = [f for f in all_types if f.startswith(incomplete_type)] return match def complete_get(ctx, args, incomplete): """ Pull out objects args from Click context and return completions. """ lg.remove() try: cfg = config.get() project = dget(cfg, ["project"]) namespace = ctx.params.get("namespace") or project objects = ctx.params.get("objects") if "/" in incomplete: # We're completing something like `oc get pod/`. in_rtype = incomplete.split("/")[0] in_rname = incomplete.split("/")[1] names = get_all_resource_names({in_rtype: []}, namespace) return [ in_rtype + "/" + n for n in names if n.startswith(in_rname) and in_rtype + "/" + n not in objects ] if "," in incomplete or [o for o in objects if "," in o]: # This is a NOP like oc return [] slash_mode = False comma_mode = False if objects: try: parsed_objects = parse_get_args(objects) except ParseError: return [] else: slash_mode = all("/" in o for o in objects) comma_mode = all("," in o for o in objects) # First arg after get, autocomplete type # or autocompleting after existing slash-notation arg if not objects or slash_mode: if slash_mode: add_slash = "/" else: add_slash = "" sugg = _suggest_type(incomplete) return [s + add_slash for s in sugg] if not slash_mode and not comma_mode and len(parsed_objects) > 0: # Autocomplete resource names based on the type: oc get pod mypod1 mypod2 names = get_all_resource_names(parsed_objects, namespace) return [n for n in names if n.startswith(incomplete) and n not in objects] # Catch all return [] except Exception: # Swallow any exception return [] ================================================ FILE: omg/get/get.py ================================================ from loguru import logger as lg from omg.get.parse import parse_get_args, ParseError from omg.config import config from omg.get.output.o_raw import o_raw from omg.get.output.o_table import o_table from omg.utils.dget import dget from omg.get.get_resources import get_all_resources def cmd(objects, output, show_labels): lg.debug("FUNC_INIT: {}".format(locals())) # Parse objects try: parsed_objects = parse_get_args(objects) except ParseError as e: lg.error(e) return 2 lg.debug("parsed_objects: {}".format(parsed_objects)) # Set namespace ns = dget(config.get(), ["project"]) lg.debug("Namespace resolved to: {}".format(ns)) # Collect resources all_res_d = get_all_resources(parsed_objects, ns) # No resource type found e.g: # all_res_d == [{}, {}, .... ] if not any(all_res_d): lg.error("Unkown resource type") return 2 # Resource type found, but no resources found e.g: # [{'pods': []}, {'pods': []}, ....] if not any([bool(all_res_d[i][rtype]) for i in all_res_d for rtype in all_res_d[i]]): print("No resources found") return 2 # Pass the parsed object to respective output function if output in ["yaml", "json", "name"]: o_raw(all_res_d, output) elif output is None or output == "wide": o_table(all_res_d, ns, output, show_labels) else: lg.error("Unknow output type: {}".format(output)) ================================================ FILE: omg/get/get_resources.py ================================================ from loguru import logger as lg from omg.config import config from omg.utils.dget import dget from omg.must_gather.load_resources import load_res from omg.must_gather.exceptions import NameSpaceRequired, UnkownResourceType def get_all_resources(parsed_objects, ns=None): """Get resources from all paths Args: parsed_objects (dict): Parsed object ns (string): Namespace/project Returns: list: for each r_type, list of resources from each path (list of dict of list) For example: [ # resources_from_path1 { 'pod': [ res1, res2 ... ], 'svc': [ res1, ... ], ... }, # resources_from_path2 ... ] """ lg.debug("FUNC_INIT: {}".format(locals())) cfg = config.get() paths = cfg["paths"] # Resources dicts from selected paths # resd_from_paths = [] resd_from_paths = {} i = 0 for path in paths: i += 1 resd = {} for r_type in parsed_objects: r_names = parsed_objects[r_type] try: res = load_res(path, r_type, r_names, ns) except NameSpaceRequired as e: lg.error(e) raise SystemExit(1) except UnkownResourceType: lg.error("Unknow resource type: {}".format(r_type)) raise SystemExit(1) else: resd[r_type] = res # resd_from_paths.append(resd) resd_from_paths[i] = resd return resd_from_paths def get_all_resource_names(parsed_objects, ns=None): resd_from_paths = get_all_resources(parsed_objects, ns) all_names = [] for i, path_resd in resd_from_paths.items(): for r_type in path_resd: res = path_resd[r_type] if res: for r in res: name = dget(r, ["res", "metadata", "name"]) if name: all_names.append(name) return all_names ================================================ FILE: omg/get/output/__init__.py ================================================ ================================================ FILE: omg/get/output/build_table.py ================================================ from importlib import import_module from loguru import logger as lg from omg.utils.dget import dget from omg.utils.age import age def _col_ns(res): return dget(res, ["res", "metadata", "namespace"], "") def _col_name(res): return dget(res, ["res", "metadata", "name"], "") def _col_name_wtype(res): group = dget(res, ["rdef", "group"]) singular = dget(res, ["rdef", "singular"]) if group == "core": out_type = singular else: out_type = str(singular) + "." + str(group) name = dget(res, ["res", "metadata", "name"], "") return "{}/{}".format(out_type, name) def _col_age(res): pod_ct = dget(res, ["res", "metadata", "creationTimestamp"]) yfile_ts = dget(res, ["yfile_ts"]) return age(pod_ct, yfile_ts) def _col_labels(res): lab = dget(res, ["res", "metadata", "labels"]) if lab: return ",".join(["{}={}".format(k, v) for k, v in lab.items()]) else: return "" def build_table(res, ns, output, show_type, show_labels): lg.debug("FUNC_INIT: {}".format(locals())) rdef = dget(res[0], ["rdef"]) # Get columns for the type of resources we are building table for # If we find the matching module in table_modules we will use that # Otherwise the default NAME and AGE columns will be used. kind = dget(rdef, ["kind"]) try: table_mod = import_module("omg.get.output.table_modules.{}".format(kind)) def_cols = table_mod.DEFAULT_COLUMNS wid_cols = table_mod.WIDE_COLUMNS except ModuleNotFoundError: def_cols = { "NAME": None, "AGE": None } wid_cols = {} pass # Header and respective header functions # We build the table header in header array and alongside, # populate the respective functions for that column in head_f array header = [] head_f = [] scope = dget(rdef, ["scope"]) # Populate NAME/AGE in default column dict if dget(def_cols, ["NAME"], "") is None: if show_type: def_cols["NAME"] = _col_name_wtype else: def_cols["NAME"] = _col_name if dget(def_cols, ["AGE"], "") is None: def_cols["AGE"] = _col_age # Go over default/wide column dicts and populate # header and header_fn. Namespace and Labels are added # (first and last respectively) if needed if ns == "_all" and scope == "Namespaced": header.append("NAMESPACE") head_f.append(_col_ns) for hd, fn in def_cols.items(): header.append(hd) head_f.append(fn) if output == "wide": for hd, fn in wid_cols.items(): header.append(hd) head_f.append(fn) if show_labels: header.append("LABELS") head_f.append(_col_labels) # Iterate over resources and call the header function # to build the table body body = [] for r in res: row = [] for hf in head_f: try: row.append(hf(r)) except Exception as e: lg.debug("table cell execption: {}".format(e)) row.append("?Unknown?") body.append(row) return [header] + body ================================================ FILE: omg/get/output/o_raw.py ================================================ from loguru import logger as lg from omg.config import config from omg.utils.dget import dget import yaml import json def o_raw(resd_from_paths, output): lg.debug("FUNC_INIT: {}".format(locals())) cfg = config.get() paths = cfg["paths"] for i, path_resd in resd_from_paths.items(): all_res = [] for r_type in path_resd: res = path_resd[r_type] if res: all_res.extend(res) if all_res: if len(all_res) == 1: out_res = dget(all_res[0], ["res"]) elif len(all_res) > 1: out_res = { "apiVersion": "v1", "kind": "List", "items": [dget(res, ["res"]) for res in all_res] } else: continue if output == "yaml": print(yaml.dump(out_res)) elif output == "json": print(json.dumps(out_res)) elif output == "name": for res in all_res: group = dget(res, ["rdef", "group"]) singular = dget(res, ["rdef", "singular"]) if group == "core": out_type = singular else: out_type = str(singular) + "." + str(group) name = dget(res, ["res", "metadata", "name"]) print( str(out_type) + "/" + str(name) ) if (len(paths) > 1): lg.opt(colors=True).success("^^^[{}]^^^\n".format(i)) ================================================ FILE: omg/get/output/o_table.py ================================================ from tabulate import tabulate from loguru import logger as lg from os import getenv from omg.config import config from omg.get.output.build_table import build_table def o_table(resd_from_paths, ns, output, show_labels): """Handles table output. Both simple (without -o) and wide (-o wide) Args: parsed_objects (dict): Contains parsed dictionary of objects to get. This dict is the one we get from parse.py module. ns (str): Namespace is needed if we are showing output for all-namespaces. output (str): This is passed from click (-o). We need to know if the output is simple (-o not set) or wide (-o wide). show_labels (bool): This is passed from click (--show-labels) """ lg.debug("FUNC_INIT: {}".format(locals())) cfg = config.get() paths = cfg["paths"] tablefmt = getenv("OMG_TABLE_FMT") or "plain" show_type = False if max([len(resd_from_paths[i]) for i in resd_from_paths]) > 1: show_type = True for i, path_resd in resd_from_paths.items(): table_all_res = None for r_type in path_resd: res = path_resd[r_type] if res: res_table = build_table(res, ns, output, show_type, show_labels) if table_all_res: table_all_res += [[""]] + res_table else: table_all_res = res_table if table_all_res: print(tabulate(table_all_res, tablefmt=tablefmt)) if (len(paths) > 1): lg.opt(colors=True).success("^^^[{}]^^^\n".format(i)) ================================================ FILE: omg/get/output/table_modules/Build.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget from omg.utils.age import age def _col_type(res): return dget(res, ["res", "spec", "strategy", "type"], "Unknown") def _col_from(res): return dget(res, ["res", "spec", "source", "type"], "Unknown") def _col_status(res): return dget(res, ["res", "status", "phase"], "Unknown") def _col_started(res): stt = dget(res, ["res", "status", "startTimestamp"]) if stt: yfile_ts = dget(res, ["yfile_ts"]) return age(stt, yfile_ts) def _col_duration(res): dur = dget(res, ["res", "status", "duration"]) if dur: return str(int(dur/1000000000)) + "s" # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "TYPE": _col_type, "FROM": _col_from, "STATUS": _col_status, "STARTED": _col_started, "DURATION": _col_duration } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { } ================================================ FILE: omg/get/output/table_modules/BuildConfig.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget def _col_type(res): return dget(res, ["res", "spec", "strategy", "type"], "Unknown") def _col_from(res): return dget(res, ["res", "spec", "source", "type"], "Unknown") def _col_latest(res): return dget(res, ["res", "status", "lastVersion"], "Unknown") # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "TYPE": _col_type, "FROM": _col_from, "LATEST": _col_latest } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { } ================================================ FILE: omg/get/output/table_modules/CSIDriver.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget def _col_attachrequired(res): return dget(res, ["res", "spec", "attachRequired"], "Unknown") def _col_podinfoonmount(res): return dget(res, ["res", "spec", "podInfoOnMount"], "Unknown") def _col_modes(res): return ",".join(dget(res, ["res", "spec", "volumeLifecycleModes"], [])) # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "ATTACHREQUIRED": _col_attachrequired, "PODINFOONMOUNT": _col_podinfoonmount, "MODES": _col_modes, "AGE": None } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { } ================================================ FILE: omg/get/output/table_modules/CSINode.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget def _col_drivers(res): drivers = dget(res, ["res", "spec", "drivers"]) if drivers: return len(drivers) return "0" # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "DRIVERS": _col_drivers, "AGE": None } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { } ================================================ FILE: omg/get/output/table_modules/CatalogSource.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget def _col_display(res): return dget(res, ["res", "spec", "displayName"]) def _col_type(res): return dget(res, ["res", "spec", "sourceType"]) def _col_publisher(res): return dget(res, ["res", "spec", "publisher"]) # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "DISPLAY": _col_display, "TYPE": _col_type, "PUBLISHER": _col_publisher, "AGE": None } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { } ================================================ FILE: omg/get/output/table_modules/CephCluster.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget def _col_datadirhostpath(res): return dget(res, ["res", "spec", "dataDirHostPath"], "Unknown") def _col_moncount(res): return dget(res, ["res", "spec", "mon", "count"], "Unknown") def _col_phase(res): return dget(res, ["res", "status", "phase"], "Unknown") def _col_message(res): return dget(res, ["res", "status", "message"], "Unknown") def _col_health(res): return dget(res, ["res", "status", "ceph", "health"], "Unknown") def _col_external(res): return dget(res, ["res", "spec", "external", "enable"], "") # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "DATADIRHOSTPATH": _col_datadirhostpath, "MONCOUNT": _col_moncount, "AGE": None, "PHASE": _col_phase, "MESSAGE": _col_message, "HEALTH": _col_health, "EXTERNAL": _col_external } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { } ================================================ FILE: omg/get/output/table_modules/CephFilesystem.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget def _col_activemds(res): return dget(res, ["res", "spec", "metadataServer", "activeCount"], "Unknown") def _col_phase(res): return dget(res, ["res", "status", "phase"], "Unknown") # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "ACTIVEMDS": _col_activemds, "AGE": None, "PHASE": _col_phase, } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { } ================================================ FILE: omg/get/output/table_modules/CertificateSigningRequest.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget def _col_signername(res): return dget(res, ["res", "spec", "signerName"], "") def _col_requestor(res): return dget(res, ["res", "spec", "username"], "") def _col_condition(res): conds = dget(res, ["res", "status", "conditions"]) if conds: return ",".join([c["type"] for c in conds]) return "Pending" # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "AGE": None, "SIGNERNAME": _col_signername, "REQUESTOR": _col_requestor, "CONDITION": _col_condition } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { } ================================================ FILE: omg/get/output/table_modules/ClusterOperator.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget from omg.utils.age import age def _col_version(res): vers = dget(res, ["res", "status", "versions"]) if vers: operator_v = [v["version"] for v in vers if v["name"] == "operator"] if operator_v: return operator_v[0] return "" def _col_available(res): conds = dget(res, ["res", "status", "conditions"]) if conds: available = [c["status"] for c in conds if c["type"] == "Available"] if available: return available[0] return "Unknown" def _col_progressing(res): conds = dget(res, ["res", "status", "conditions"]) if conds: prog = [c["status"] for c in conds if c["type"] == "Progressing"] if prog: return prog[0] return "Unknown" def _col_degraded(res): conds = dget(res, ["res", "status", "conditions"]) if conds: degraded = [c["status"] for c in conds if c["type"] == "Degraded"] if degraded: return degraded[0] return "Unknown" def _col_since(res): conds = dget(res, ["res", "status", "conditions"]) if conds: ltt = [c["lastTransitionTime"] for c in conds if c["type"] == "Available"] if ltt: yfile_ts = dget(res, ["yfile_ts"]) return age(ltt[0], yfile_ts) return "Unknown" # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "VERSION": _col_version, "AVAILABLE": _col_available, "PROGRESSING": _col_progressing, "DEGRADED": _col_degraded, "SINCE": _col_since } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { } ================================================ FILE: omg/get/output/table_modules/ClusterServiceVersion.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget def _col_display(res): return dget(res, ["res", "spec", "displayName"]) def _col_version(res): return dget(res, ["res", "spec", "version"]) def _col_replaces(res): return dget(res, ["res", "spec", "replaces"]) def _col_phase(res): return dget(res, ["res", "status", "phase"]) # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "DISPLAY": _col_display, "VERSION": _col_version, "REPLACES": _col_replaces, "PHASE": _col_phase } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { } ================================================ FILE: omg/get/output/table_modules/ClusterVersion.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget from omg.utils.age import age def _col_version(res): hist = dget(res, ["res", "status", "history"]) if hist: cluster_v = [h["version"] for h in hist if h["state"] == "Completed"] if cluster_v: return cluster_v[0] return "" def _col_available(res): conds = dget(res, ["res", "status", "conditions"]) if conds: available = [c["status"] for c in conds if c["type"] == "Available"] if available: return available[0] return "Unknown" def _col_progressing(res): conds = dget(res, ["res", "status", "conditions"]) if conds: prog = [c["status"] for c in conds if c["type"] == "Progressing"] if prog: return prog[0] return "Unknown" def _col_since(res): conds = dget(res, ["res", "status", "conditions"]) if conds: ltt = [c["lastTransitionTime"] for c in conds if c["type"] == "Available"] if ltt: yfile_ts = dget(res, ["yfile_ts"]) return age(ltt[0], yfile_ts) return "Unknown" def _col_status(res): conds = dget(res, ["res", "status", "conditions"]) if conds: status = [c["message"] for c in conds if c["type"] == "Progressing"] if status: return status[0] return "Unknown" # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "VERSION": _col_version, "AVAILABLE": _col_available, "PROGRESSING": _col_progressing, "SINCE": _col_since, "STATUS": _col_status } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { } ================================================ FILE: omg/get/output/table_modules/ConfigMap.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget def _col_data(res): return len(dget(res, ["res", "data"], [])) # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "DATA": _col_data, "AGE": None, } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { } ================================================ FILE: omg/get/output/table_modules/CronJob.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget from omg.utils.age import age def _col_schedule(res): return dget(res, ["res", "spec", "schedule"]) def _col_suspend(res): return dget(res, ["res", "spec", "suspend"]) def _col_active(res): return len(dget(res, ["res", "status", "active"], [])) def _col_last_schedule(res): last_sched = dget(res, ["res", "status", "lastScheduleTime"]) if last_sched: return age( last_sched, dget(res, ["yfile_ts"]) ) return "" # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "SCHEDULE": _col_schedule, "SUSPEND": _col_suspend, "ACTIVE": _col_active, "LAST SCHEDULE": _col_last_schedule, "AGE": None } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { } ================================================ FILE: omg/get/output/table_modules/CustomResourceDefinition.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget def _col_created_at(res): return dget(res, ["res", "metadata", "creationTimestamp"], "Unknown") # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "CREATED AT": _col_created_at } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { } ================================================ FILE: omg/get/output/table_modules/DaemonSet.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget def _col_desired(res): return dget(res, ["res", "status", "desiredNumberScheduled"]) def _col_current(res): return dget(res, ["res", "status", "currentNumberScheduled"]) def _col_ready(res): return dget(res, ["res", "status", "numberReady"]) def _col_uptodate(res): return dget(res, ["res", "status", "updatedNumberScheduled"], "0") def _col_available(res): return dget(res, ["res", "status", "numberAvailable"], "0") def _col_node_selector(res): nselector = dget(res, ["res", "spec", "template", "spec", "nodeSelector"], {}) selector = [] for k, v in nselector.items(): selector.append("{}={}".format(k, v)) if selector: return ",".join(selector) else: return "" def _col_containers(res): conts = [c["name"] for c in dget(res, ["res", "spec", "template", "spec", "containers"])] if conts: return ",".join(conts) return "" def _col_images(res): images = [c["image"] for c in dget(res, ["res", "spec", "template", "spec", "containers"])] if images: return ",".join(images) return "" # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "DESIRED": _col_desired, "CURRENT": _col_current, "READY": _col_ready, "UP-TO-DATE": _col_uptodate, "AVAILABLE": _col_available, "NODE SELECTOR": _col_node_selector, "AGE": None, } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { "CONTAINERS": _col_containers, "IMAGES": _col_images, } ================================================ FILE: omg/get/output/table_modules/Deployment.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget def _col_ready(res): replicas = dget(res, ["res", "spec", "replicas"], "?") readyReplicas = dget(res, ["res", "status", "readyReplicas"], "0") return "{}/{}".format(readyReplicas, replicas) def _col_uptodate(res): return dget(res, ["res", "status", "updatedReplicas"], "0") def _col_available(res): return dget(res, ["res", "status", "availableReplicas"], "0") def _col_containers(res): conts = [c["name"] for c in dget(res, ["res", "spec", "template", "spec", "containers"])] if conts: return ",".join(conts) return "" def _col_images(res): images = [c["image"] for c in dget(res, ["res", "spec", "template", "spec", "containers"])] if images: return ",".join(images) return "" def _col_selector(res): labels = dget(res, ["res", "spec", "selector", "matchLabels"]) selector = [] for k, v in labels.items(): selector.append("{}={}".format(k, v)) return ",".join(selector) # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "READY": _col_ready, "UP-TO-DATE": _col_uptodate, "AVAILABLE": _col_available, "AGE": None, } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { "CONTAINERS": _col_containers, "IMAGES": _col_images, "SELECTOR": _col_selector } ================================================ FILE: omg/get/output/table_modules/DeploymentConfig.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget def _col_revision(res): return dget(res, ["res", "status", "latestVersion"]) def _col_desired(res): return dget(res, ["res", "spec", "replicas"]) def _col_current(res): return dget(res, ["res", "status", "readyReplicas"]) def _col_triggered_by(res): triggers = dget(res, ["res", "spec", "triggers"], []) trig_list = [] for trig in triggers: if trig["type"] == "ConfigChange": trig_list.append("config") elif trig["type"] == "ImageChange": img = dget(trig, ["imageChangeParams", "from", "name"]) trig_list.append("image({})".format(img)) else: trig_list.append(str(trig["type"])) return ",".join(trig_list) # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "REVISION": _col_revision, "DESIRED": _col_desired, "CURRENT": _col_current, "TRIGGERED BY": _col_triggered_by, } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { } ================================================ FILE: omg/get/output/table_modules/EndpointSlice.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget def _col_addresstype(res): return dget(res, ["res", "addressType"]) def _col_ports(res): ports = [ str(dget(p, ["port"])) for p in dget(res, ["res", "ports"]) or [] ] port_string = "" if ports: while len(ports) > 0: port = ports.pop() if len(port_string) + len(port) <= 30: if port_string: port_string = ",".join([port_string, port]) else: port_string = port else: port_string = "{} + {} more...".format( port_string, len(ports) + 1 ) return port_string return "" def _col_endpoints(res): addresses = [ addr for ep in dget(res, ["res", "endpoints"]) or [] for addr in dget(ep, ["addresses"]) or [] ] ep_string = "" if addresses: while len(addresses) > 0: ep = addresses.pop() if len(ep_string) + len(ep) <= 30: if ep_string: ep_string = ",".join([ep_string, ep]) else: ep_string = ep else: ep_string = "{} + {} more...".format( ep_string, len(addresses) + 1 ) break return ep_string # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "ADDRESSTYPE": _col_addresstype, "PORTS": _col_ports, "ENDPOINTS": _col_endpoints, "AGE": None } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { } ================================================ FILE: omg/get/output/table_modules/Endpoints.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget def _col_endpoints(res): endpoints = [ "{}:{}".format( dget(addr, ["ip"]), dget(port, ["port"]) ) for subset in dget(res, ["res", "subsets"], []) for addr in dget(subset, ["addresses"], []) for port in dget(subset, ["ports"], []) ] ep_string = "" while len(endpoints) > 0: ep = endpoints.pop() if len(ep_string) + len(ep) <= 40: if ep_string: ep_string = ",".join([ep_string, ep]) else: ep_string = ep else: ep_string = "{} + {} more...".format( ep_string, len(endpoints) + 1 ) break return ep_string # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "ENDPOINTS": _col_endpoints, "AGE": None } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { } ================================================ FILE: omg/get/output/table_modules/Event.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget from omg.utils.age import age def _col_last_seen(res): return age( dget(res, ["res", "lastTimestamp"]), dget(res, ["yfile_ts"]) ) def _col_type(res): return dget(res, ["res", "type"]) def _col_reason(res): return dget(res, ["res", "reason"]) def _col_object(res): obj = "{}/{}".format( dget(res, ["res", "involvedObject", "kind"], ""), dget(res, ["res", "involvedObject", "name"], "") ) if obj == "/": return "" else: return obj def _col_message(res): return dget(res, ["res", "message"], "") # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "LAST SEEN": _col_last_seen, "TYPE": _col_type, "REASON": _col_reason, "OBJECT": _col_object, "MESSAGE": _col_message } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { } ================================================ FILE: omg/get/output/table_modules/HorizontalPodAutoscaler.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget def _col_reference(res): return "{}/{}".format( dget(res, ["res", "spec", "scaleTargetRef", "kind"], ""), dget(res, ["res", "spec", "scaleTargetRef", "name"], "") ) def _col_targets(res): return "{}%/{}%".format( dget(res, ["res", "status", "currentCPUUtilizationPercentage"], "Unknown"), dget(res, ["res", "spec", "targetCPUUtilizationPercentage"], "Unkown") ) def _col_minpods(res): return dget(res, ["res", "spec", "minReplicas"]) def _col_maxpods(res): return dget(res, ["res", "spec", "maxReplicas"]) def _col_replicas(res): return dget(res, ["res", "status", "currentReplicas"]) # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "REFERENCE": _col_reference, "TARGETS": _col_targets, "MINPODS": _col_minpods, "MAXPODS": _col_maxpods, "REPLICAS": _col_replicas, "AGE": None, } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { } ================================================ FILE: omg/get/output/table_modules/HostSubnet.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget def _col_host(res): return dget(res, ["res", "host"]) def _col_ip(res): return dget(res, ["res", "hostIP"]) def _col_subnet(res): return dget(res, ["res", "subnet"]) def _col_cidrs(res): return dget(res, ["res", "egressCIDRs"]) def _col_egress_ips(res): return dget(res, ["res", "egressIPs"]) # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "HOST": _col_host, "HOST IP": _col_ip, "SUBNET": _col_subnet, "EGRESS CIDRS": _col_cidrs, "EGRESS IPS": _col_egress_ips, } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { } ================================================ FILE: omg/get/output/table_modules/ImageStream.py ================================================ # -*- coding: utf-8 -*- from datetime import datetime from omg.utils.dget import dget from dateutil.parser import parse from omg.utils.age import age def _col_image_repository(res): return dget(res, ["res", "status", "publicDockerImageRepository"]) def _col_tags(res): tags = [ tag["tag"] for tag in dget(res, ["res", "status", "tags"], []) if "tag" in tag ] tag_string = "" while len(tags) > 0: t = tags.pop() if len(tag_string) + len(t) <= 30: if tag_string: tag_string = ",".join([tag_string, t]) else: tag_string = t else: tag_string = "{} + {} more...".format( tag_string, len(tags) + 1 ) break return tag_string def _col_updated(res): creation_ts = [] tags = dget(res, ["res", "status", "tags"], []) if tags: for tag in tags: items = dget(tag, ["items"], []) if items: for item in items: created = dget(item, ["created"]) if created: creation_ts.append(created) latest = None if creation_ts: for cts in creation_ts: if isinstance(cts, datetime): cts = cts.isoformat() p_cts = parse(cts) if ( latest is None or p_cts > latest ): latest = p_cts if latest: return age(latest.isoformat(), dget(res, ["yfile_ts"])) # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "IMAGE REPOSITORY": _col_image_repository, "TAGS": _col_tags, "UPDATED": _col_updated } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { } ================================================ FILE: omg/get/output/table_modules/InstallPlan.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget def _col_csv(res): csv = dget(res, ["res", "spec", "clusterServiceVersionNames"]) if csv: return csv[0] def _col_approval(res): return dget(res, ["res", "spec", "approval"]) def _col_approved(res): return dget(res, ["res", "spec", "approved"]) # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "CSV": _col_csv, "APPROVAL": _col_approval, "APPROVED": _col_approved } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { } ================================================ FILE: omg/get/output/table_modules/Job.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget from omg.utils.age import age def _col_completions(res): return "{}/{}".format( dget(res, ["res", "status", "succeeded"], 0), dget(res, ["res", "spec", "completions"], 1) ) def _col_duration(res): st = dget(res, ["res", "status", "startTime"]) ct = dget(res, ["res", "status", "completionTime"]) if st and ct: return age(st, ct, ts1_type="iso", ts2_type="iso") else: return "" # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "COMPLETIONS": _col_completions, "DURATION": _col_duration, "AGE": None, } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { } ================================================ FILE: omg/get/output/table_modules/Machine.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget def _col_phase(res): return dget(res, ["res", "status", "phase"], "") def _col_type(res): return dget(res, ["res", "metadata", "labels", "machine.openshift.io/instance-type"], "") def _col_region(res): return dget(res, ["res", "metadata", "labels", "machine.openshift.io/region"], "") def _col_zone(res): return dget(res, ["res", "metadata", "labels", "machine.openshift.io/zone"], "") # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "PHASE": _col_phase, "TYPE": _col_type, "REGION": _col_region, "ZONE": _col_zone, "AGE": None } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { } ================================================ FILE: omg/get/output/table_modules/MachineConfig.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget def _col_generatedbycontroller(res): return dget(res, [ "res", "metadata", "annotations", "machineconfiguration.openshift.io/generated-by-controller-version"], "") def _col_ignitionversion(res): return dget(res, ["res", "spec", "config", "ignition", "version"], "Unknown") # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "GENERATEDBYCONTROLLER": _col_generatedbycontroller, "IGNITIONVERSION": _col_ignitionversion, "AGE": None } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { } ================================================ FILE: omg/get/output/table_modules/MachineConfigPool.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget def _col_config(res): return dget(res, ["res", "spec", "configuration", "name"], "") def _col_updated(res): conds = dget(res, ["res", "status", "conditions"]) if conds: updated = [c["status"] for c in conds if c["type"] == "Updated"] if updated: return updated[0] return "Unknown" def _col_updating(res): conds = dget(res, ["res", "status", "conditions"]) if conds: updating = [c["status"] for c in conds if c["type"] == "Updating"] if updating: return updating[0] return "Unknown" def _col_degraded(res): conds = dget(res, ["res", "status", "conditions"]) if conds: degraded = [c["status"] for c in conds if c["type"] == "Degraded"] if degraded: return degraded[0] return "Unknown" def _col_machinecount(res): return dget(res, ["res", "status", "machineCount"], "Unknown") def _col_readymachinecount(res): return dget(res, ["res", "status", "readyMachineCount"], "Unknown") def _col_updatedmachinecount(res): return dget(res, ["res", "status", "updatedMachineCount"], "Unknown") def _col_degradedmachinecount(res): return dget(res, ["res", "status", "degradedMachineCount"], "Unknown") # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "CONFIG": _col_config, "UPDATED": _col_updated, "UPDATING": _col_updating, "DEGRADED": _col_degraded, "MACHINECOUNT": _col_machinecount, "READYMACHINECOUNT": _col_readymachinecount, "UPDATEDMACHINECOUNT": _col_updatedmachinecount, "DEGRADEDMACHINECOUNT": _col_degradedmachinecount, "AGE": None } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { } ================================================ FILE: omg/get/output/table_modules/MachineSet.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget def _col_desired(res): return dget(res, ["res", "spec", "replicas"], "") def _col_current(res): return dget(res, ["res", "status", "replicas"], "") def _col_ready(res): return dget(res, ["res", "status", "readyReplicas"], "") def _col_available(res): return dget(res, ["res", "status", "availableReplicas"], "") # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "DESIRED": _col_desired, "CURRENT": _col_current, "READY": _col_ready, "AVAILABLE": _col_available, "AGE": None } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { } ================================================ FILE: omg/get/output/table_modules/MutatingWebhookConfiguration.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget def _col_webhooks(res): return len(dget(res, ["res", "webhooks"])) # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "WEBHOOKS": _col_webhooks, "AGE": None, } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { } ================================================ FILE: omg/get/output/table_modules/Namespace.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget def _col_disp_name(res): return dget(res, ["res", "metadata", "annotations", "openshift.io/display-name"], "") def _col_status(res): return dget(res, ["res", "status", "phase"], "") # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by _build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "DISPLAY NAME": _col_disp_name, "STATUS": _col_status, } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { } ================================================ FILE: omg/get/output/table_modules/NetNamespace.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget def _col_netid(res): return dget(res, ["res", "netid"]) def _col_egress_ips(res): return dget(res, ["res", "egressIPs"]) # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "NETID": _col_netid, "EGRESS IPS": _col_egress_ips } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { } ================================================ FILE: omg/get/output/table_modules/NetworkPolicy.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget def _col_pod_selector(res): selectors = [] # matchExpressions me = dget(res, ["res", "spec", "podSelector", "matchExpressions"], []) for exp in me: selectors.append( "{} {} ({})".format( dget(exp, ["key"]), dget(exp, ["operator"]).lower(), ",".join(dget(exp, ["values"], [])) ) ) # matchLabels ml = dget(res, ["res", "spec", "podSelector", "matchLabels"], {}) for k, v in ml.items(): selectors.append("{}={}".format(k, v)) if selectors: return ",".join(selectors) else: return "" # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "POD-SELECTOR": _col_pod_selector, "AGE": None } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { } ================================================ FILE: omg/get/output/table_modules/Node.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget def _col_status(res): status = "Unknown" conds = dget(res, ["res", "status", "conditions"]) if conds: for c in conds: if dget(c, ["type"]) == "Ready": if dget(c, ["status"]) == "True": status = "Ready" elif dget(c, ["status"]) == "False": status = "NotReady" if dget(res, ["res", "spec", "unschedulable"]): status += ",SchedulingDisabled" return status def _col_roles(res): roles = [] labels = dget(res, ["res", "metadata", "labels"]) if labels: for label in labels: if label.startswith("node-role.kubernetes.io/"): roles.append(label.split("/")[1]) return ",".join(roles) def _col_version(res): return dget( res, ["res", "status", "nodeInfo", "kubeletVersion"], "Unknown" ) def _col_iip(res): iip = "" addresses = dget(res, ["res", "status", "addresses"]) if addresses: for adr in addresses: if dget(adr, ["type"]) == "InternalIP": iip = dget(adr, ["address"]) break return iip def _col_eip(res): eip = "" addresses = dget(res, ["res", "status", "addresses"]) if addresses: for adr in addresses: if dget(adr, ["type"]) == "ExternalIP": eip = dget(adr, ["address"]) break return eip def _col_osimg(res): return dget( res, ["res", "status", "nodeInfo", "osImage"], "Unknown" ) def _col_kerver(res): return dget( res, ["res", "status", "nodeInfo", "kernelVersion"], "Unknown" ) def _col_crt(res): return dget( res, ["res", "status", "nodeInfo", "containerRuntimeVersion"], "Unknown" ) # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "STATUS": _col_status, "ROLES": _col_roles, "AGE": None, "VERSION": _col_version } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { "INTERNAL-IP": _col_iip, "EXTERNAL-IP": _col_eip, "OS-IMAGE": _col_osimg, "KERNEL-VERSION": _col_kerver, "CONTAINER-RUNTIME": _col_crt, } ================================================ FILE: omg/get/output/table_modules/PersistentVolume.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget def _col_capacity(res): return dget(res, ["res", "spec", "capacity", "storage"]) def _col_access_modes(res): am = dget(res, ["res", "spec", "accessModes"], []) return ",".join([ a .replace("Read", "R") .replace("Write", "W") .replace("Many", "X") .replace("Once", "O") for a in am ]) def _col_reclaim_policy(res): return dget(res, ["res", "spec", "persistentVolumeReclaimPolicy"], "Unknown") def _col_status(res): return dget(res, ["res", "status", "phase"], "") def _col_claim(res): claim = "{}/{}".format( dget(res, ["res", "spec", "claimRef", "namespace"], ""), dget(res, ["res", "spec", "claimRef", "name"], "") ) if claim == "/": return "" else: return claim def _col_storageclass(res): return dget(res, ["res", "spec", "storageClassName"], "") def _col_reason(res): return dget(res, ["res", "status", "reason"], "") # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "CAPACITY": _col_capacity, "ACCESS MODES": _col_access_modes, "RECLAIM POLICY": _col_reclaim_policy, "STATUS": _col_status, "CLAIM": _col_claim, "STORAGECLASS": _col_storageclass, "REASON": _col_reason, "AGE": None } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { } ================================================ FILE: omg/get/output/table_modules/PersistentVolumeClaim.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget def _col_status(res): return dget(res, ["res", "status", "phase"], "") def _col_volume(res): return dget(res, ["res", "spec", "volumeName"], "") def _col_capacity(res): return dget(res, ["res", "status", "capacity", "storage"], "Unkown") def _col_access_modes(res): am = dget(res, ["res", "spec", "accessModes"], []) return ",".join([ a .replace("Read", "R") .replace("Write", "W") .replace("Many", "X") .replace("Once", "O") for a in am ]) def _col_storageclass(res): return dget(res, ["res", "spec", "storageClassName"], "") def _col_volumemode(res): return dget(res, ["res", "spec", "volumeMode"], "Unknow") # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "STATUS": _col_status, "VOLUME": _col_volume, "CAPACITY": _col_capacity, "ACCESS MODES": _col_access_modes, "STORAGECLASS": _col_storageclass, "AGE": None } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { "VOLUMEMODE": _col_volumemode } ================================================ FILE: omg/get/output/table_modules/Pod.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget def _col_ready(res): cont_total = len(dget(res, ["res", "spec", "containers"], "")) cont_ready = len([ r for r in dget(res, ["res", "status", "containerStatuses"], "") if dget(r, ["ready"]) is True ]) return "{}/{}".format(cont_ready, cont_total) def _col_status(res): return dget(res, ["res", "status", "phase"], "") def _col_restarts(res): con_statuses = dget(res, ["res", "status", "containerStatuses"]) if con_statuses: return max([ dget(r, ["restartCount"], 0) for r in con_statuses ]) else: return 0 def _col_ip(res): return dget(res, ["res", "status", "podIP"], "") def _col_node(res): return dget(res, ["res", "spec", "nodeName"]) # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "READY": _col_ready, "STATUS": _col_status, "RESTARTS": _col_restarts, "AGE": None } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { "IP": _col_ip, "NODE": _col_node } ================================================ FILE: omg/get/output/table_modules/ReplicaSet.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget def _col_desired(res): return dget(res, ["res", "spec", "replicas"], "0") def _col_current(res): return dget(res, ["res", "status", "availableReplicas"], "0") def _col_ready(res): replicas = dget(res, ["res", "spec", "replicas"], "?") readyReplicas = dget(res, ["res", "status", "readyReplicas"], "0") return "{}/{}".format(readyReplicas, replicas) def _col_containers(res): conts = [c["name"] for c in dget(res, ["res", "spec", "template", "spec", "containers"])] if conts: return ",".join(conts) return "" def _col_images(res): images = [c["image"] for c in dget(res, ["res", "spec", "template", "spec", "containers"])] if images: return ",".join(images) return "" def _col_selector(res): labels = dget(res, ["res", "spec", "selector", "matchLabels"], {}) selector = [] for k, v in labels.items(): selector.append("{}={}".format(k, v)) return ",".join(selector) # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "DESIRED": _col_desired, "CURRENT": _col_current, "READY": _col_ready, "AGE": None, } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { "CONTAINERS": _col_containers, "IMAGES": _col_images, "SELECTOR": _col_selector } ================================================ FILE: omg/get/output/table_modules/ReplicationController.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget def _col_desired(res): return dget(res, ["res", "status", "replicas"], "0") def _col_current(res): return dget(res, ["res", "status", "fullyLabeledReplicas"], "0") def _col_ready(res): return dget(res, ["res", "status", "readyReplicas"], "0") def _col_containers(res): conts = [c["name"] for c in dget(res, ["res", "spec", "template", "spec", "containers"])] if conts: return ",".join(conts) return "" def _col_images(res): images = [c["image"] for c in dget(res, ["res", "spec", "template", "spec", "containers"])] if images: return ",".join(images) return "" def _col_selector(res): labels = dget(res, ["res", "spec", "selector", "matchLabels"]) selector = [] for k, v in labels.items(): selector.append("{}={}".format(k, v)) return ",".join(selector) # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "DESIRED": _col_desired, "CURRENT": _col_current, "READY": _col_ready, "AGE": None, } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { "CONTAINERS": _col_containers, "IMAGES": _col_images, "SELECTOR": _col_selector } ================================================ FILE: omg/get/output/table_modules/Route.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget def _col_host_port(res): return dget(res, ["res", "spec", "host"]) def _col_path(res): return dget(res, ["res", "spec", "path"]) def _col_services(res): return dget(res, ["res", "spec", "to", "name"]) def _col_port(res): return dget(res, ["res", "spec", "port", "targetPort"], "") def _col_termination(res): return "/".join([ dget(res, ["res", "spec", "tls", "termination"], ""), dget(res, ["res", "spec", "tls", "insecureEdgeTerminationPolicy"], "") ]) def _col_wildcard(res): return dget(res, ["res", "spec", "wildcardPolicy"]) # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "HOST/PORT": _col_host_port, "PATH": _col_path, "SERVICES": _col_services, "PORT": _col_port, "TERMINATION": _col_termination, "WILDCARD": _col_wildcard, "AGE": None, } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { } ================================================ FILE: omg/get/output/table_modules/Secret.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget def _col_type(res): return dget(res, ["res", "type"], "Unkown") def _col_data(res): return len(dget(res, ["res", "data"], "")) # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "TYPE": _col_type, "DATA": _col_data, "AGE": None, } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { } ================================================ FILE: omg/get/output/table_modules/Service.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget def _col_type(res): return dget(res, ["res", "spec", "type"], "Unkown") def _col_cluster_ip(res): return dget(res, ["res", "spec", "clusterIP"], "") def _col_external_ip(res): en = dget(res, ["res", "spec", "externalName"]) if en: return en ei = dget(res, ["res", "spec", "externalIP"]) if ei: return ei return "" def _col_ports(res): return ",".join( "{}/{}".format(p["port"], p["protocol"]) for p in dget(res, ["res", "spec", "ports"], []) ) def _col_selector(res): labels = dget(res, ["res", "spec", "selector"], {}) selector = [] for k, v in labels.items(): selector.append("{}={}".format(k, v)) return ",".join(selector) or "" # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "TYPE": _col_type, "CLUSTER-IP": _col_cluster_ip, "EXTERNAL-IP": _col_external_ip, "PORT(S)": _col_ports, "AGE": None, } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { "SELECTOR": _col_selector } ================================================ FILE: omg/get/output/table_modules/StatefulSet.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget def _col_ready(res): replicas = dget(res, ["res", "status", "replicas"], "?") readyReplicas = dget(res, ["res", "status", "readyReplicas"], "0") return "{}/{}".format(readyReplicas, replicas) def _col_containers(res): conts = [c["name"] for c in dget(res, ["res", "spec", "template", "spec", "containers"])] if conts: return ",".join(conts) return "" def _col_images(res): images = [c["image"] for c in dget(res, ["res", "spec", "template", "spec", "containers"])] if images: return ",".join(images) return "" def _col_selector(res): labels = dget(res, ["res", "spec", "selector", "matchLabels"]) selector = [] for k, v in labels.items(): selector.append("{}={}".format(k, v)) return ",".join(selector) # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "READY": _col_ready, "AGE": None, } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { "CONTAINERS": _col_containers, "IMAGES": _col_images, "SELECTOR": _col_selector } ================================================ FILE: omg/get/output/table_modules/StorageClass.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget def _col_provisioner(res): return dget(res, ["res", "provisioner"]) def _col_reclaimpolicy(res): return dget(res, ["res", "reclaimPolicy"]) def _col_volumebindingmode(res): return dget(res, ["res", "volumeBindingMode"]) def _col_allowvolumeexpansion(res): return dget(res, ["res", "allowVolumeExpansion"], "false") # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "PROVISIONER": _col_provisioner, "RECLAIMPOLICY": _col_reclaimpolicy, "VOLUMEBINDINGMODE": _col_volumebindingmode, "ALLOWVOLUMEEXPANSION": _col_allowvolumeexpansion, "AGE": None, } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { } ================================================ FILE: omg/get/output/table_modules/Subscription.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget def _col_package(res): return dget(res, ["res", "spec", "name"]) def _col_source(res): return dget(res, ["res", "spec", "source"]) def _col_channel(res): return dget(res, ["res", "spec", "channel"]) # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "PACKAGE": _col_package, "SOURCE": _col_source, "CHANNEL": _col_channel } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { } ================================================ FILE: omg/get/output/table_modules/ValidatingWebhookConfiguration.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget def _col_webhooks(res): return len(dget(res, ["res", "webhooks"])) # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "WEBHOOKS": _col_webhooks, "AGE": None, } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { } ================================================ FILE: omg/get/output/table_modules/VirtualMachine.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget def _col_ready(res): conds = dget(res, ["res", "status", "conditions"]) if conds: ready = [c["status"] for c in conds if c["type"] == "Ready"] if ready: return ready[0] return "Unknown" def _col_status(res): return dget(res, ["res", "status", "printableStatus"], "") # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "AGE": None, "STATUS": _col_status, "READY": _col_ready, } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { } ================================================ FILE: omg/get/output/table_modules/VirtualMachineInstance.py ================================================ # -*- coding: utf-8 -*- from omg.utils.dget import dget def _col_ready(res): conds = dget(res, ["res", "status", "conditions"]) if conds: ready = [c["status"] for c in conds if c["type"] == "Ready"] if ready: return ready[0] def _col_phase(res): return dget(res, ["res", "status", "phase"], "") def _col_ip(res): interfaces = dget(res, ["res", "status", "interfaces"]) if interfaces: return interfaces[0]["ipAddresses"][0] def _col_node(res): return dget(res, ["res", "status", "nodeName"]) def _col_live_migratable(res): conds = dget(res, ["res", "status", "conditions"]) if conds: LiveMigratable = [c["status"] for c in conds if c["type"] == "LiveMigratable"] if LiveMigratable: return LiveMigratable[0] def _col_paused(res): conds = dget(res, ["res", "status", "conditions"]) if conds: Paused = [c["status"] for c in conds if c["type"] == "Paused"] if Paused: return Paused[0] # Default columns (without -o wide) # NAME and AGE cols, if present, with None value, # will be handled by build_table function that will # fill them with the common name/age column functions DEFAULT_COLUMNS = { "NAME": None, "AGE": None, "PHASE": _col_phase, "IP": _col_ip, "NODE": _col_node, "READY": _col_ready } # Wide columns (with -o wide) # In addition to the default columns WIDE_COLUMNS = { "LIVE-MIGRATABLE": _col_live_migratable, "PAUSED" : _col_paused } ================================================ FILE: omg/get/parse.py ================================================ # This module handles parsing of the omg's `get` command # i.e, it normalizes whatever is passed after `omg get <....>` # Since omg get can be called in a variety of ways, following is a # detailed description of all the "varities" omg will handle: # # 1- SLASH Notation # Syntax: # omg get Type1/Name1 [Type2/Name2 Type3/Name3 ....] # Examples: # - omg get pod/httpd-sdf32 # - omg get svc/httpd route/httpd # # 2- COMMA Notation # Syntax: # omg get Type1,Type2[,Type3,...] [Name1 Name2 ...] # Examples: # - omg get pods,svc # - omg get svc,route,deployment httpd nginx # # 3- PLAIN # Syntax: # omg get Type [Name1 Name2 Name3] # Examples: # - omg get pods # - omg get nodes node1 node2 # - omg get all # # Note: # Any get request can fall into either one of these syntaxes # A mix of these types will not be supported # What resources to show when `omg get all` is called ALL_TYPES = ['pod', 'rc', 'svc', 'ds', 'deployment', 'rs', 'statefulset', 'hpa', 'job', 'cronjob', 'dc', 'bc', 'build.build.openshift.io', 'is'] class ParseError(Exception): """ Error raised during parsing of `oc get` args. """ pass def _parse_slash(args): """ Parses slash based get args """ objects = [] for arg in args: if '/' not in arg: raise ParseError("Invalid arguments to get") o_split = arg.split('/') r_type = o_split[0] r_name = o_split[1] objects.append((r_type, r_name)) return objects def _parse_comma(args): """ Parses comma based get args """ objects = [] # The first arg contains comma sperated types first = args[0] types = first.split(",") if 'all' in types: types.extend(ALL_TYPES) types.remove("all") # If more than one args are present these are names of objects to get if len(args) > 1: names = args[1:] else: names = [] for t in types: if names: for n in names: objects.append((t, n)) else: objects.append((t, [])) return objects def _parse_plain(args): """ Parses plain get args (e.g, without comma or slash) """ objects = [] # The first arg should be the type first = args[0] if first == 'all': types = tuple(ALL_TYPES) else: types = (first,) # If more than one args are present these are names of objects to get if len(args) > 1: # names are not allowed with "all" if first == 'all': raise ParseError("Resource names not allowed with 'all'") names = args[1:] else: names = [] for t in types: if names: for n in names: objects.append((t, n)) else: objects.append((t, None)) return objects def parse_get_args(objects): """ Takes a tuple (examples below) of arguments passed to `omg get ...` and parses it. Returns a dict (key: "resource type", value: list("resource names")). Raises ResourceParseError if it runs into any issues. Example input -> output: ('pod', 'httpd') -> {'pod': ['httpd']} ('pods', 'httpd1', 'httpd2') -> {'pod': ['httpd1', 'httpd2']} ('dc/httpd', 'pod/httpd1') -> {'dc': ['httpd'], 'pod': ['httpd1']} ('routes') -> {'routes': []} ('pod,svc') -> {'pod': [], 'svc': []} ('svc,route','httpd','nginx') -> {'svc': ['httpd', 'nginx'], 'route': ['httpd', 'nginx']} """ parsed_resources = {} if not objects: raise ParseError("Empty arguments to get") # Determine the type of args from the first arg first = objects[0] if '/' in first: parsed_objects = _parse_slash(objects) elif ',' in first: parsed_objects = _parse_comma(objects) else: parsed_objects = _parse_plain(objects) for r_type, r_name in parsed_objects: if r_type not in parsed_resources: parsed_resources[r_type] = [] if r_name: parsed_resources[r_type].append(r_name) return parsed_resources ================================================ FILE: omg/log/__init__.py ================================================ ================================================ FILE: omg/log/complete.py ================================================ from omg.config import config from omg.utils.dget import dget import os from loguru import logger as lg def complete_pods(ctx, args, incomplete): """ Callback for pod name (within a ns) autocompletion :return: List of matching pod names or empty list. """ lg.remove() cfg = config.get() c_paths = dget(cfg, ["paths"]) c_project = dget(cfg, ["project"]) ns = ctx.params.get("namespace") or c_project suggestions = [] for path in c_paths: pod_dir = os.path.join(path, "namespaces", ns, "pods") if os.path.isdir(pod_dir): pod_listing = os.listdir(pod_dir) if pod_listing: suggestions.extend([pod for pod in pod_listing if incomplete in pod]) return suggestions def complete_containers(ctx, args, incomplete): """ Callback for container name (within a pod and ns) autocompletion :return: List of matching container names or empty list """ lg.remove() cfg = config.get() c_paths = dget(cfg, ["paths"]) c_project = dget(cfg, ["project"]) if ( len(ctx.args) != 1 ): # If there's no pod specified yet, can't autocomplete a container name return [] ns = ctx.params.get("namespace") or c_project pod = ctx.args[0] container_listing = [] for path in c_paths: container_dir = os.path.join(path, "namespaces", ns, "pods", pod) if os.path.isdir(container_dir): containers = os.listdir(container_dir) if containers: container_listing.extend(containers) suggestions = [ c for c in container_listing if incomplete in c and not c.endswith(".yaml") ] # skip .yaml files return suggestions ================================================ FILE: omg/log/log.py ================================================ import os from loguru import logger as lg from omg.config import config from omg.utils.dget import dget def cmd(resource, container, previous): lg.debug("FUNC_INIT: {}".format(locals())) cfg = config.get() paths = dget(cfg, ["paths"]) ns = dget(cfg, ["project"]) if not paths: lg.error("No must-gather selected") raise SystemExit(1) if ns == "_all": lg.error("All Namespaces is not supported with `omg log ...` ") raise SystemExit(1) elif ns is None: lg.error("No namespace/project selected") raise SystemExit(1) if "/" in resource: r_type = resource.split("/")[0] pod = resource.split("/")[1] if r_type not in ["pod", "pods"]: lg.error("Can not print logs of type:", r_type) raise SystemExit(1) else: pod = resource if not ns: lg.error("Namespace/Project not set") raise SystemExit(1) log_files = [] for path in paths: proj_path = os.path.join(path, "namespaces", ns) if not os.path.isdir(proj_path): continue pod_dir = os.path.join(proj_path, "pods", pod) if not os.path.isdir(pod_dir): # lg.warning("Pod directory not found: {}".format(pod_dir)) continue con_dirs = [ c for c in os.listdir(pod_dir) if os.path.isdir(os.path.join(pod_dir, c)) ] if not con_dirs: lg.warning("No container directory not found in {}".format(pod_dir)) continue elif len(con_dirs) == 1: con_dir = con_dirs[0] if container and container != con_dir: lg.warning("Container directory {} not found in {}".format( container, pod_dir)) continue elif len(con_dirs) > 1: if container is None: lg.error( "This pod has more than one containers:" + str(con_dirs) + "\n" "Use -c/--container to specify the container" ) raise SystemExit(1) elif container not in con_dirs: lg.warning("Container directory {} not found in {}".format( container, pod_dir)) continue else: con_dir = container if previous: log_files.append( os.path.join(pod_dir, con_dir, con_dir, "logs", "previous.log") ) else: log_files.append( os.path.join(pod_dir, con_dir, con_dir, "logs", "current.log") ) if not log_files: lg.error("No log files found") for logfile in log_files: if not os.path.isfile(logfile): lg.warning("Log file not found: {}".format(logfile)) else: lg.info(logfile) with open(logfile, "r") as lf: print(lf.read()) if len(log_files) > 1: print("") print("~~~") print("") ================================================ FILE: omg/machine_config/__init__.py ================================================ ================================================ FILE: omg/machine_config/compare.py ================================================ import difflib from loguru import logger as lg from omg.get.get_resources import get_all_resources from omg.machine_config.decode_content import decode def mc_compare(m, show_contents): # NOTE TO SELF: Recursion has gone out of hand, # probably re-impelement the comparison logic without # using recursion if len(m) != 2: lg.error("Provide two machine-configs to compare") raise SystemExit(1) try: two_mcs = [] for mc_name in m: all_mcs = get_all_resources({"mc": [mc_name]}) matched_mcs = [] for i, mc_res in all_mcs.items(): for _, mc_data_l in mc_res.items(): if mc_data_l: for mc_data in mc_data_l: matched_mcs.append(mc_data["res"]) if not matched_mcs: raise Exception("MachineConfig {} not found".format(mc_name)) elif len(matched_mcs) > 1: raise Exception( "More than one MachineConfig matched for {}\n" "Use --path/-P to select a single must-gather path" .format(mc_name) ) else: two_mcs.append(matched_mcs[0]) mc1 = two_mcs[0] mc2 = two_mcs[1] except Exception as e: lg.error(e) raise SystemExit(1) # Recursive function to show diff when --show-contents is set # We either get both strings in d1 and d2 ([*CHANGE]), or # we get on empty string on one and a dict on other ([+ADDED], [-REMOVED]) def show_diff(d1, d2, indent=1, show_contents=show_contents): # print(type(d1)) # print(type(d2)) if show_contents: if type(d1) in [str, int, bool] and type(d2) in [str, int, bool]: if str(d1).startswith("data:"): data1 = decode(str(d1)) else: data1 = str(d1) if str(d2).startswith("data:"): data2 = decode(str(d2)) else: data2 = str(d2) # Add new line at the end if missing if data1[-1:] != "\n" or data2[-1:] != "\n": if data1 != "": data1 += "\n" if data2 != "": data2 += "\n" diff = "".join( difflib.ndiff( data1.splitlines(keepends=True), data2.splitlines(keepends=True) ) ) for x in diff.splitlines(): print(" " * indent + x) print("") elif type(d1) is dict and d2 == "": if len(d1) == 0: show_diff("{}", "", indent) for key in d1: print(" " * indent + "-> " + key) show_diff(d1[key], "", indent + 1) elif type(d2) is dict and d1 == "": if len(d2) == 0: show_diff("", "{}", indent) else: for key in d2: print(" " * indent + "-> " + key) show_diff("", d2[key], indent + 1) # Recursive function to walk through two machine-configs, # and find differences between them def mc_diff(d1, d2, path=[]): # The two values are equal, nothing to do if d1 == d2: return # One of the two values is None elif d1 is None: print("[+ADDED]", " -> ".join(path), "\n") show_diff("", d2) elif d2 is None: print("[-REMOVED]", " -> ".join(path), "\n") show_diff(d1, "") # The two values are string/int/bool which are not equal elif ( (type(d1) is str and type(d2) is str) or (type(d1) is int and type(d2) is int) or (type(d1) is bool and type(d2) is bool) ): print("[*CHANGE]", " -> ".join(path), "\n") show_diff(str(d1), str(d2)) # The two values are dict which are not equal elif type(d1) is dict and type(d2) is dict: for k in set(list(d1.keys()) + list(d2.keys())): path.append(k) if k not in d2: mc_diff(d1[k], None, path) elif k not in d1: mc_diff(None, d2[k]) else: mc_diff(d1[k], d2[k], path) path.pop() # The two values are lists which are not equal # We need to compare the two lists with some extended logic elif type(d1) is list and type(d2) is list: # The two lists contain different types of data ltypes = set([type(x) for x in d1 + d2]) if len(ltypes) != 1: print("[WARNING] skipping inconsistent list: ", path) print(" Found mix types in list: ", ltypes) return done_lod_keys = [] # Traverse on both the list items for l in d1 + d2: # noqa # If "list of dict" with kind/name/path keys, # we compare based on kind/name/path keys in the dicts if type(l) is dict and ("name" in l or "path" in l or "kind" in l): if "kind" in l: lod_key = "kind" elif "name" in l: lod_key = "name" elif "path" in l: lod_key = "path" path.append(l[lod_key]) ld1 = [x for x in d1 if x[lod_key] == l[lod_key]] ld2 = [x for x in d2 if x[lod_key] == l[lod_key]] if len(ld1) > 1 and l[lod_key] not in done_lod_keys: print( " [WARNING] Duplicate (%i) entries found in " "1st MachineConfig for %s:%s" % (len(ld1), lod_key, l[lod_key]) ) if len(ld2) > 1 and l[lod_key] not in done_lod_keys: print( " [WARNING] Duplicate (%i) entries found in " "2nd MachineConfig for %s:%s" % (len(ld2), lod_key, l[lod_key]) ) if len(ld1) == 0: mc_diff(None, ld2[-1], path) elif len(ld2) == 0: mc_diff(ld1[-1], None, path) elif l[lod_key] not in done_lod_keys: mc_diff(ld1[-1], ld2[-1], path) done_lod_keys.append(l[lod_key]) path.pop() else: if l not in d2: mc_diff(l, None, path) if l not in d1: mc_diff(None, l, path) else: print("[WARNING] Unhandled condition at", path) mc_diff(mc1, mc2) ================================================ FILE: omg/machine_config/decode_content.py ================================================ from base64 import b64decode from cryptography import x509 from cryptography.hazmat.backends import default_backend from urllib.parse import unquote def decode(content): """ Decodes url/bas64 encoded content found in machine-configs Certificate data is also converted to human readable format """ split = content.split(",", 1) head = split[0] data = split[1] if head.startswith("data:"): if len(data) == 0: return "" form = head[5:].split(";") if "base64" in form: charset = next((x[8:] for x in form if x[0:8] == "charset="), "utf-8") dec_data = b64decode(data).decode(charset) else: dec_data = unquote(data) if dec_data.startswith("-----BEGIN CERTIFICATE-----"): certs = [] cert = [] for cert_line in dec_data.splitlines(): if cert_line != "-----END CERTIFICATE-----": cert.append(cert_line) else: cert.append(cert_line) certs.append("\n".join(cert)) cert = [] dec_certs = [] for c in certs: dec_cert = [] parse_cert = x509.load_pem_x509_certificate( str.encode(c), default_backend() ) dec_cert.append("~~~~~BEGIN CERTIFICATE~~~~~") dec_cert.append("SUBJECT : " + parse_cert.subject.rfc4514_string()) dec_cert.append("ISSUER : " + parse_cert.issuer.rfc4514_string()) dec_cert.append("SERIAL : " + str(parse_cert.serial_number)) dec_cert.append( "NOT BEFORE : " + parse_cert.not_valid_before.isoformat() ) dec_cert.append( "NOT AFTER : " + parse_cert.not_valid_after.isoformat() ) dec_cert.append("~~~~~END CERTIFICATE~~~~~") dec_certs.append("\n".join(dec_cert)) return "\n".join(dec_certs) else: return dec_data else: print('[Warning] Unable to recognize content (not starting with "data:")') return content ================================================ FILE: omg/machine_config/extract.py ================================================ import os import yaml from loguru import logger as lg from omg.config import config from omg.utils.dget import dget from omg.get.get_resources import get_all_resources from omg.machine_config.decode_content import decode def _write_unit(systemd_path, unit): os.makedirs(systemd_path, exist_ok=True) name = unit["name"] if "enabled" in unit: if unit["enabled"] is not True: name += ".disabled" if "content" in unit: abs_fil = os.path.join(systemd_path, name) with open(abs_fil, "w") as fh: print(abs_fil) fh.write(unit["contents"]) def _write_mc(emc_path, mc): lg.debug("Writing MC with keys: {}".format(mc.keys())) lg.trace("{}".format(mc)) mc_name = dget(mc, ["metadata", "name"]) mc_config = dget(mc, ["spec", "config"]) if not (mc_name and mc_config): lg.warning("Skipping invalid MachineConfig") return mc_path = os.path.join(emc_path, mc_name) os.makedirs(mc_path, exist_ok=True) # storage storage = dget(mc, ["spec", "config", "storage"]) if storage: storage_path = os.path.join(mc_path, "storage") if "files" in storage: for fi in storage["files"]: path = fi["path"] rel_fil = path[1:] rel_dir = os.path.dirname(rel_fil) abs_dir = os.path.join(storage_path, rel_dir) abs_fil = os.path.join(storage_path, rel_fil) os.makedirs(abs_dir, exist_ok=True) with open(abs_fil, "w") as fh: print(abs_fil) fh.write(decode(fi["contents"]["source"])) # systemd systemd_u = dget(mc, ["spec", "config", "systemd", "units"]) if systemd_u: for unit in systemd_u: dropins = dget(systemd_u, ["dropins"]) if dropins: systemd_path = os.path.join( mc_path, "systemd/" + dget(unit, ["name"], "") + ".d" ) for d_unit in dropins: _write_unit(systemd_path, d_unit) if dget(unit, ["name"]) and dget(unit, ["contents"]): systemd_path = os.path.join(mc_path, "systemd") _write_unit(systemd_path, unit) # passwd passwd = dget(mc, ["spec", "config", "passwd"]) if passwd: passwd_path = os.path.join(mc_path, "passwd") if "users" in passwd: for user in passwd["users"]: os.makedirs(passwd_path, exist_ok=True) name = user["name"] abs_fil = os.path.join(passwd_path, name) with open(abs_fil, "w") as fh: print(abs_fil) fh.write(yaml.dump(user)) # TODO groups # TODO networkd # TODO directories, links, disks, raid, filesystems def mc_extract(m): cfg = config.get() paths = cfg["paths"] if m: mc_names = list(m) else: mc_names = [] all_mcs = get_all_resources({"mc": mc_names}) # {1: {"mc": [...]}, 2: {"mc": [...] }} for i, mc_res in all_mcs.items(): mg_path = paths[i-1] emc_path = os.path.join(mg_path, "extracted-machine-configs") # {"mc": [{"res": {}, "yfile_ts": "..."}, ... ]} for _, mc_data in mc_res.items(): if mc_data: try: os.makedirs(emc_path, exist_ok=True) except PermissionError as e: lg.warning(e) continue for mc in mc_data: mc_rd = mc["res"] _write_mc(emc_path, mc_rd) ================================================ FILE: omg/must_gather/RDEFS.py ================================================ # Built-in Resource Definitions (rdefs) RDEFS = [ { "kind": "Binding", "singular": "binding", "plural": "bindings", "scope": "Namespaced", "group": "core" }, { "kind": "ComponentStatus", "singular": "componentstatuse", "plural": "componentstatuses", "scope": "Cluster", "shortNames": ["cs"], "group": "core" }, { "kind": "ConfigMap", "singular": "configmap", "plural": "configmaps", "scope": "Namespaced", "shortNames": ["cm"], "group": "core" }, { "kind": "Endpoints", "singular": "endpoint", "plural": "endpoints", "scope": "Namespaced", "shortNames": ["ep"], "group": "core" }, { "kind": "Event", "singular": "event", "plural": "events", "scope": "Namespaced", "shortNames": ["ev"], "group": "core" }, { "kind": "LimitRange", "singular": "limitrange", "plural": "limitranges", "scope": "Namespaced", "shortNames": ["limits"], "group": "core" }, { "kind": "Namespace", "singular": "namespace", "plural": "namespaces", "scope": "Cluster", "shortNames": ["ns"], "group": "core" }, { "kind": "Node", "singular": "node", "plural": "nodes", "scope": "Cluster", "shortNames": ["no"], "group": "core" }, { "kind": "PersistentVolumeClaim", "singular": "persistentvolumeclaim", "plural": "persistentvolumeclaims", "scope": "Namespaced", "shortNames": ["pvc"], "group": "core" }, { "kind": "PersistentVolume", "singular": "persistentvolume", "plural": "persistentvolumes", "scope": "Cluster", "shortNames": ["pv"], "group": "core" }, { "kind": "Pod", "singular": "pod", "plural": "pods", "scope": "Namespaced", "shortNames": ["po"], "group": "core" }, { "kind": "PodTemplate", "singular": "podtemplate", "plural": "podtemplates", "scope": "Namespaced", "group": "core" }, { "kind": "ReplicationController", "singular": "replicationcontroller", "plural": "replicationcontrollers", "scope": "Namespaced", "shortNames": ["rc"], "group": "core" }, { "kind": "ResourceQuota", "singular": "resourcequota", "plural": "resourcequotas", "scope": "Namespaced", "shortNames": ["quota"], "group": "core" }, { "kind": "Secret", "singular": "secret", "plural": "secrets", "scope": "Namespaced", "group": "core" }, { "kind": "ServiceAccount", "singular": "serviceaccount", "plural": "serviceaccounts", "scope": "Namespaced", "shortNames": ["sa"], "group": "core" }, { "kind": "Service", "singular": "service", "plural": "services", "scope": "Namespaced", "shortNames": ["svc"], "group": "core" }, { "kind": "MutatingWebhookConfiguration", "singular": "mutatingwebhookconfiguration", "plural": "mutatingwebhookconfigurations", "scope": "Cluster", "group": "admissionregistration.k8s.io" }, { "kind": "ValidatingWebhookConfiguration", "singular": "validatingwebhookconfiguration", "plural": "validatingwebhookconfigurations", "scope": "Cluster", "group": "admissionregistration.k8s.io" }, { "kind": "CustomResourceDefinition", "singular": "customresourcedefinition", "plural": "customresourcedefinitions", "scope": "Cluster", "shortNames": ["crd", "crds"], "group": "apiextensions.k8s.io" }, { "kind": "APIService", "singular": "apiservice", "plural": "apiservices", "scope": "Cluster", "group": "apiregistration.k8s.io" }, { "kind": "APIRequestCount", "singular": "apirequestcount", "plural": "apirequestcounts", "scope": "Cluster", "group": "apiserver.openshift.io" }, { "kind": "ControllerRevision", "singular": "controllerrevision", "plural": "controllerrevisions", "scope": "Namespaced", "group": "apps" }, { "kind": "DaemonSet", "singular": "daemonset", "plural": "daemonsets", "scope": "Namespaced", "shortNames": ["ds"], "group": "apps" }, { "kind": "Deployment", "singular": "deployment", "plural": "deployments", "scope": "Namespaced", "shortNames": ["deploy"], "group": "apps" }, { "kind": "ReplicaSet", "singular": "replicaset", "plural": "replicasets", "scope": "Namespaced", "shortNames": ["rs"], "group": "apps" }, { "kind": "StatefulSet", "singular": "statefulset", "plural": "statefulsets", "scope": "Namespaced", "shortNames": ["sts"], "group": "apps" }, { "kind": "DeploymentConfig", "singular": "deploymentconfig", "plural": "deploymentconfigs", "scope": "Namespaced", "shortNames": ["dc"], "group": "apps.openshift.io" }, { "kind": "TokenReview", "singular": "tokenreview", "plural": "tokenreviews", "scope": "Cluster", "group": "authentication.k8s.io" }, { "kind": "LocalSubjectAccessReview", "singular": "localsubjectaccessreview", "plural": "localsubjectaccessreviews", "scope": "Namespaced", "group": "authorization.k8s.io" }, { "kind": "SelfSubjectAccessReview", "singular": "selfsubjectaccessreview", "plural": "selfsubjectaccessreviews", "scope": "Cluster", "group": "authorization.k8s.io" }, { "kind": "SelfSubjectRulesReview", "singular": "selfsubjectrulesreview", "plural": "selfsubjectrulesreviews", "scope": "Cluster", "group": "authorization.k8s.io" }, { "kind": "SubjectAccessReview", "singular": "subjectaccessreview", "plural": "subjectaccessreviews", "scope": "Cluster", "group": "authorization.k8s.io" }, { "kind": "ClusterRoleBinding", "singular": "clusterrolebinding", "plural": "clusterrolebindings", "scope": "Cluster", "group": "authorization.openshift.io" }, { "kind": "ClusterRole", "singular": "clusterrole", "plural": "clusterroles", "scope": "Cluster", "group": "authorization.openshift.io" }, { "kind": "LocalResourceAccessReview", "singular": "localresourceaccessreview", "plural": "localresourceaccessreviews", "scope": "Namespaced", "group": "authorization.openshift.io" }, { "kind": "LocalSubjectAccessReview", "singular": "localsubjectaccessreview", "plural": "localsubjectaccessreviews", "scope": "Namespaced", "group": "authorization.openshift.io" }, { "kind": "ResourceAccessReview", "singular": "resourceaccessreview", "plural": "resourceaccessreviews", "scope": "Cluster", "group": "authorization.openshift.io" }, { "kind": "RoleBindingRestriction", "singular": "rolebindingrestriction", "plural": "rolebindingrestrictions", "scope": "Namespaced", "group": "authorization.openshift.io" }, { "kind": "RoleBinding", "singular": "rolebinding", "plural": "rolebindings", "scope": "Namespaced", "group": "authorization.openshift.io" }, { "kind": "Role", "singular": "role", "plural": "roles", "scope": "Namespaced", "group": "authorization.openshift.io" }, { "kind": "SelfSubjectRulesReview", "singular": "selfsubjectrulesreview", "plural": "selfsubjectrulesreviews", "scope": "Namespaced", "group": "authorization.openshift.io" }, { "kind": "SubjectAccessReview", "singular": "subjectaccessreview", "plural": "subjectaccessreviews", "scope": "Cluster", "group": "authorization.openshift.io" }, { "kind": "SubjectRulesReview", "singular": "subjectrulesreview", "plural": "subjectrulesreviews", "scope": "Namespaced", "group": "authorization.openshift.io" }, { "kind": "HorizontalPodAutoscaler", "singular": "horizontalpodautoscaler", "plural": "horizontalpodautoscalers", "scope": "Namespaced", "shortNames": ["hpa"], "group": "autoscaling" }, { "kind": "ClusterAutoscaler", "singular": "clusterautoscaler", "plural": "clusterautoscalers", "scope": "Cluster", "shortNames": ["ca"], "group": "autoscaling.openshift.io" }, { "kind": "MachineAutoscaler", "singular": "machineautoscaler", "plural": "machineautoscalers", "scope": "Namespaced", "shortNames": ["ma"], "group": "autoscaling.openshift.io" }, { "kind": "CronJob", "singular": "cronjob", "plural": "cronjobs", "scope": "Namespaced", "shortNames": ["cj"], "group": "batch" }, { "kind": "Job", "singular": "job", "plural": "jobs", "scope": "Namespaced", "group": "batch" }, { "kind": "BuildConfig", "singular": "buildconfig", "plural": "buildconfigs", "scope": "Namespaced", "shortNames": ["bc"], "group": "build.openshift.io" }, { "kind": "Build", "singular": "build", "plural": "builds", "scope": "Namespaced", "group": "build.openshift.io" }, { "kind": "CertificateSigningRequest", "singular": "certificatesigningrequest", "plural": "certificatesigningrequests", "scope": "Cluster", "shortNames": ["csr"], "group": "certificates.k8s.io" }, { "kind": "CredentialsRequest", "singular": "credentialsrequest", "plural": "credentialsrequests", "scope": "Namespaced", "group": "cloudcredential.openshift.io" }, { "kind": "APIServer", "singular": "apiserver", "plural": "apiservers", "scope": "Cluster", "group": "config.openshift.io" }, { "kind": "Authentication", "singular": "authentication", "plural": "authentications", "scope": "Cluster", "group": "config.openshift.io" }, { "kind": "Build", "singular": "build", "plural": "builds", "scope": "Cluster", "group": "config.openshift.io" }, { "kind": "ClusterOperator", "singular": "clusteroperator", "plural": "clusteroperators", "scope": "Cluster", "shortNames": ["co"], "group": "config.openshift.io" }, { "kind": "ClusterVersion", "singular": "clusterversion", "plural": "clusterversions", "scope": "Cluster", "group": "config.openshift.io" }, { "kind": "Console", "singular": "console", "plural": "consoles", "scope": "Cluster", "group": "config.openshift.io" }, { "kind": "DNS", "singular": "dnse", "plural": "dnses", "scope": "Cluster", "group": "config.openshift.io" }, { "kind": "FeatureGate", "singular": "featuregate", "plural": "featuregates", "scope": "Cluster", "group": "config.openshift.io" }, { "kind": "Image", "singular": "image", "plural": "images", "scope": "Cluster", "group": "config.openshift.io" }, { "kind": "Infrastructure", "singular": "infrastructure", "plural": "infrastructures", "scope": "Cluster", "group": "config.openshift.io" }, { "kind": "Ingress", "singular": "ingresse", "plural": "ingresses", "scope": "Cluster", "group": "config.openshift.io" }, { "kind": "Network", "singular": "network", "plural": "networks", "scope": "Cluster", "group": "config.openshift.io" }, { "kind": "OAuth", "singular": "oauth", "plural": "oauths", "scope": "Cluster", "group": "config.openshift.io" }, { "kind": "OperatorHub", "singular": "operatorhub", "plural": "operatorhubs", "scope": "Cluster", "group": "config.openshift.io" }, { "kind": "Project", "singular": "project", "plural": "projects", "scope": "Cluster", "group": "config.openshift.io" }, { "kind": "Proxy", "singular": "proxie", "plural": "proxies", "scope": "Cluster", "group": "config.openshift.io" }, { "kind": "Scheduler", "singular": "scheduler", "plural": "schedulers", "scope": "Cluster", "group": "config.openshift.io" }, { "kind": "ConsoleCLIDownload", "singular": "consoleclidownload", "plural": "consoleclidownloads", "scope": "Cluster", "group": "console.openshift.io" }, { "kind": "ConsoleExternalLogLink", "singular": "consoleexternalloglink", "plural": "consoleexternalloglinks", "scope": "Cluster", "group": "console.openshift.io" }, { "kind": "ConsoleLink", "singular": "consolelink", "plural": "consolelinks", "scope": "Cluster", "group": "console.openshift.io" }, { "kind": "ConsoleNotification", "singular": "consolenotification", "plural": "consolenotifications", "scope": "Cluster", "group": "console.openshift.io" }, { "kind": "ConsolePlugin", "singular": "consoleplugin", "plural": "consoleplugins", "scope": "Cluster", "group": "console.openshift.io" }, { "kind": "ConsoleQuickStart", "singular": "consolequickstart", "plural": "consolequickstarts", "scope": "Cluster", "group": "console.openshift.io" }, { "kind": "ConsoleYAMLSample", "singular": "consoleyamlsample", "plural": "consoleyamlsamples", "scope": "Cluster", "group": "console.openshift.io" }, { "kind": "PodNetworkConnectivityCheck", "singular": "podnetworkconnectivitycheck", "plural": "podnetworkconnectivitychecks", "scope": "Namespaced", "group": "controlplane.operator.openshift.io" }, { "kind": "Lease", "singular": "lease", "plural": "leases", "scope": "Namespaced", "group": "coordination.k8s.io" }, { "kind": "EndpointSlice", "singular": "endpointslice", "plural": "endpointslices", "scope": "Namespaced", "group": "discovery.k8s.io" }, { "kind": "Event", "singular": "event", "plural": "events", "scope": "Namespaced", "shortNames": ["ev"], "group": "events.k8s.io" }, { "kind": "Ingress", "singular": "ingresse", "plural": "ingresses", "scope": "Namespaced", "shortNames": ["ing"], "group": "extensions" }, { "kind": "FlowSchema", "singular": "flowschema", "plural": "flowschemas", "scope": "Cluster", "group": "flowcontrol.apiserver.k8s.io" }, { "kind": "PriorityLevelConfiguration", "singular": "prioritylevelconfiguration", "plural": "prioritylevelconfigurations", "scope": "Cluster", "group": "flowcontrol.apiserver.k8s.io" }, { "kind": "HelmChartRepository", "singular": "helmchartrepositorie", "plural": "helmchartrepositories", "scope": "Cluster", "group": "helm.openshift.io" }, { "kind": "Image", "singular": "image", "plural": "images", "scope": "Cluster", "group": "image.openshift.io" }, { "kind": "ImageSignature", "singular": "imagesignature", "plural": "imagesignatures", "scope": "Cluster", "group": "image.openshift.io" }, { "kind": "ImageStreamImage", "singular": "imagestreamimage", "plural": "imagestreamimages", "scope": "Namespaced", "shortNames": ["isimage"], "group": "image.openshift.io" }, { "kind": "ImageStreamImport", "singular": "imagestreamimport", "plural": "imagestreamimports", "scope": "Namespaced", "group": "image.openshift.io" }, { "kind": "ImageStreamMapping", "singular": "imagestreammapping", "plural": "imagestreammappings", "scope": "Namespaced", "group": "image.openshift.io" }, { "kind": "ImageStream", "singular": "imagestream", "plural": "imagestreams", "scope": "Namespaced", "shortNames": ["is"], "group": "image.openshift.io" }, { "kind": "ImageStreamTag", "singular": "imagestreamtag", "plural": "imagestreamtags", "scope": "Namespaced", "shortNames": ["istag"], "group": "image.openshift.io" }, { "kind": "ImageTag", "singular": "imagetag", "plural": "imagetags", "scope": "Namespaced", "shortNames": ["itag"], "group": "image.openshift.io" }, { "kind": "Config", "singular": "config", "plural": "configs", "scope": "Cluster", "group": "imageregistry.operator.openshift.io" }, { "kind": "ImagePruner", "singular": "imagepruner", "plural": "imagepruners", "scope": "Cluster", "group": "imageregistry.operator.openshift.io" }, { "kind": "DNSRecord", "singular": "dnsrecord", "plural": "dnsrecords", "scope": "Namespaced", "group": "ingress.operator.openshift.io" }, { "kind": "NetworkAttachmentDefinition", "singular": "network-attachment-definition", "plural": "network-attachment-definitions", "scope": "Namespaced", "shortNames": ["net-attach-def"], "group": "k8s.cni.cncf.io" }, { "kind": "MachineHealthCheck", "singular": "machinehealthcheck", "plural": "machinehealthchecks", "scope": "Namespaced", "shortNames": ["mhc", "mhcs"], "group": "machine.openshift.io" }, { "kind": "Machine", "singular": "machine", "plural": "machines", "scope": "Namespaced", "group": "machine.openshift.io" }, { "kind": "MachineSet", "singular": "machineset", "plural": "machinesets", "scope": "Namespaced", "group": "machine.openshift.io" }, { "kind": "ContainerRuntimeConfig", "singular": "containerruntimeconfig", "plural": "containerruntimeconfigs", "scope": "Cluster", "shortNames": ["ctrcfg"], "group": "machineconfiguration.openshift.io" }, { "kind": "ControllerConfig", "singular": "controllerconfig", "plural": "controllerconfigs", "scope": "Cluster", "group": "machineconfiguration.openshift.io" }, { "kind": "KubeletConfig", "singular": "kubeletconfig", "plural": "kubeletconfigs", "scope": "Cluster", "group": "machineconfiguration.openshift.io" }, { "kind": "MachineConfigPool", "singular": "machineconfigpool", "plural": "machineconfigpools", "scope": "Cluster", "shortNames": ["mcp"], "group": "machineconfiguration.openshift.io" }, { "kind": "MachineConfig", "singular": "machineconfig", "plural": "machineconfigs", "scope": "Cluster", "shortNames": ["mc"], "group": "machineconfiguration.openshift.io" }, { "kind": "BareMetalHost", "singular": "baremetalhost", "plural": "baremetalhosts", "scope": "Namespaced", "shortNames": ["bmh", "bmhost"], "group": "metal3.io" }, { "kind": "Provisioning", "singular": "provisioning", "plural": "provisionings", "scope": "Cluster", "group": "metal3.io" }, { "kind": "NodeMetrics", "singular": "node", "plural": "nodes", "scope": "Cluster", "group": "metrics.k8s.io" }, { "kind": "PodMetrics", "singular": "pod", "plural": "pods", "scope": "Namespaced", "group": "metrics.k8s.io" }, { "kind": "StorageState", "singular": "storagestate", "plural": "storagestates", "scope": "Cluster", "group": "migration.k8s.io" }, { "kind": "StorageVersionMigration", "singular": "storageversionmigration", "plural": "storageversionmigrations", "scope": "Cluster", "group": "migration.k8s.io" }, { "kind": "AlertmanagerConfig", "singular": "alertmanagerconfig", "plural": "alertmanagerconfigs", "scope": "Namespaced", "group": "monitoring.coreos.com" }, { "kind": "Alertmanager", "singular": "alertmanager", "plural": "alertmanagers", "scope": "Namespaced", "group": "monitoring.coreos.com" }, { "kind": "PodMonitor", "singular": "podmonitor", "plural": "podmonitors", "scope": "Namespaced", "group": "monitoring.coreos.com" }, { "kind": "Probe", "singular": "probe", "plural": "probes", "scope": "Namespaced", "group": "monitoring.coreos.com" }, { "kind": "Prometheus", "singular": "prometheuse", "plural": "prometheuses", "scope": "Namespaced", "group": "monitoring.coreos.com" }, { "kind": "PrometheusRule", "singular": "prometheusrule", "plural": "prometheusrules", "scope": "Namespaced", "group": "monitoring.coreos.com" }, { "kind": "ServiceMonitor", "singular": "servicemonitor", "plural": "servicemonitors", "scope": "Namespaced", "group": "monitoring.coreos.com" }, { "kind": "ThanosRuler", "singular": "thanosruler", "plural": "thanosrulers", "scope": "Namespaced", "group": "monitoring.coreos.com" }, { "kind": "ClusterNetwork", "singular": "clusternetwork", "plural": "clusternetworks", "scope": "Cluster", "group": "network.openshift.io" }, { "kind": "EgressNetworkPolicy", "singular": "egressnetworkpolicie", "plural": "egressnetworkpolicies", "scope": "Namespaced", "group": "network.openshift.io" }, { "kind": "HostSubnet", "singular": "hostsubnet", "plural": "hostsubnets", "scope": "Cluster", "group": "network.openshift.io" }, { "kind": "NetNamespace", "singular": "netnamespace", "plural": "netnamespaces", "scope": "Cluster", "group": "network.openshift.io" }, { "kind": "EgressRouter", "singular": "egressrouter", "plural": "egressrouters", "scope": "Namespaced", "group": "network.operator.openshift.io" }, { "kind": "OperatorPKI", "singular": "operatorpki", "plural": "operatorpkis", "scope": "Namespaced", "group": "network.operator.openshift.io" }, { "kind": "IngressClass", "singular": "ingressclasse", "plural": "ingressclasses", "scope": "Cluster", "group": "networking.k8s.io" }, { "kind": "Ingress", "singular": "ingresse", "plural": "ingresses", "scope": "Namespaced", "shortNames": ["ing"], "group": "networking.k8s.io" }, { "kind": "NetworkPolicy", "singular": "networkpolicie", "plural": "networkpolicies", "scope": "Namespaced", "shortNames": ["netpol"], "group": "networking.k8s.io" }, { "kind": "RuntimeClass", "singular": "runtimeclasse", "plural": "runtimeclasses", "scope": "Cluster", "group": "node.k8s.io" }, { "kind": "OAuthAccessToken", "singular": "oauthaccesstoken", "plural": "oauthaccesstokens", "scope": "Cluster", "group": "oauth.openshift.io" }, { "kind": "OAuthAuthorizeToken", "singular": "oauthauthorizetoken", "plural": "oauthauthorizetokens", "scope": "Cluster", "group": "oauth.openshift.io" }, { "kind": "OAuthClientAuthorization", "singular": "oauthclientauthorization", "plural": "oauthclientauthorizations", "scope": "Cluster", "group": "oauth.openshift.io" }, { "kind": "OAuthClient", "singular": "oauthclient", "plural": "oauthclients", "scope": "Cluster", "group": "oauth.openshift.io" }, { "kind": "TokenReview", "singular": "tokenreview", "plural": "tokenreviews", "scope": "Cluster", "group": "oauth.openshift.io" }, { "kind": "UserOAuthAccessToken", "singular": "useroauthaccesstoken", "plural": "useroauthaccesstokens", "scope": "Cluster", "group": "oauth.openshift.io" }, { "kind": "Authentication", "singular": "authentication", "plural": "authentications", "scope": "Cluster", "group": "operator.openshift.io" }, { "kind": "CloudCredential", "singular": "cloudcredential", "plural": "cloudcredentials", "scope": "Cluster", "group": "operator.openshift.io" }, { "kind": "ClusterCSIDriver", "singular": "clustercsidriver", "plural": "clustercsidrivers", "scope": "Cluster", "group": "operator.openshift.io" }, { "kind": "Config", "singular": "config", "plural": "configs", "scope": "Cluster", "group": "operator.openshift.io" }, { "kind": "Console", "singular": "console", "plural": "consoles", "scope": "Cluster", "group": "operator.openshift.io" }, { "kind": "CSISnapshotController", "singular": "csisnapshotcontroller", "plural": "csisnapshotcontrollers", "scope": "Cluster", "group": "operator.openshift.io" }, { "kind": "DNS", "singular": "dnse", "plural": "dnses", "scope": "Cluster", "group": "operator.openshift.io" }, { "kind": "Etcd", "singular": "etcd", "plural": "etcds", "scope": "Cluster", "group": "operator.openshift.io" }, { "kind": "ImageContentSourcePolicy", "singular": "imagecontentsourcepolicie", "plural": "imagecontentsourcepolicies", "scope": "Cluster", "group": "operator.openshift.io" }, { "kind": "IngressController", "singular": "ingresscontroller", "plural": "ingresscontrollers", "scope": "Namespaced", "group": "operator.openshift.io" }, { "kind": "KubeAPIServer", "singular": "kubeapiserver", "plural": "kubeapiservers", "scope": "Cluster", "group": "operator.openshift.io" }, { "kind": "KubeControllerManager", "singular": "kubecontrollermanager", "plural": "kubecontrollermanagers", "scope": "Cluster", "group": "operator.openshift.io" }, { "kind": "KubeScheduler", "singular": "kubescheduler", "plural": "kubeschedulers", "scope": "Cluster", "group": "operator.openshift.io" }, { "kind": "KubeStorageVersionMigrator", "singular": "kubestorageversionmigrator", "plural": "kubestorageversionmigrators", "scope": "Cluster", "group": "operator.openshift.io" }, { "kind": "Network", "singular": "network", "plural": "networks", "scope": "Cluster", "group": "operator.openshift.io" }, { "kind": "OpenShiftAPIServer", "singular": "openshiftapiserver", "plural": "openshiftapiservers", "scope": "Cluster", "group": "operator.openshift.io" }, { "kind": "OpenShiftControllerManager", "singular": "openshiftcontrollermanager", "plural": "openshiftcontrollermanagers", "scope": "Cluster", "group": "operator.openshift.io" }, { "kind": "ServiceCA", "singular": "serviceca", "plural": "servicecas", "scope": "Cluster", "group": "operator.openshift.io" }, { "kind": "Storage", "singular": "storage", "plural": "storages", "scope": "Cluster", "group": "operator.openshift.io" }, { "kind": "CatalogSource", "singular": "catalogsource", "plural": "catalogsources", "scope": "Namespaced", "shortNames": ["catsrc"], "group": "operators.coreos.com" }, { "kind": "ClusterServiceVersion", "singular": "clusterserviceversion", "plural": "clusterserviceversions", "scope": "Namespaced", "shortNames": ["csv", "csvs"], "group": "operators.coreos.com" }, { "kind": "InstallPlan", "singular": "installplan", "plural": "installplans", "scope": "Namespaced", "shortNames": ["ip"], "group": "operators.coreos.com" }, { "kind": "OperatorCondition", "singular": "operatorcondition", "plural": "operatorconditions", "scope": "Namespaced", "shortNames": ["condition"], "group": "operators.coreos.com" }, { "kind": "OperatorGroup", "singular": "operatorgroup", "plural": "operatorgroups", "scope": "Namespaced", "shortNames": ["og"], "group": "operators.coreos.com" }, { "kind": "Operator", "singular": "operator", "plural": "operators", "scope": "Cluster", "group": "operators.coreos.com" }, { "kind": "Subscription", "singular": "subscription", "plural": "subscriptions", "scope": "Namespaced", "shortNames": ["sub", "subs"], "group": "operators.coreos.com" }, { "kind": "PackageManifest", "singular": "packagemanifest", "plural": "packagemanifests", "scope": "Namespaced", "group": "packages.operators.coreos.com" }, { "kind": "PodDisruptionBudget", "singular": "poddisruptionbudget", "plural": "poddisruptionbudgets", "scope": "Namespaced", "shortNames": ["pdb"], "group": "policy" }, { "kind": "PodSecurityPolicy", "singular": "podsecuritypolicie", "plural": "podsecuritypolicies", "scope": "Cluster", "shortNames": ["psp"], "group": "policy" }, { "kind": "ProjectRequest", "singular": "projectrequest", "plural": "projectrequests", "scope": "Cluster", "group": "project.openshift.io" }, { "kind": "Project", "singular": "project", "plural": "projects", "scope": "Cluster", "group": "project.openshift.io" }, { "kind": "AppliedClusterResourceQuota", "singular": "appliedclusterresourcequota", "plural": "appliedclusterresourcequotas", "scope": "Namespaced", "group": "quota.openshift.io" }, { "kind": "ClusterResourceQuota", "singular": "clusterresourcequota", "plural": "clusterresourcequotas", "scope": "Cluster", "shortNames": ["clusterquota"], "group": "quota.openshift.io" }, { "kind": "ClusterRoleBinding", "singular": "clusterrolebinding", "plural": "clusterrolebindings", "scope": "Cluster", "group": "rbac.authorization.k8s.io" }, { "kind": "ClusterRole", "singular": "clusterrole", "plural": "clusterroles", "scope": "Cluster", "group": "rbac.authorization.k8s.io" }, { "kind": "RoleBinding", "singular": "rolebinding", "plural": "rolebindings", "scope": "Namespaced", "group": "rbac.authorization.k8s.io" }, { "kind": "Role", "singular": "role", "plural": "roles", "scope": "Namespaced", "group": "rbac.authorization.k8s.io" }, { "kind": "Route", "singular": "route", "plural": "routes", "scope": "Namespaced", "group": "route.openshift.io" }, { "kind": "Config", "singular": "config", "plural": "configs", "scope": "Cluster", "group": "samples.operator.openshift.io" }, { "kind": "PriorityClass", "singular": "priorityclasse", "plural": "priorityclasses", "scope": "Cluster", "shortNames": ["pc"], "group": "scheduling.k8s.io" }, { "kind": "RangeAllocation", "singular": "rangeallocation", "plural": "rangeallocations", "scope": "Cluster", "group": "security.internal.openshift.io" }, { "kind": "PodSecurityPolicyReview", "singular": "podsecuritypolicyreview", "plural": "podsecuritypolicyreviews", "scope": "Namespaced", "group": "security.openshift.io" }, { "kind": "PodSecurityPolicySelfSubjectReview", "singular": "podsecuritypolicyselfsubjectreview", "plural": "podsecuritypolicyselfsubjectreviews", "scope": "Namespaced", "group": "security.openshift.io" }, { "kind": "PodSecurityPolicySubjectReview", "singular": "podsecuritypolicysubjectreview", "plural": "podsecuritypolicysubjectreviews", "scope": "Namespaced", "group": "security.openshift.io" }, { "kind": "RangeAllocation", "singular": "rangeallocation", "plural": "rangeallocations", "scope": "Cluster", "group": "security.openshift.io" }, { "kind": "SecurityContextConstraints", "singular": "securitycontextconstraint", "plural": "securitycontextconstraints", "scope": "Cluster", "shortNames": ["scc"], "group": "security.openshift.io" }, { "kind": "VolumeSnapshotClass", "singular": "volumesnapshotclasse", "plural": "volumesnapshotclasses", "scope": "Cluster", "group": "snapshot.storage.k8s.io" }, { "kind": "VolumeSnapshotContent", "singular": "volumesnapshotcontent", "plural": "volumesnapshotcontents", "scope": "Cluster", "group": "snapshot.storage.k8s.io" }, { "kind": "VolumeSnapshot", "singular": "volumesnapshot", "plural": "volumesnapshots", "scope": "Namespaced", "group": "snapshot.storage.k8s.io" }, { "kind": "CSIDriver", "singular": "csidriver", "plural": "csidrivers", "scope": "Cluster", "group": "storage.k8s.io" }, { "kind": "CSINode", "singular": "csinode", "plural": "csinodes", "scope": "Cluster", "group": "storage.k8s.io" }, { "kind": "CSIStorageCapacity", "singular": "csistoragecapacitie", "plural": "csistoragecapacities", "scope": "Namespaced", "group": "storage.k8s.io" }, { "kind": "StorageClass", "singular": "storageclasse", "plural": "storageclasses", "scope": "Cluster", "shortNames": ["sc"], "group": "storage.k8s.io" }, { "kind": "VolumeAttachment", "singular": "volumeattachment", "plural": "volumeattachments", "scope": "Cluster", "group": "storage.k8s.io" }, { "kind": "BrokerTemplateInstance", "singular": "brokertemplateinstance", "plural": "brokertemplateinstances", "scope": "Cluster", "group": "template.openshift.io" }, { "kind": "Template", "singular": "processedtemplate", "plural": "processedtemplates", "scope": "Namespaced", "group": "template.openshift.io" }, { "kind": "TemplateInstance", "singular": "templateinstance", "plural": "templateinstances", "scope": "Namespaced", "group": "template.openshift.io" }, { "kind": "Template", "singular": "template", "plural": "templates", "scope": "Namespaced", "group": "template.openshift.io" }, { "kind": "Profile", "singular": "profile", "plural": "profiles", "scope": "Namespaced", "group": "tuned.openshift.io" }, { "kind": "Tuned", "singular": "tuned", "plural": "tuneds", "scope": "Namespaced", "group": "tuned.openshift.io" }, { "kind": "Group", "singular": "group", "plural": "groups", "scope": "Cluster", "group": "user.openshift.io" }, { "kind": "Identity", "singular": "identitie", "plural": "identities", "scope": "Cluster", "group": "user.openshift.io" }, { "kind": "UserIdentityMapping", "singular": "useridentitymapping", "plural": "useridentitymappings", "scope": "Cluster", "group": "user.openshift.io" }, { "kind": "User", "singular": "user", "plural": "users", "scope": "Cluster", "group": "user.openshift.io" }, { "kind": "IPPool", "singular": "ippool", "plural": "ippools", "scope": "Namespaced", "group": "whereabouts.cni.cncf.io" }, { "kind": "OverlappingRangeIPReservation", "singular": "overlappingrangeipreservation", "plural": "overlappingrangeipreservations", "scope": "Namespaced", "group": "whereabouts.cni.cncf.io" }, { "kind": "CephBlockPool", "singular": "cephblockpool", "plural": "cephblockpools", "scope": "Namespaced", "group": "ceph.rook.io" }, { "kind": "CephClient", "singular": "cephclient", "plural": "cephclients", "scope": "Namespaced", "group": "ceph.rook.io" }, { "kind": "CephCluster", "singular": "cephcluster", "plural": "cephclusters", "scope": "Namespaced", "group": "ceph.rook.io" }, { "kind": "CephFilesystemMirror", "singular": "cephfilesystemmirror", "plural": "cephfilesystemmirrors", "scope": "Namespaced", "group": "ceph.rook.io" }, { "kind": "CephFilesystem", "singular": "cephfilesystem", "plural": "cephfilesystems", "scope": "Namespaced", "group": "ceph.rook.io" }, { "kind": "CephNFS", "singular": "cephnfse", "plural": "cephnfses", "scope": "Namespaced", "shortNames": ["nfs"], "group": "ceph.rook.io" }, { "kind": "CephObjectRealm", "singular": "cephobjectrealm", "plural": "cephobjectrealms", "scope": "Namespaced", "group": "ceph.rook.io" }, { "kind": "CephObjectStore", "singular": "cephobjectstore", "plural": "cephobjectstores", "scope": "Namespaced", "group": "ceph.rook.io" }, { "kind": "CephObjectStoreUser", "singular": "cephobjectstoreuser", "plural": "cephobjectstoreusers", "scope": "Namespaced", "shortNames": ["rcou", "objectuser"], "group": "ceph.rook.io" }, { "kind": "CephObjectZoneGroup", "singular": "cephobjectzonegroup", "plural": "cephobjectzonegroups", "scope": "Namespaced", "group": "ceph.rook.io" }, { "kind": "CephObjectZone", "singular": "cephobjectzone", "plural": "cephobjectzones", "scope": "Namespaced", "group": "ceph.rook.io" }, { "kind": "CephRBDMirror", "singular": "cephrbdmirror", "plural": "cephrbdmirrors", "scope": "Namespaced", "group": "ceph.rook.io" }, # { # "kind": "", # "singular": "", # "plural": "", # "scope": "", # "shortNames": [], # "group": "" # }, ] # RDEFS Generated by the following script: """ #!/bin/bash while read apiresline; do cols=$(echo ${apiresline} | tr -s ' ' | tr ' ' '\n' | wc -l) name=$(echo ${apiresline} | awk '{print $1}') if [ "${cols}" == "4" ]; then short="" api=$(echo ${apiresline} | awk '{print $2}') nsed=$(echo ${apiresline} | awk '{print $3}') kind=$(echo ${apiresline} | awk '{print $4}') elif [ "${cols}" == "5" ]; then short=$(echo ${apiresline} | awk '{print $2}') api=$(echo ${apiresline} | awk '{print $3}') nsed=$(echo ${apiresline} | awk '{print $4}') kind=$(echo ${apiresline} | awk '{print $5}') else echo "WARNING: Invalid line: ${apiresline}" continue fi sing=$(echo "${name}" | sed 's/s$//') if [ "${nsed}" == "true" ]; then scope="Namespaced" else scope="Cluster" fi if [[ "{$api}" == *"/"* ]]; then group=$(echo ${api} | cut -d '/' -f 1) apiver=$(echo ${api} | cut -d '/' -f 2) else group="core" apiver=${api} fi if [ -n "${short}" ]; then shortNames='[' for sn in $(echo ${short} | tr ',' '\n'); do shortNames="${shortNames}\"${sn}\", " done shortNames=$(echo ${shortNames} | sed 's/,$/]/') else shortNames="" fi if [ -n "${shortNames}" ]; then cat <, 'yfile_ts': <>, rdef}, ...] res: k8 resource yfile_ts: timestamp of the yaml file from which the resource was loaded (used for age calculation) rdef: resrouce definition of the resource """ lg.debug("FUNC_INIT: {}".format(locals())) ydata = load_yaml(yfile) if not _is_valid_k8_res(ydata): raise InvalidResource( "Resource loaded from {} is not valid".format(yfile)) lg.debug("ydata.keys(): {}".format(ydata.keys())) yfile_ts = getmtime(yfile) lg.debug("Yaml file's timestamp: {}".format(yfile_ts)) kind = dget(rdef, ["kind"]) res = [] # List in yaml (kind: List) if "items" in ydata: lg.debug("'items' in ydata (we got a list)") lg.debug("len of items: {}".format(len(ydata["items"] or []))) if ydata["items"] is not None and len(ydata["items"]) > 0: res.extend( [ {"res": r, "yfile_ts": yfile_ts, "rdef": rdef} for r in ydata["items"] if kind is None or ("kind" in r and r["kind"] == kind) ]) # else: # lg.warning("No items in yaml file {}, skipping".format(yfile)) # Single resource in yaml elif "metadata" in ydata: lg.debug("'metadata' in ydata (we got a single item)") lg.debug("ydata.keys(): {}".format(ydata.keys())) if kind is None or ("kind" in ydata and ydata["kind"] == kind): res.extend([{"res": ydata, "yfile_ts": yfile_ts, "rdef": rdef}]) else: lg.warning("Yaml file {} didnt contain kind {}".format(yfile, kind)) else: raise InvalidResource( "Invalid yaml file {}. Didn't get 'items' or 'metadata'".format(yfile)) lg.debug("resources loaded length: {}".format(len(res))) lg.trace("res: {}".format(res)) return res def load_res(path, r_type, r_name=None, ns=None): """Load specific resource type from a must-gather path This function first calls locate yamls to locate the yamls of the r_type object. Then it calls load_res_from_yaml to load the k8 resources from these yamls. Finally it filters for r_name if is not None, and returns the array. Args: path (str): Absolute must-gather path r_type (str): Resource type e.g, pod, node. r_name (list[str], optional): Resource names to filter. All names are returned if None (Default). ns (str): Namespace if the the object is namespace scoped. If the r_type is ns-scoped but ns is None, we use Config().project '_all' would mean all namespaces. Ignored for cluster scoped resource types. Returns: list[dict]: list of dictionary [ {'res': <>, 'yfile_ts': <>, rdef}, ...] res: k8 resource yfile_ts: timestamp of the yaml file from which the resource was loaded (used for age calculation) rdef: resrouce definition of the resource """ lg.debug("FUNC_INIT: {}".format(locals())) rdef, yamls = locate_yamls(path, r_type, ns=ns) lg.debug("Found {} yamls".format(len(yamls))) # Load resources from these yamls and save in res # after filtering names if r_name is set res = [] # total counters t_matched = 0 t_not_matched = 0 for y in yamls: # per yaml counters matched = 0 not_matched = 0 # Handling Partial namespace directory with missing yaml if ( dget(rdef, ["kind"]) == "Namespace" and type(y) is dict and dget(y, ["yaml_missing"]) ): ns_name = dget(y, ["yaml_missing"]) res_yd = [{ "res": { "apiVersion": "v1", "kind": "Namespace", "metadata": { "name": ns_name } } }] else: try: res_yd = load_res_from_yaml(y, rdef) except InvalidResource as e: lg.warning(e) continue if not r_name: # res name is not set, get all from yaml lg.debug("Matching all resource names") matched += len(res_yd) t_matched += matched res.extend(res_yd) else: # res name is set, filter name from yaml lg.debug("Matching resources with name: {}".format(r_name)) for r in res_yd: if ( "res" in r and "metadata" in r["res"] and "name" in r["res"]["metadata"] and r["res"]["metadata"]["name"] in r_name ): matched += 1 res.append(r) else: not_matched += 1 t_matched += matched t_not_matched += not_matched lg.info("{}/{} from yaml file: {}".format(matched, matched+not_matched, y)) return res ================================================ FILE: omg/must_gather/locate_yamls.py ================================================ """ locate_yamls.py This module helps in locating yaml files as we expect them to be in a must-gather. We don't look whats inside. Simply return the paths to relevant yaml files for a specific resource type. The main function is locate_yamls. It uses locate_project if resource type is project. yaml files are located calculated as per following pattern: / [namespaces|cluster-scoped-resources]/ group/ [plural.yaml | plural/*.yaml] _detect_yamls "detects" if plural.yaml is present or plural/*.yaml """ from os.path import join, isdir, isfile from os import listdir from loguru import logger as lg from omg.must_gather.get_rdef import get_rdef from omg.must_gather.exceptions import UnkownResourceType, NameSpaceRequired def _detect_yamls(path, plural): """Detects if yaml file(s) are present as plural.yaml or plural/*.yaml. First priority is given to plural.yaml and if its not present, plural/*.yaml files are scanned. TODO: Ensure this order is correct Args: path (str): Path where yaml needs to be detected plural (str): Plural name of the resrouce we are detecting Returns: list[str]: List of yaml paths that were detected Returns None if none were detected """ lg.debug("FUNC_INIT: {}".format(locals())) # potential yaml file pot_y = join(path, plural+".yaml") # potential yaml dir pot_d = join(path, plural) if isfile(pot_y): lg.debug("detected yaml file: {}".format(pot_y)) return [pot_y] if isdir(pot_d): lg.debug("detected yaml dir {}".format(pot_d)) y_in_d = [join(pot_d, y) for y in listdir(pot_d) if y.endswith(".yaml")] lg.debug("{} yamls found".format(len(y_in_d))) lg.trace("yamls_in_dir: {}".format(y_in_d)) return y_in_d return None def locate_project(path, tell): """Special function to locate project yamls project yamls are present in must-gather/namespaces//.yaml, unlike for other res_types, project type needs separate/special function to locate the yamls. This function can return yamls, paths or just the project names. depending on what is asked in arg tell="" Args: path (str)): Absolute must-gather path tell (str): What to tell/return? Possible options are: "yamls": yaml files of the projects "paths": paths of project directories "names": names of the projects present Returns: list: List of requested item (yamls/paths/names) """ lg.debug("FUNC_INIT: {}".format(locals())) result = [] lg.debug("Looking for projects in {}".format(path)) p_nss = join(path, "namespaces") if isdir(p_nss): lg.debug("Found namspaces in {}".format(path)) for proj in listdir(p_nss): p_nss_proj = join(p_nss, proj) if isdir(p_nss_proj): if tell == "names" and proj not in result: if proj not in result: result.append(proj) elif tell == "paths": result.append(p_nss_proj) elif tell == "yamls": p_nss_proj_y = join(p_nss_proj, proj+".yaml") if isfile(p_nss_proj_y): result.append(p_nss_proj_y) else: # ns dir exists but yaml is missing # we will append a special dict with ns name # instead of the path of the yaml result.append({"yaml_missing": proj}) else: raise ValueError("Invalid arg(tell): {}".format(tell)) lg.trace("result: {}".format(result)) return result def locate_yamls(path, r_type, ns=None): """Find yaml for a particular resource type in paths. Args: path (str): Absolute must-gather path r_type (str): Resource type e.g, pod, node. ns (str): Namespace. Required if r_type is namespace scoped. Value of '_all' denotes all namespaces. Ignored for cluster scoped resource types. Returns: dict, list: rdef and List of paths of yamls located in paths. """ lg.debug("FUNC_INIT: {}".format(locals())) yaml_paths = [] # r_type == project | namespace if r_type.lower() in ["project", "projects", "namespace", "ns"]: yaml_paths = locate_project(path, "yamls") rdef = { "kind": "Namespace", "group": "core", "singular": "namespace", "plugral": "namespaces" } # r_type != project else: rdef = get_rdef(r_type) if not rdef: raise UnkownResourceType("Unknown resource type: {}".format(r_type)) lg.debug("rdef: {}".format(rdef)) # kind = rdef["kind"] plural = rdef["plural"] group = rdef["group"] scope = rdef["scope"] if scope == "Namespaced": if not ns: raise NameSpaceRequired( "{} is Namespaced but ns/project is not set".format(r_type)) if ns == "_all": # all namespaces all_proj_paths = locate_project(path, tell="paths") for app in all_proj_paths: ymls = _detect_yamls(join(app, group), plural) if ymls: yaml_paths.extend(ymls) else: # specific ns ymls = _detect_yamls(join(path, "namespaces", ns, group), plural) if ymls: yaml_paths.extend(ymls) else: # scope == "Cluster" ymls = _detect_yamls(join(path, "cluster-scoped-resources", group), plural) if ymls: yaml_paths.extend(ymls) lg.trace("rdef: {}, yaml_paths: {}".format(rdef, yaml_paths)) return rdef, yaml_paths ================================================ FILE: omg/must_gather/scan_mg.py ================================================ import os from loguru import logger as lg from omg.must_gather.exceptions import NoValidMgFound def scan_mg(tdirs): """Scan directories for valid must-gather/inspect directories Args: tdirs (tuple[str]): Non-empty tuple of directory paths to scan Returns: list: List of valid (absolute) must-gather/inspect directories """ lg.debug("FUNC_INIT: {}".format(locals())) valid_dirs = [] for tdir in tdirs: vdirs = [] if os.path.isdir(tdir): scan_q = [tdir] while len(scan_q) > 0: lg.debug('scan_q: ' + str(scan_q)) wdir = scan_q.pop() subdirs = [d for d in os.listdir(wdir) if os.path.isdir(os.path.join(wdir, d))] if ("cluster-scoped-resources" in subdirs or "namespaces" in subdirs): lg.debug('Valid dir found: ' + str(wdir)) vdirs.append(os.path.abspath(wdir)) # if there are any other subdirs we will scan those as well try: subdirs.remove("cluster-scoped-resources") except ValueError: pass try: subdirs.remove("namespaces") except ValueError: pass for sd in subdirs: scan_q.append(os.path.join(wdir, sd)) # if namespaces/all/namespaces exists we will mark it valid as well if os.path.isdir(os.path.join(wdir, "namespaces", "all", "namespaces")): vdirs.append(os.path.abspath(os.path.join(wdir, "namespaces", "all"))) else: lg.debug('Not valid dir scanning deeper: ' + str(wdir)) scan_q.extend([os.path.join(wdir, d) for d in subdirs]) if vdirs: valid_dirs.extend(vdirs) else: lg.warning('Not a valid must-gather: ' + str(tdir)) if len(valid_dirs) > 0: lg.debug("valid_dirs: {}".format(valid_dirs)) try: # Put the primary must-gather path on top of the paths list # Optional but good to do in multidir mode pmgs = [ pmg for pmg in valid_dirs if "quay-io-openshift-release-dev-ocp-v4-0-art-dev-sha256" in pmg ] lg.debug("primary mgs: {}".format(pmgs)) if len(pmgs) > 1: lg.warning("Multiple primary must-gather directories selected") # if not pmgs: # lg.warning("No primary must-gather directory selected") for pmg in pmgs: valid_dirs.insert( 0, valid_dirs.pop( valid_dirs.index(pmg) ) ) except Exception: pass return valid_dirs else: raise NoValidMgFound("No valid must-gather(s) found!") ================================================ FILE: omg/project/__init__.py ================================================ ================================================ FILE: omg/project/complete.py ================================================ from omg.must_gather.locate_yamls import locate_project from omg.config import config from omg.utils.dget import dget from loguru import logger as lg def complete_projects(ctx, args, incomplete): """ Callback for project name autocompletion :return: List of matching namespace names or empty list. """ lg.remove() def _get_all_projects(): cfg = config.get() c_paths = dget(cfg, ["paths"]) if c_paths: projects = [] for path in c_paths: projects.extend(locate_project(path, tell="names")) return projects return [] if incomplete is not None: projects = _get_all_projects() suggestions = [ns for ns in projects if ns.startswith(incomplete)] return suggestions return [] ================================================ FILE: omg/project/project.py ================================================ from loguru import logger as lg from omg.config import config from omg.utils.dget import dget from omg.must_gather.locate_yamls import locate_project def cmd(name): cfg = config.get() c_paths = dget(cfg, ["paths"]) c_project = dget(cfg, ["project"]) # print current project if name is None: if c_project is None: print("No project selected") else: print("Using project {}".format(c_project)) # set current project else: if name == c_project: print("Already using project {}".format(c_project)) else: select_project = None for path in c_paths: projs_in_path = locate_project(path, tell="names") if name in projs_in_path: select_project = name break if select_project: print("Now using project {}".format(select_project)) config.save(project=name) else: lg.error("Project {} not found in {} must-gather paths".format( name, len(c_paths))) ================================================ FILE: omg/project/projects.py ================================================ from loguru import logger as lg from omg.config import config from omg.utils.dget import dget from omg.must_gather.locate_yamls import locate_project def cmd(): lg.debug("FUNC_INIT: {}".format(locals())) cfg = config.get() c_paths = dget(cfg, ["paths"]) c_project = dget(cfg, ["project"]) if c_paths: for path in c_paths: projs_in_path = locate_project(path, tell="names") print("{} projects in {}".format( len(projs_in_path), path)) print("") print("Selected project: {}".format(c_project)) ================================================ FILE: omg/show/__init__.py ================================================ ================================================ FILE: omg/use/__init__.py ================================================ ================================================ FILE: omg/use/show_mg_info.py ================================================ import re from loguru import logger as lg from omg.config import config from omg.must_gather.load_resources import load_res from omg.must_gather.locate_yamls import locate_project from omg.utils.dget import dget def _hide_hash(path): """Hide the image hash in the path for better readability.""" return re.sub("sha256-[a-z0-9]*", "sha256*", path) def _show_info(path): out = lg.opt(colors=True).success proj_count = len(locate_project(path, "yamls")) out(" Projects: {}".format(proj_count)) try: infra = load_res(path, "infrastructure") if infra: api_url = [ dget(i, ["res", "status", "apiServerURL"]) for i in infra ] platform = [ dget(i, ["res", "status", "platform"]) for i in infra ] out(" API URL: {}".format(api_url)) out(" Platform: {}".format(platform)) c_ver = load_res(path, "clusterversion") if c_ver: cluster_id = [ dget(cv, ["res", "spec", "clusterID"]) for cv in c_ver ] desired_v = [ dget(cv, ["res", "status", "desired", "version"]) for cv in c_ver ] out(" Cluster ID: {}".format(cluster_id)) out(" Desired Version: {}".format(desired_v)) out("") except Exception as e: lg.warning("Error loading cluster info: {}".format(e)) def show_mg_info(cfile=None): """ Shows the info of current selected must-gather(s) """ lg.debug("FUNC_INIT: {}".format(locals())) cfg = config.get(cfile=cfile) lg.debug("Loaded config file: {}".format(cfg)) paths = cfg["paths"] project = cfg["project"] out = lg.opt(colors=True).success if "cwd" in cfg and cfg["cwd"]: out("-=[CWD Mode]=-") out("") if len(paths) > 1: out("-=[MultiDir Mode]=-") out("") out("Selected must-gather paths:") i = 1 for path in paths: out(" [{}] {}".format(i, _hide_hash(path))) i = i + 1 _show_info(path) out("") out("Current Project: {}".format(project)) elif len(paths) == 1: out("Selected must-gather: {}".format(_hide_hash(paths[0]))) _show_info(paths[0]) out(" Current Project: {}".format(project)) ================================================ FILE: omg/use/use.py ================================================ from omg.must_gather.generate_rdefs import generate_rdefs from loguru import logger as lg from omg.config import config from omg.must_gather.exceptions import NoValidMgFound from omg.use.show_mg_info import show_mg_info from omg.must_gather.scan_mg import scan_mg def cmd(mg_paths=None, cwd=False, cfile=None): """Landing function for `omg use` Args: mg_paths (string, optional): Path to extracted must-gather. Defaults to None. cwd (bool, optional): --cwd flag. Defaults to False. Returns: int: return code 0/1 (success/failure) """ lg.debug(str(locals())) if not mg_paths: # --cwd if cwd: try: config.save(paths=['.'], cfile=cfile) except Exception as e: lg.error(e) return 1 else: lg.opt(colors=True).success( "[CWD Mode] Assuming your working directory as must-gather") return 0 # No args passed else: show_mg_info(cfile) return 0 else: # One or more dirs are passed via mg_paths, # scan and save the valid directories try: valid_mg_paths = scan_mg(mg_paths) except NoValidMgFound as e: lg.error(e) return 1 # Foce re-generate rdefs for all discovered paths for path in valid_mg_paths: try: generate_rdefs(path) except Exception: # lg.warning("Failed generating rdef for {}: {}".format(path, e)) pass # Save paths in config config.save(paths=valid_mg_paths, cfile=cfile) # Show selected must-gather paths to user show_mg_info(cfile) return 0 ================================================ FILE: omg/utils/__init__.py ================================================ ================================================ FILE: omg/utils/age.py ================================================ from datetime import datetime from dateutil.parser import parse from dateutil.relativedelta import relativedelta from loguru import logger as lg def age(ts1, ts2, ts1_type="iso", ts2_type="epoch"): """Calculate age of the objects This function is used to calculate age of the objects We compare the time reported in the yaml definition, with the timestamp of the yaml file (i.e, when it was generated). This should give us age of the object at the time of must-gather By default, ts1 is considered in iso-8601 e.g: '2020-06-04T22:10:41Z' and ts2 is considered in unix/epoch format e.g: 1590912494.0 (returned by os.path.getmtime) Args: ts1 (str): First timestamp ts2 (str): Second timestamp ts1_type (str, optional): Type of fist timestamp. Defaults to "iso". ts2_type (str, optional): Type of second timestamp. Defaults to "epoch". Returns: str: Human readable age e.g: 1d, 3m, 6h, 20s etc. Biggest unit is days (d) and smallest is (s) """ try: if ts1_type == "iso": if isinstance(ts1, datetime): ts1 = ts1.isoformat() dt1 = parse(ts1, ignoretz=True) elif ts1_type == "epoch": dt1 = datetime.utcfromtimestamp(ts1) if ts2_type == "iso": if isinstance(ts2, datetime): ts2 = ts2.isoformat() dt2 = parse(ts2, ignoretz=True) elif ts2_type == "epoch": dt2 = datetime.utcfromtimestamp(ts2) rd = relativedelta(dt2, dt1) except Exception as e: lg.debug("error parsing timestamps: {}".format(e)) return "Unknown" if rd.days > 0 or rd.months > 0 or rd.years > 0: days = int(rd.years * 365) + int(rd.months * 30) + int(rd.days) return str(days) + "d" elif rd.hours > 9: return str(rd.hours) + "h" elif rd.hours > 0 and rd.hours < 10: return str(rd.hours) + "h" + str(rd.minutes) + "m" elif rd.minutes > 9: return str(rd.minutes) + "m" elif rd.minutes > 0 and rd.minutes < 10: return str(rd.minutes) + "m" + str(rd.seconds) + "s" else: return str(rd.seconds) + "s" ================================================ FILE: omg/utils/dget.py ================================================ def dget(_dict, keys, default=None): """Safely get key values from nested dictionary Args: _dict (dict): Dictionary to get the key from keys (list): Iterable list of keys to get default (any optional): Value to return if key is missing. Defaults to None. Returns: any: Value found at the key or the default value if key is not found """ for key in keys: if isinstance(_dict, dict): _dict = _dict.get(key, default) else: return default return _dict ================================================ FILE: omg/utils/extract_labels.py ================================================ def extract_labels(obj): """Receives an object/resource and returns the labels in flat/string format. Helper function to print labels when --show-labels is passed Args: o (dict): object Returns: str: Labels in plain string e.g: "app=console,component=ui" Returns '' if 'labels' is absent in object -> metadata """ if "labels" in obj["metadata"]: try: lab = obj["metadata"]["labels"] l_str = ",".join(["%s=%s" % (k, v) for k, v in lab.items()]) return l_str except Exception: return "" else: return "" ================================================ FILE: omg/utils/load_json.py ================================================ import json from loguru import logger as lg def load_json(jfile): try: with open(jfile, "r") as j_f: j_d = j_f.read() j_data = json.loads(j_d) return j_data except Exception as e: lg.warning("Error loading json file ({}): {}".format(jfile, e)) return None ================================================ FILE: omg/utils/load_yaml.py ================================================ """ load_resources_from_yaml.py """ import yaml import os from loguru import logger as lg try: from yaml import CSafeLoader as SafeLoader except ImportError: lg.warning("yaml.CSafeLoader failed to load, using SafeLoader") from yaml import SafeLoader def load_yaml(yfile): """Load yaml file and return python object Args: yfile (str): Yaml file path Returns: (str|list|dict): Python object loaded from yaml """ lg.debug("yfile: {}".format(yfile)) if not os.path.isfile(yfile): raise Exception("File not found: {}".format(yfile)) ydata = None with open(yfile, "r") as y_f: lg.debug("Opened yaml file: " + yfile) y_d = y_f.read() try: ydata = yaml.load(y_d, Loader=SafeLoader) except (yaml.scanner.ScannerError, yaml.parser.ParserError): # yaml load/parse failed # try skipping lines from the bottom # Until we are able to load the yaml file # We will try until > 1 lines are left lines_total = y_d.count("\n") lines_skipped = 0 while y_d.count("\n") > 1: # skip last line y_d = y_d[:y_d.rfind("\n")] lines_skipped += 1 try: ydata = yaml.load(y_d, Loader=SafeLoader) except (yaml.scanner.ScannerError, yaml.parser.ParserError): pass else: lg.warning("Skipped " + str(lines_skipped) + "/" + str(lines_total) + " lines from the end of " + yfile + " to the load the yaml file properly") break lg.debug("yaml file loaded in ydata. type: " + str(type(ydata))) lg.trace("ydata: " + str(ydata)) # if not ydata: # raise Exception("Unable to load yaml file: {}".format(yfile)) return ydata ================================================ FILE: omg/utils/size.py ================================================ def num2human( num, form="{n:.2f} {u}B", factor=1024, unit_list=["", "K", "M", "G", "T", "P", "E", "Z", "Y"] ): for unit in unit_list: if factor > num or unit == unit_list[-1]: return form.format(n=num, u=unit) num /= factor ================================================ FILE: omg/whoami/__init__.py ================================================ ================================================ FILE: omg/whoami/whoami.py ================================================ def cmd(): print() print('You are awesome :)') print() ================================================ FILE: setup.cfg ================================================ [wheel] universal = 1 [metadata] description_file = README.md ================================================ FILE: setup.py ================================================ """ oc like tool that works with must-gather rather than OpenShift API """ from setuptools import find_packages, setup import omg #dependencies = ['tabulate', 'pyyaml', 'python-dateutil', 'cryptography>=2.5,<=3.3.2', 'click==7.1.2'] dependencies = ['tabulate', 'pyyaml', 'python-dateutil', 'cryptography>=2.5', 'click==8.0.1', 'loguru==0.6.0'] setup( name='o-must-gather', version=omg.version, url='https://github.com/kxr/o-must-gather', license='GPLv3', author='Khizer Naeem', author_email='khizernaeem@gmail.com', description='oc like tool that works with must-gather rather than OpenShift API', long_description=__doc__, packages=find_packages(), include_package_data=True, zip_safe=False, platforms='any', install_requires=dependencies, entry_points={ 'console_scripts': [ 'omg = omg.cli:cli', ], }, classifiers=[ # As from http://pypi.python.org/pypi?%3Aaction=list_classifiers 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: BSD License', 'Operating System :: POSIX', 'Operating System :: MacOS', 'Operating System :: Unix', 'Programming Language :: Python :: 3', 'Topic :: Utilities', ] ) ================================================ FILE: tests/__init__.py ================================================ ================================================ FILE: tests/conftest.py ================================================ import os import logging import pytest import tarfile from _pytest.logging import caplog as _caplog from loguru import logger _ = _caplog # to satisfy flake8 @pytest.fixture def caplog(_caplog): class PropogateHandler(logging.Handler): def emit(self, record): logging.getLogger(record.name).handle(record) handler_id = logger.add(PropogateHandler(), level=25, format="{message}") yield _caplog logger.remove(handler_id) @pytest.fixture def simple_must_gather(tmpdir): mg_tar = tarfile.open("samples/must-gather.46i.tgz") mg_tar.extractall(tmpdir) mg_tar.close() return os.path.join(tmpdir) @pytest.fixture def omgconfig(tmpdir): return os.path.join(str(tmpdir), ".omgconfig") ================================================ FILE: tests/dev_testing.py ================================================ from omg.config.logging import setup_logging from omg.must_gather.load_resources import load_res setup_logging("info") paths = [ '/home/knaeem/Desktop/mgs/must-gather.etism/registry-redhat-io-openshift-service-mesh-istio-must-gather-rhel7-sha256-b73931d591587f34e94fd79de84b557417b817616a04631e6c741268b47d9d05', '/home/knaeem/Desktop/mgs/must-gather.etism/quay-io-openshift-release-dev-ocp-v4-0-art-dev-sha256-2f3d142d13081954fc73e1d5e6ee96a04ba7c5714e9193f985d0a6962d325841' ] # config = Config() # config.paths = paths # config.project = "openshift-apiserver" res = load_res(paths, "configmap", ns="openshift-config") for r in res: rs = r["res"] print(rs["metadata"]["name"]) ================================================ FILE: tests/test_config.py ================================================ import pytest from omg.config import config from omg.config.logging import setup_logging setup_logging(loglevel="normal") def test_config_load_no_config(caplog): with pytest.raises(config.NoMgSelected): config._load_config("/non/exitent/file") def test_config_dump(tmpdir): dump_file = tmpdir.join("dump_file.txt") config._dump_config( {'testkey': 'testvalue'}, dump_file ) assert dump_file.read() == "testkey: testvalue\n" def test_config_get_no_config(caplog): with pytest.raises(SystemExit): config.get("/non/exitent/file") assert "You have not selected a must-gather" in caplog.text def test_config_save_get(tmpdir): omg_config = tmpdir.join(".omgconfig") config.save( paths=["/test/path"], project="testproject", cfile=omg_config ) cfg = config.get(cfile=omg_config) assert cfg["paths"] == ["/test/path"] assert cfg["project"] == "testproject" ================================================ FILE: tests/test_mg_ops.py ================================================ import pytest import os from omg.lib.mg_ops.locate_yamls import locate_yamls from omg.lib.mg_ops.scan_mg import scan_mg, NoValidMgFound from omg.config.logging import setup_logging setup_logging(loglevel="normal") def test_scan_mg_invalid(tmpdir): with pytest.raises(NoValidMgFound): scan_mg( (str(tmpdir),) ) def test_scan_mg_valid(simple_must_gather, omgconfig): paths = scan_mg( (str(simple_must_gather),) ) assert len(paths) == 1 for path in paths: assert os.path.isdir(path) assert ( os.path.isdir( os.path.join(path, "namespaces")) or os.path.isdir( os.path.join(path, "cluster-scoped-resources")) ) def test_locate_yamls(simple_must_gather): paths = scan_mg( (str(simple_must_gather),) ) kind, yamls = locate_yamls( paths=paths, r_type="infrastructure" ) assert kind == "Infrastructure" assert yamls == [ paths[0] + "/cluster-scoped-resources/config.openshift.io/infrastructures.yaml" ] ================================================ FILE: tests/test_use.py ================================================ import os import yaml from omg.use import use from omg.config.logging import setup_logging setup_logging(loglevel="normal") def test_use_invalid_paths(caplog): use.cmd( mg_paths=('/non/exitent/path',) ) assert "No valid must-gather(s) found in ('/non/exitent/path',)" in caplog.text def test_use_simple_must_gather(caplog, omgconfig, simple_must_gather): use.cmd( mg_paths=(simple_must_gather,), cfile=omgconfig ) with open(omgconfig, "r") as omgcfg: cfg = yaml.load(omgcfg.read(), Loader=yaml.SafeLoader) for path in cfg["paths"]: assert os.path.isdir(path) assert ( os.path.isdir( os.path.join(path, "namespaces")) or os.path.isdir( os.path.join(path, "cluster-scoped-resources")) ) assert "quay-io-openshift-release-dev-ocp-v4-0-art-dev-sha256*" in caplog.text assert "Cluster API URL: ['https://api.ocp46.v.kxr.me:6443']" in caplog.text assert "Cluster Platform: ['VSphere']" in caplog.text assert "Cluster ID: ['51611b91-5e45-4246-8b64-b3da2ed6ad22']" in caplog.text assert "Desired Version: ['4.6.16']" in caplog.text # TODO: test_use_multidir_must_gather def test_use_cwd(caplog, omgconfig): use.cmd( cwd=True, cfile=omgconfig ) assert "[CWD Mode] Assuming your working directory as must-gather" in caplog.text with open(omgconfig, "r") as omgcfg: assert omgcfg.read() == "paths:\n- .\nproject: null\n"